From 642a5fe6cc152eb198398f22c10dec0bd46f7c7f Mon Sep 17 00:00:00 2001 From: xtqqczze Date: Mon, 27 Jul 2020 20:14:16 +0100 Subject: [PATCH 1/3] Update Test.Common.props --- test/Test.Common.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Test.Common.props b/test/Test.Common.props index 777680552a4..85876cbf796 100644 --- a/test/Test.Common.props +++ b/test/Test.Common.props @@ -5,7 +5,7 @@ (c) Microsoft Corporation. netcoreapp5.0 - 8.0 + preview true true From 1cedbac1d1405be1edb3dce12b0167e407fee8a0 Mon Sep 17 00:00:00 2001 From: xtqqczze Date: Thu, 30 Jul 2020 14:33:41 +0100 Subject: [PATCH 2/3] `!= null` -> `is not null` --- .../CimAsyncOperation.cs | 6 +- .../CimBaseAction.cs | 2 +- .../CimCommandBase.cs | 10 +- .../CimGetAssociatedInstance.cs | 2 +- .../CimGetInstance.cs | 14 +- .../CimIndicationWatcher.cs | 10 +- .../CimInvokeCimMethod.cs | 18 +- .../CimNewCimInstance.cs | 6 +- .../CimRegisterCimIndication.cs | 14 +- .../CimRemoveCimInstance.cs | 4 +- .../CimResultObserver.cs | 6 +- .../CimSessionOperations.cs | 14 +- .../CimSessionProxy.cs | 70 +-- .../CimSetCimInstance.cs | 6 +- .../CimWriteError.cs | 22 +- .../CmdletOperation.cs | 2 +- .../GetCimAssociatedInstanceCommand.cs | 2 +- .../GetCimClassCommand.cs | 2 +- .../GetCimInstanceCommand.cs | 2 +- .../InvokeCimMethodCommand.cs | 2 +- .../NewCimInstanceCommand.cs | 8 +- .../NewCimSessionCommand.cs | 20 +- .../NewCimSessionOptionCommand.cs | 10 +- .../RegisterCimIndicationCommand.cs | 6 +- .../RemoveCimInstanceCommand.cs | 2 +- .../SetCimInstanceCommand.cs | 2 +- .../Utils.cs | 6 +- .../HelpWindow/HelpParagraphBuilder.cs | 36 +- .../HelpWindow/HelpViewModel.cs | 6 +- .../HelpWindow/ParagraphBuilder.cs | 2 +- .../HelpWindow/ParagraphSearcher.cs | 24 +- .../ManagementList/Common/CommandHelper.cs | 4 +- .../Common/DismissiblePopup.Generated.cs | 2 +- .../ManagementList/Common/DismissiblePopup.cs | 10 +- .../Common/IntegralConverter.cs | 2 +- .../Common/IsNotNullConverter.cs | 2 +- .../ManagementList/Common/KeyboardHelp.cs | 4 +- .../Common/ListOrganizer.Generated.cs | 2 +- .../Common/ListOrganizerItem.Generated.cs | 2 +- .../Common/ListOrganizerItem.cs | 8 +- .../Common/MessageTextBox.Generated.cs | 2 +- .../Common/PickerBase.Generated.cs | 2 +- .../ManagementList/Common/PickerBase.cs | 6 +- .../Common/PopupControlButton.Generated.cs | 2 +- .../ReadOnlyObservableAsyncCollection.cs | 4 +- .../Common/ScalableImage.Generated.cs | 2 +- .../ManagementList/Common/ScalableImage.cs | 8 +- .../Common/ScalableImageSource.Generated.cs | 2 +- .../ManagementList/Common/TextBlockService.cs | 2 +- .../ManagementList/Common/WpfHelp.cs | 34 +- .../CommonControls/ExpanderButton.cs | 2 +- .../CommonControls/Resizer.Generated.cs | 2 +- .../ManagementList/CommonControls/Resizer.cs | 4 +- .../UIElementAdorner.Generated.cs | 2 +- .../CommonControls/UIElementAdorner.cs | 8 +- .../DefaultFilterRuleCustomizationFactory.cs | 16 +- .../FilterCore/FilterEvaluator.cs | 6 +- .../FilterExpressionNode.cs | 6 +- .../FilterExpressionOperandNode.cs | 2 +- .../FilterRuleCustomizationFactory.cs | 2 +- .../FilterCore/FilterRules/FilterRule.cs | 2 +- .../PropertiesTextContainsFilterRule.cs | 2 +- .../PropertyValueSelectorFilterRule.cs | 2 +- .../FilterCore/FilterUtilities.cs | 2 +- .../FilterCore/ItemsControlFilterEvaluator.cs | 10 +- .../FilterCore/ValidatingSelectorValue.cs | 4 +- .../FilterCore/ValidatingValue.cs | 2 +- .../FilterCore/ValidatingValueBase.cs | 4 +- .../AddFilterRulePicker.Generated.cs | 2 +- .../FilterProviders/AddFilterRulePicker.cs | 2 +- .../AddFilterRulePickerItem.cs | 2 +- .../FilterProviders/FilterRulePanel.cs | 14 +- .../FilterRulePanelController.cs | 6 +- .../FilterProviders/FilterRulePanelItem.cs | 2 +- .../FilterRuleTemplateSelector.cs | 2 +- .../InputFieldBackgroundTextConverter.cs | 4 +- .../FilterProviders/SearchBox.Generated.cs | 2 +- .../FilterProviders/SearchBox.cs | 2 +- .../FilterProviders/SearchTextParser.cs | 4 +- .../ManagementList/ColumnPicker.xaml.cs | 4 +- .../ManagementList/InnerList.Generated.cs | 2 +- .../ManagementList/InnerListGridView.cs | 6 +- .../ManagementList/Innerlist.cs | 28 +- .../ManagementList.Generated.cs | 2 +- .../ManagementListStateDescriptor.cs | 2 +- .../ManagementListTitle.Generated.cs | 2 +- .../ManagementList/PropertyValueComparer.cs | 4 +- .../ManagementList/PropertyValueGetter.cs | 2 +- .../ManagementList/managementlist.cs | 4 +- .../Controls/ImageButton/ImageButton.xaml.cs | 4 +- .../ImageButtonToolTipConverter.cs | 4 +- .../ImageButton/ImageToggleButton.xaml.cs | 4 +- .../Controls/ParameterSetControl.xaml.cs | 4 +- .../ViewModel/AllModulesViewModel.cs | 20 +- .../ShowCommand/ViewModel/CommandViewModel.cs | 20 +- .../ShowCommand/ViewModel/ModuleViewModel.cs | 18 +- .../ViewModel/ParameterSetViewModel.cs | 4 +- .../ViewModel/ParameterViewModel.cs | 2 +- .../Windows/ShowAllModulesWindow.xaml.cs | 2 +- .../commandHelpers/HelpWindowHelper.cs | 2 +- .../commandHelpers/OutGridView.cs | 16 +- .../commandHelpers/ShowCommandHelper.cs | 26 +- .../ExportCounterCommand.cs | 2 +- .../GetCounterCommand.cs | 4 +- .../GetEventCommand.cs | 14 +- .../NewWinEventCommand.cs | 8 +- .../PdhHelper.cs | 26 +- .../cmdletization/SessionBasedWrapper.cs | 42 +- .../cmdletization/cim/CimJobException.cs | 36 +- .../cmdletization/cim/CreateInstanceJob.cs | 12 +- .../cmdletization/cim/DeleteInstanceJob.cs | 2 +- .../cim/EnumerateAssociatedInstancesJob.cs | 8 +- .../cim/ExtrinsicMethodInvocationJob.cs | 26 +- .../cim/InstanceMethodInvocationJob.cs | 2 +- .../cim/MethodInvocationJobBase.cs | 12 +- .../cmdletization/cim/ModifyInstanceJob.cs | 12 +- .../cmdletization/cim/PropertySettingJob.cs | 2 +- .../cimSupport/cmdletization/cim/QueryJob.cs | 2 +- .../cmdletization/cim/QueryJobBase.cs | 4 +- .../cim/TerminatingErrorTracker.cs | 4 +- .../cmdletization/cim/cimChildJobBase.cs | 30 +- .../cim/cimCmdletDefinitionContext.cs | 6 +- .../cim/cimCmdletInvocationContext.cs | 2 +- .../cmdletization/cim/cimConverter.cs | 22 +- .../cmdletization/cim/cimJobContext.cs | 2 +- .../cim/cimOperationOptionsHelper.cs | 8 +- .../cimSupport/cmdletization/cim/cimQuery.cs | 4 +- .../cmdletization/cim/cimWrapper.cs | 10 +- .../cmdletization/cim/clientSideQuery.cs | 8 +- .../commands/management/AddContentCommand.cs | 2 +- .../commands/management/CIMHelper.cs | 6 +- .../management/ClearContentCommand.cs | 2 +- .../management/ClearPropertyCommand.cs | 2 +- .../management/ClearRecycleBinCommand.cs | 4 +- .../commands/management/Clipboard.cs | 2 +- .../commands/management/CombinePathCommand.cs | 8 +- .../commands/management/Computer.cs | 24 +- .../commands/management/ContentCommandBase.cs | 24 +- .../management/ControlPanelItemCommand.cs | 12 +- .../management/CopyPropertyCommand.cs | 2 +- .../commands/management/Eventlog.cs | 16 +- .../commands/management/GetChildrenCommand.cs | 2 +- .../management/GetComputerInfoCommand.cs | 94 ++-- .../commands/management/GetContentCommand.cs | 18 +- .../commands/management/GetPropertyCommand.cs | 14 +- .../management/GetWMIObjectCommand.cs | 2 +- .../commands/management/Hotfix.cs | 10 +- .../management/InvokeWMIMethodCommand.cs | 16 +- .../management/MovePropertyCommand.cs | 4 +- .../commands/management/Navigation.cs | 38 +- .../commands/management/NewPropertyCommand.cs | 2 +- .../commands/management/ParsePathCommand.cs | 4 +- .../commands/management/PingPathCommand.cs | 2 +- .../commands/management/Process.cs | 62 +-- .../management/RegisterWMIEventCommand.cs | 8 +- .../management/RemovePropertyCommand.cs | 4 +- .../management/RemoveWMIObjectCommand.cs | 6 +- .../management/RenamePropertyCommand.cs | 2 +- .../commands/management/ResolvePathCommand.cs | 2 +- .../commands/management/Service.cs | 36 +- .../management/SetClipboardCommand.cs | 6 +- .../commands/management/SetPropertyCommand.cs | 2 +- .../management/SetWMIInstanceCommand.cs | 10 +- .../management/TestConnectionCommand.cs | 2 +- .../commands/management/TimeZoneCommands.cs | 2 +- .../management/UseTransactionCommand.cs | 2 +- .../commands/management/WMIHelper.cs | 54 +- .../commands/management/WebServiceProxy.cs | 8 +- .../management/WriteContentCommandBase.cs | 14 +- .../commands/utility/AddMember.cs | 14 +- .../commands/utility/AddType.cs | 10 +- .../commands/utility/Compare-Object.cs | 34 +- .../utility/ConvertFrom-SddlString.cs | 2 +- .../commands/utility/ConvertTo-Html.cs | 26 +- .../commands/utility/CsvCommands.cs | 30 +- .../commands/utility/CustomSerialization.cs | 100 ++-- .../commands/utility/DebugRunspaceCommand.cs | 58 +-- .../EnableDisableRunspaceDebugCommand.cs | 6 +- .../commands/utility/ExportAliasCommand.cs | 10 +- .../FormatAndOutput/OutGridView/ColumnInfo.cs | 2 +- .../OutGridView/ExpressionColumnInfo.cs | 2 +- .../OutGridView/OriginalColumnInfo.cs | 4 +- .../OutGridView/OutGridViewCommand.cs | 16 +- .../OutGridView/OutWindowProxy.cs | 6 +- .../FormatAndOutput/OutGridView/TableView.cs | 16 +- .../common/GetFormatDataCommand.cs | 12 +- .../FormatAndOutput/format-hex/Format-Hex.cs | 4 +- .../format-object/Format-Object.cs | 2 +- .../format-wide/Format-Wide.cs | 2 +- .../FormatAndOutput/out-file/Out-File.cs | 8 +- .../out-printer/PrinterLineOutput.cs | 4 +- .../FormatAndOutput/out-string/Out-String.cs | 4 +- .../commands/utility/Get-Error.cs | 2 +- .../commands/utility/Get-PSBreakpoint.cs | 2 +- .../commands/utility/GetDateCommand.cs | 4 +- .../commands/utility/GetEventCommand.cs | 6 +- .../utility/GetEventSubscriberCommand.cs | 6 +- .../commands/utility/GetHash.cs | 4 +- .../commands/utility/GetMember.cs | 2 +- .../commands/utility/GetRandomCommand.cs | 12 +- .../commands/utility/GetVerbCommand.cs | 4 +- .../commands/utility/Group-Object.cs | 12 +- .../utility/ImplicitRemotingCommands.cs | 94 ++-- .../commands/utility/Import-LocalizedData.cs | 6 +- .../commands/utility/ImportAliasCommand.cs | 6 +- .../utility/ImportPowerShellDataFile.cs | 2 +- .../utility/InvokeExpressionCommand.cs | 2 +- .../commands/utility/Join-String.cs | 4 +- .../utility/MarkdownOptionCommands.cs | 4 +- .../commands/utility/MatchString.cs | 32 +- .../commands/utility/Measure-Object.cs | 20 +- .../commands/utility/New-Object.cs | 14 +- .../commands/utility/NewAliasCommand.cs | 4 +- .../commands/utility/NewEventCommand.cs | 8 +- .../commands/utility/ObjectCommandComparer.cs | 2 +- .../commands/utility/OrderObjectBase.cs | 32 +- .../commands/utility/ReadConsoleCmdlet.cs | 6 +- .../commands/utility/RemoveAliasCommand.cs | 2 +- .../commands/utility/RemoveEventCommand.cs | 6 +- .../commands/utility/RunspaceAttribute.cs | 2 +- .../commands/utility/Select-Object.cs | 18 +- .../commands/utility/Send-MailMessage.cs | 14 +- .../commands/utility/Set-PSBreakpoint.cs | 2 +- .../commands/utility/SetAliasCommand.cs | 2 +- .../utility/ShowCommand/ShowCommand.cs | 4 +- .../ShowCommand/ShowCommandCommandInfo.cs | 6 +- .../ShowCommand/ShowCommandParameterInfo.cs | 2 +- .../commands/utility/ShowMarkdownCommand.cs | 2 +- .../commands/utility/StartSleepCommand.cs | 6 +- .../commands/utility/Tee-Object.cs | 2 +- .../commands/utility/TestJsonCommand.cs | 8 +- .../utility/UnregisterEventCommand.cs | 6 +- .../commands/utility/Update-List.cs | 18 +- .../commands/utility/Update-TypeData.cs | 64 +-- .../commands/utility/Var.cs | 26 +- .../commands/utility/WaitEventCommand.cs | 2 +- .../WebCmdlet/Common/ContentHelper.Common.cs | 6 +- .../Common/InvokeRestMethodCommand.Common.cs | 4 +- .../Common/WebRequestPSCmdlet.Common.cs | 84 ++-- .../Common/WebResponseObject.Common.cs | 2 +- .../WebCmdlet/ConvertFromJsonCommand.cs | 4 +- .../utility/WebCmdlet/ConvertToJsonCommand.cs | 2 +- .../CoreCLR/WebResponseHelper.CoreClr.cs | 2 +- .../commands/utility/WebCmdlet/FormObject.cs | 2 +- .../commands/utility/WebCmdlet/JsonObject.cs | 28 +- .../utility/WebCmdlet/StreamHelper.cs | 6 +- .../WebCmdlet/WebCmdletElementCollection.cs | 2 +- .../commands/utility/Write.cs | 20 +- .../commands/utility/WriteConsoleCmdlet.cs | 8 +- .../commands/utility/XmlCommands.cs | 50 +- .../utility/trace/TraceExpressionCommand.cs | 18 +- .../utility/trace/TraceListenerCommandBase.cs | 8 +- .../host/msh/CommandLineParameterParser.cs | 24 +- .../host/msh/ConsoleControl.cs | 2 +- .../host/msh/ConsoleHost.cs | 128 ++--- .../host/msh/ConsoleHostRawUserInterface.cs | 4 +- .../host/msh/ConsoleHostTranscript.cs | 2 +- .../host/msh/ConsoleHostUserInterface.cs | 28 +- .../msh/ConsoleHostUserInterfaceProgress.cs | 16 +- .../msh/ConsoleHostUserInterfacePrompt.cs | 22 +- ...ConsoleHostUserInterfacePromptForChoice.cs | 8 +- .../host/msh/ConsoleTextWriter.cs | 2 +- .../host/msh/Executor.cs | 28 +- .../host/msh/ManagedEntrance.cs | 2 +- .../host/msh/PendingProgress.cs | 44 +- .../host/msh/ProgressNode.cs | 2 +- .../host/msh/ProgressPane.cs | 6 +- .../host/msh/Serialization.cs | 6 +- .../host/msh/StartTranscriptCmdlet.cs | 2 +- .../host/msh/StopTranscriptCmdlet.cs | 2 +- .../host/msh/UpdatesNotification.cs | 8 +- .../DotNetCode/Eventing/EventProvider.cs | 22 +- .../Eventing/EventProviderTraceListener.cs | 20 +- .../Eventing/Reader/NativeWrapper.cs | 2 +- .../Commands/AddLocalGroupMemberCommand.cs | 20 +- .../Commands/DisableLocalUserCommand.cs | 8 +- .../Commands/EnableLocalUserCommand.cs | 8 +- .../Commands/GetLocalGroupCommand.cs | 6 +- .../Commands/GetLocalGroupMemberCommand.cs | 12 +- .../Commands/GetLocalUserCommand.cs | 6 +- .../Commands/NewLocalGroupCommand.cs | 2 +- .../Commands/NewLocalUserCommand.cs | 2 +- .../Commands/RemoveLocalGroupCommand.cs | 8 +- .../Commands/RemoveLocalGroupMemberCommand.cs | 20 +- .../Commands/RemoveLocalUserCommand.cs | 8 +- .../Commands/RenameLocalGroupCommand.cs | 8 +- .../Commands/RenameLocalUserCommand.cs | 8 +- .../Commands/SetLocalGroupCommand.cs | 10 +- .../Commands/SetLocalUserCommand.cs | 8 +- .../LocalAccounts/Extensions.cs | 6 +- .../LocalAccounts/Sam.cs | 18 +- .../FencedCodeBlockRenderer.cs | 2 +- .../ScheduledJob.cs | 50 +- .../ScheduledJobDefinition.cs | 60 +-- .../ScheduledJobSourceAdapter.cs | 10 +- .../ScheduledJobStore.cs | 4 +- .../ScheduledJobTrigger.cs | 12 +- .../ScheduledJobWTS.cs | 18 +- .../commands/DisableJobDefinitionBase.cs | 2 +- .../commands/EnableDisableCmdletBase.cs | 2 +- .../commands/GetScheduledJobOption.cs | 2 +- .../commands/RegisterJobDefinition.cs | 12 +- .../commands/SchedJobCmdletBase.cs | 2 +- .../commands/SetJobDefinition.cs | 24 +- .../commands/SetJobTrigger.cs | 8 +- .../commands/SetScheduledJobOption.cs | 2 +- .../commands/UnregisterJobDefinition.cs | 4 +- .../security/AclCommands.cs | 30 +- .../security/CatalogCommands.cs | 6 +- .../security/CertificateCommands.cs | 2 +- .../security/CertificateProvider.cs | 62 +-- .../security/CmsCommands.cs | 12 +- .../security/CredentialCommands.cs | 4 +- .../security/SecureStringCommands.cs | 14 +- .../security/SignatureCommands.cs | 10 +- .../ConfigProvider.cs | 144 +++--- src/Microsoft.WSMan.Management/CredSSP.cs | 32 +- .../CurrentConfigurations.cs | 6 +- .../InvokeWSManAction.cs | 2 +- .../NewWSManSession.cs | 4 +- src/Microsoft.WSMan.Management/PingWSMan.cs | 2 +- .../Set-QuickConfig.cs | 6 +- .../WSManConnections.cs | 4 +- .../WSManInstance.cs | 24 +- src/Microsoft.WSMan.Management/WsManHelper.cs | 60 +-- src/ResGen/Program.cs | 2 +- .../CoreCLR/CorePsAssemblyLoadContext.cs | 8 +- .../CoreCLR/CorePsPlatform.cs | 10 +- .../DscSupport/CimDSCParser.cs | 142 +++--- .../FormatAndOutput/common/BaseCommand.cs | 8 +- .../common/BaseFormattingCommand.cs | 18 +- .../common/BaseFormattingCommandParameters.cs | 8 +- .../common/BaseOutputtingCommand.cs | 50 +- .../FormatAndOutput/common/ComplexWriter.cs | 10 +- .../common/DisplayDatabase/FormatTable.cs | 2 +- .../common/DisplayDatabase/XmlLoaderBase.cs | 8 +- .../DisplayDatabase/displayDescriptionData.cs | 16 +- .../displayDescriptionData_Complex.cs | 26 +- .../displayDescriptionData_List.cs | 12 +- .../displayDescriptionData_Table.cs | 16 +- .../displayDescriptionData_Wide.cs | 4 +- .../displayResourceManagerCache.cs | 8 +- .../common/DisplayDatabase/typeDataManager.cs | 2 +- .../common/DisplayDatabase/typeDataQuery.cs | 34 +- .../DisplayDatabase/typeDataXmlLoader.cs | 60 +-- .../DisplayDatabase/typeDataXmlLoader_List.cs | 2 +- .../typeDataXmlLoader_Table.cs | 8 +- .../typeDataXmlLoader_Views.cs | 6 +- .../DisplayDatabase/typeDataXmlLoader_Wide.cs | 2 +- .../common/FormatGroupManager.cs | 2 +- .../common/FormatMsgCtxManager.cs | 8 +- .../common/FormatViewGenerator.cs | 46 +- .../common/FormatViewGenerator_Complex.cs | 52 +- .../common/FormatViewGenerator_List.cs | 32 +- .../common/FormatViewGenerator_Table.cs | 52 +- .../common/FormatViewGenerator_Wide.cs | 20 +- .../common/FormatViewManager.cs | 38 +- .../FormatAndOutput/common/FormatXMLWriter.cs | 30 +- .../common/FormattingObjectsDeserializer.cs | 10 +- .../FormatAndOutput/common/ListWriter.cs | 6 +- .../FormatAndOutput/common/OutputManager.cs | 16 +- .../FormatAndOutput/common/OutputQueue.cs | 18 +- .../FormatAndOutput/common/TableWriter.cs | 2 +- .../common/Utilities/MshObjectUtil.cs | 44 +- .../common/Utilities/MshParameter.cs | 10 +- .../Utilities/MshParameterAssociation.cs | 6 +- .../common/Utilities/Mshexpression.cs | 14 +- .../out-console/ConsoleLineOutput.cs | 4 +- .../FormatAndOutput/out-console/OutConsole.cs | 12 +- .../cimSupport/cmdletization/EnumWriter.cs | 2 +- .../cmdletization/MethodInvocationInfo.cs | 6 +- .../cmdletization/ObjectModelWrapper.cs | 4 +- .../cimSupport/cmdletization/ScriptWriter.cs | 196 ++++---- ...lets-over-objects.xmlSerializer.autogen.cs | 6 +- ...lets-over-objects.xmlSerializer.autogen.cs | 100 ++-- .../other/ciminstancetypeadapter.cs | 26 +- .../engine/AliasInfo.cs | 12 +- .../engine/ArgumentTypeConverterAttribute.cs | 12 +- .../engine/Attributes.cs | 12 +- .../engine/COM/ComAdapter.cs | 4 +- .../engine/COM/ComInvoker.cs | 10 +- .../engine/COM/ComTypeInfo.cs | 12 +- .../engine/COM/ComUtil.cs | 2 +- .../ChildrenCmdletProviderInterfaces.cs | 26 +- .../engine/CmdletInfo.cs | 24 +- .../engine/CmdletParameterBinderController.cs | 66 +-- .../engine/ComInterop/BoundDispEvent.cs | 2 +- .../engine/ComInterop/ComBinder.cs | 6 +- .../engine/ComInterop/ComBinderHelpers.cs | 10 +- .../engine/ComInterop/ComEventSink.cs | 6 +- .../ComInterop/ComEventSinksContainer.cs | 4 +- .../engine/ComInterop/ComInvokeBinder.cs | 26 +- .../engine/ComInterop/ComMethodDesc.cs | 2 +- .../engine/ComInterop/ComObject.cs | 10 +- .../engine/ComInterop/ComRuntimeHelpers.cs | 6 +- .../engine/ComInterop/ComTypeDesc.cs | 4 +- .../engine/ComInterop/ComTypeLibDesc.cs | 2 +- .../engine/ComInterop/DispCallable.cs | 2 +- .../ComInterop/DispCallableMetaObject.cs | 2 +- .../engine/ComInterop/ExcepInfo.cs | 6 +- .../engine/ComInterop/IDispatchComObject.cs | 18 +- .../engine/ComInterop/IDispatchMetaObject.cs | 6 +- .../engine/ComInterop/SimpleArgBuilder.cs | 4 +- .../engine/ComInterop/SplatCallSite.cs | 6 +- .../engine/ComInterop/TypeLibMetaObject.cs | 2 +- .../engine/ComInterop/TypeUtils.cs | 8 +- .../engine/ComInterop/Variant.cs | 8 +- .../engine/ComInterop/VariantBuilder.cs | 8 +- .../engine/CommandBase.cs | 4 +- .../CommandCompletion/CommandCompletion.cs | 60 +-- .../CommandCompletion/CompletionAnalysis.cs | 168 +++---- .../CommandCompletion/CompletionCompleters.cs | 404 +++++++-------- .../CommandCompletion/ExtensibleCompletion.cs | 2 +- .../PseudoParameterBinder.cs | 88 ++-- .../engine/CommandDiscovery.cs | 72 +-- .../engine/CommandInfo.cs | 32 +- .../engine/CommandMetadata.cs | 34 +- .../engine/CommandParameter.cs | 8 +- .../engine/CommandPathSearch.cs | 12 +- .../engine/CommandProcessor.cs | 34 +- .../engine/CommandProcessorBase.cs | 40 +- .../engine/CommandSearcher.cs | 58 +-- .../engine/CommonCommandParameters.cs | 2 +- .../engine/CompiledCommandParameter.cs | 26 +- .../engine/ContentCmdletProviderInterfaces.cs | 24 +- .../engine/CoreAdapter.cs | 206 ++++---- .../engine/Credential.cs | 10 +- .../engine/DataStoreAdapter.cs | 18 +- .../engine/DataStoreAdapterProvider.cs | 16 +- .../engine/DefaultCommandRuntime.cs | 4 +- .../engine/DriveInterfaces.cs | 22 +- .../engine/DscResourceInfo.cs | 4 +- .../engine/DscResourceSearcher.cs | 12 +- .../engine/EngineIntrinsics.cs | 2 +- .../engine/ErrorPackage.cs | 50 +- .../engine/EventManager.cs | 46 +- .../engine/ExecutionContext.cs | 54 +- .../GetExperimentalFeatureCommand.cs | 2 +- .../engine/ExternalScriptInfo.cs | 12 +- .../engine/ExtraAdapter.cs | 10 +- .../engine/GetCommandCommand.cs | 52 +- .../engine/InformationRecord.cs | 2 +- .../engine/InitialSessionState.cs | 172 +++---- .../engine/InternalCommands.cs | 52 +- .../engine/InvocationInfo.cs | 28 +- .../engine/ItemCmdletProviderInterfaces.cs | 84 ++-- .../engine/LanguagePrimitives.cs | 120 ++--- .../engine/ManagementObjectAdapter.cs | 40 +- .../engine/MergedCommandParameterMetadata.cs | 6 +- .../engine/Modules/AnalysisCache.cs | 22 +- .../Modules/ExportModuleMemberCommand.cs | 10 +- .../engine/Modules/GetModuleCommand.cs | 18 +- .../engine/Modules/ImportModuleCommand.cs | 74 +-- .../engine/Modules/ModuleCmdletBase.cs | 398 +++++++-------- .../engine/Modules/ModuleIntrinsics.cs | 66 +-- .../engine/Modules/ModuleSpecification.cs | 16 +- .../engine/Modules/ModuleUtils.cs | 12 +- .../engine/Modules/NewModuleCommand.cs | 4 +- .../Modules/NewModuleManifestCommand.cs | 74 +-- .../engine/Modules/PSModuleInfo.cs | 64 +-- .../engine/Modules/RemoteDiscoveryHelper.cs | 48 +- .../engine/Modules/RemoveModuleCommand.cs | 12 +- .../engine/Modules/ScriptAnalysis.cs | 18 +- .../Modules/TestModuleManifestCommand.cs | 16 +- .../engine/MshCmdlet.cs | 32 +- .../engine/MshCommandRuntime.cs | 80 +-- .../engine/MshMemberInfo.cs | 98 ++-- .../engine/MshObject.cs | 76 +-- .../engine/MshObjectTypeDescriptor.cs | 16 +- .../engine/MshReference.cs | 4 +- .../engine/MshSnapinQualifiedName.cs | 2 +- .../engine/NativeCommand.cs | 2 +- .../engine/NativeCommandParameterBinder.cs | 2 +- .../engine/NativeCommandProcessor.cs | 62 +-- .../engine/ObjectEventRegistrationBase.cs | 6 +- .../engine/PSClassInfo.cs | 2 +- .../engine/PSClassSearcher.cs | 34 +- .../engine/PSConfiguration.cs | 2 +- .../engine/PSVersionInfo.cs | 20 +- .../engine/ParameterBinderBase.cs | 86 ++-- .../engine/ParameterBinderController.cs | 20 +- .../engine/ParameterInfo.cs | 2 +- .../engine/ParameterSetInfo.cs | 6 +- .../engine/PathInterfaces.cs | 48 +- .../engine/Pipe.cs | 54 +- .../engine/ProcessCodeMethods.cs | 2 +- .../PropertyCmdletProviderInterfaces.cs | 64 +-- .../engine/ProviderInterfaces.cs | 6 +- .../engine/ProxyCommand.cs | 26 +- .../engine/PseudoParameterBinder.cs | 2 +- .../engine/PseudoParameters.cs | 2 +- .../engine/ReflectionParameterBinder.cs | 6 +- .../engine/ScopedItemSearcher.cs | 4 +- .../engine/ScriptCommandProcessor.cs | 18 +- ...urityDescriptorCmdletProviderInterfaces.cs | 12 +- .../engine/SecurityManagerBase.cs | 8 +- .../engine/SessionState.cs | 6 +- .../engine/SessionStateAliasAPIs.cs | 6 +- .../engine/SessionStateCmdletAPIs.cs | 8 +- .../engine/SessionStateContainer.cs | 180 +++---- .../engine/SessionStateContent.cs | 40 +- .../engine/SessionStateDriveAPIs.cs | 46 +- .../engine/SessionStateDynamicProperty.cs | 80 +-- .../engine/SessionStateFunctionAPIs.cs | 8 +- .../engine/SessionStateItem.cs | 54 +- .../engine/SessionStateLocationAPIs.cs | 14 +- .../engine/SessionStateNavigation.cs | 76 +-- .../engine/SessionStateProperty.cs | 42 +- .../engine/SessionStateProviderAPIs.cs | 26 +- .../engine/SessionStatePublic.cs | 8 +- .../engine/SessionStateScope.cs | 66 +-- .../engine/SessionStateScopeAPIs.cs | 12 +- .../engine/SessionStateScopeEnumerator.cs | 4 +- ...SessionStateSecurityDescriptorInterface.cs | 20 +- .../engine/SessionStateUtils.cs | 8 +- .../engine/SessionStateVariableAPIs.cs | 32 +- .../engine/ShellVariable.cs | 36 +- .../engine/ThirdPartyAdapter.cs | 16 +- .../engine/TransactedString.cs | 8 +- .../engine/TransactionManager.cs | 18 +- .../engine/TypeMetadata.cs | 64 +-- .../engine/TypeTable.cs | 182 +++---- .../engine/Utils.cs | 64 +-- .../engine/VariableAttributeCollection.cs | 6 +- .../engine/VariableInterfaces.cs | 24 +- .../engine/VariablePath.cs | 2 +- .../engine/cmdlet.cs | 50 +- .../engine/debugger/Breakpoint.cs | 16 +- .../engine/debugger/debugger.cs | 174 +++---- .../engine/hostifaces/AsyncResult.cs | 8 +- .../engine/hostifaces/ChoiceDescription.cs | 4 +- .../engine/hostifaces/Command.cs | 24 +- .../engine/hostifaces/Connection.cs | 34 +- .../engine/hostifaces/ConnectionBase.cs | 18 +- .../engine/hostifaces/FieldDescription.cs | 4 +- .../engine/hostifaces/History.cs | 44 +- .../engine/hostifaces/HostUtilities.cs | 14 +- .../engine/hostifaces/InformationalRecord.cs | 2 +- .../engine/hostifaces/InternalHost.cs | 14 +- .../hostifaces/InternalHostUserInterface.cs | 20 +- .../engine/hostifaces/ListModifier.cs | 2 +- .../engine/hostifaces/LocalConnection.cs | 54 +- .../engine/hostifaces/LocalPipeline.cs | 42 +- .../engine/hostifaces/MshHostUserInterface.cs | 58 +-- .../hostifaces/NativeCultureResolver.cs | 6 +- .../engine/hostifaces/PSCommand.cs | 18 +- .../engine/hostifaces/PSDataCollection.cs | 40 +- .../engine/hostifaces/PSTask.cs | 20 +- .../engine/hostifaces/Parameter.cs | 6 +- .../engine/hostifaces/Pipeline.cs | 6 +- .../engine/hostifaces/PowerShell.cs | 206 ++++---- .../hostifaces/PowerShellProcessInstance.cs | 10 +- .../engine/hostifaces/RunspaceInit.cs | 2 +- .../engine/hostifaces/RunspacePool.cs | 4 +- .../engine/hostifaces/RunspacePoolInternal.cs | 12 +- .../engine/hostifaces/pipelinebase.cs | 30 +- .../engine/interpreter/BranchLabel.cs | 2 +- .../interpreter/CallInstruction.Generated.cs | 36 +- .../engine/interpreter/CallInstruction.cs | 2 +- .../interpreter/ControlFlowInstructions.cs | 8 +- .../engine/interpreter/InstructionList.cs | 8 +- .../engine/interpreter/InterpretedFrame.cs | 4 +- .../engine/interpreter/LabelInfo.cs | 14 +- .../engine/interpreter/LightCompiler.cs | 90 ++-- .../interpreter/LightDelegateCreator.cs | 16 +- .../interpreter/LightLambda.Generated.cs | 64 +-- .../engine/interpreter/LightLambda.cs | 8 +- .../interpreter/LightLambdaClosureVisitor.cs | 6 +- .../engine/interpreter/LocalVariables.cs | 6 +- .../engine/interpreter/LoopCompiler.cs | 14 +- .../engine/interpreter/TypeOperations.cs | 2 +- .../engine/interpreter/Utilities.cs | 58 +-- .../engine/lang/interface/PSParseError.cs | 4 +- .../engine/lang/interface/PSParser.cs | 2 +- .../engine/lang/parserutils.cs | 26 +- .../engine/lang/scriptblock.cs | 38 +- .../engine/parser/AstVisitor.cs | 12 +- .../engine/parser/Compiler.cs | 260 +++++----- .../engine/parser/ConstantValues.cs | 10 +- .../engine/parser/DebugViewWriter.cs | 66 +-- .../engine/parser/FusionAssemblyIdentity.cs | 16 +- .../engine/parser/GlobalAssemblyCache.cs | 8 +- .../engine/parser/PSType.cs | 68 +-- .../engine/parser/Parser.cs | 334 ++++++------ .../engine/parser/Position.cs | 2 +- .../engine/parser/PreOrderVisitor.cs | 2 +- .../engine/parser/SafeValues.cs | 24 +- .../engine/parser/SemanticChecks.cs | 150 +++--- .../engine/parser/SymbolResolver.cs | 56 +-- .../engine/parser/TypeInferenceVisitor.cs | 90 ++-- .../engine/parser/TypeResolver.cs | 56 +-- .../engine/parser/VariableAnalysis.cs | 74 +-- .../engine/parser/ast.cs | 408 +++++++-------- .../engine/parser/token.cs | 6 +- .../engine/parser/tokenizer.cs | 56 +-- .../engine/pipeline.cs | 78 +-- .../engine/regex.cs | 6 +- .../remoting/client/ClientMethodExecutor.cs | 16 +- .../remoting/client/ClientRemotePowerShell.cs | 18 +- .../engine/remoting/client/Job.cs | 110 ++-- .../engine/remoting/client/Job2.cs | 106 ++-- .../engine/remoting/client/JobManager.cs | 26 +- .../remoting/client/JobSourceAdapter.cs | 8 +- .../client/RemoteRunspacePoolInternal.cs | 88 ++-- .../remoting/client/RemotingErrorRecord.cs | 4 +- .../remoting/client/RemotingProtocol2.cs | 44 +- .../engine/remoting/client/RunspaceRef.cs | 24 +- .../engine/remoting/client/ThrottlingJob.cs | 28 +- .../remoting/client/clientremotesession.cs | 8 +- ...clientremotesessionprotocolstatemachine.cs | 8 +- .../engine/remoting/client/remotepipeline.cs | 22 +- .../engine/remoting/client/remoterunspace.cs | 102 ++-- .../client/remotingprotocolimplementation.cs | 18 +- .../remoting/commands/ConnectPSSession.cs | 30 +- .../remoting/commands/CustomShellCommands.cs | 92 ++-- .../engine/remoting/commands/DebugJob.cs | 12 +- .../remoting/commands/DisconnectPSSession.cs | 6 +- .../commands/EnterPSHostProcessCommand.cs | 8 +- .../engine/remoting/commands/GetJob.cs | 6 +- .../remoting/commands/InvokeCommandCommand.cs | 68 +-- .../engine/remoting/commands/JobRepository.cs | 2 +- .../commands/NewPSSessionConfigurationFile.cs | 30 +- .../commands/NewPSSessionOptionCommand.cs | 6 +- .../remoting/commands/PSRemotingCmdlet.cs | 98 ++-- .../remoting/commands/PushRunspaceCommand.cs | 62 +-- .../engine/remoting/commands/ReceiveJob.cs | 64 +-- .../remoting/commands/ReceivePSSession.cs | 42 +- .../engine/remoting/commands/RemoveJob.cs | 22 +- .../engine/remoting/commands/ResumeJob.cs | 4 +- .../engine/remoting/commands/StartJob.cs | 6 +- .../engine/remoting/commands/StopJob.cs | 6 +- .../engine/remoting/commands/SuspendJob.cs | 6 +- .../engine/remoting/commands/WaitJob.cs | 12 +- .../remoting/commands/getrunspacecommand.cs | 6 +- .../remoting/commands/newrunspacecommand.cs | 42 +- .../remoting/commands/remotingcommandutil.cs | 6 +- .../remoting/commands/runspacerepository.cs | 2 +- .../engine/remoting/common/DispatchTable.cs | 4 +- .../engine/remoting/common/Indexer.cs | 2 +- .../engine/remoting/common/ObjectRef.cs | 6 +- .../common/RemoteSessionHyperVSocket.cs | 20 +- .../remoting/common/RemoteSessionNamedPipe.cs | 26 +- .../remoting/common/RunspaceConnectionInfo.cs | 66 +-- .../common/WireDataFormat/EncodeAndDecode.cs | 40 +- .../common/WireDataFormat/RemoteHost.cs | 18 +- .../WireDataFormat/RemoteHostEncoder.cs | 16 +- .../WireDataFormat/RemoteSessionCapability.cs | 2 +- .../WireDataFormat/RemotingDataObject.cs | 16 +- .../engine/remoting/common/fragmentor.cs | 32 +- .../engine/remoting/common/misc.cs | 8 +- .../engine/remoting/common/psstreamobject.cs | 40 +- .../engine/remoting/common/throttlemanager.cs | 8 +- .../remoting/fanin/BaseTransportManager.cs | 20 +- .../fanin/InitialSessionStateProvider.cs | 82 +-- .../fanin/OutOfProcTransportManager.cs | 74 +-- .../engine/remoting/fanin/PSPrincipal.cs | 4 +- .../fanin/PSSessionConfigurationData.cs | 4 +- .../remoting/fanin/PriorityCollection.cs | 36 +- .../engine/remoting/fanin/WSManNativeAPI.cs | 14 +- .../engine/remoting/fanin/WSManPlugin.cs | 28 +- .../remoting/fanin/WSManPluginFacade.cs | 6 +- .../remoting/fanin/WSManPluginShellSession.cs | 10 +- .../fanin/WSManPluginTransportManager.cs | 6 +- .../remoting/fanin/WSManTransportManager.cs | 114 ++--- .../server/OutOfProcServerMediator.cs | 18 +- .../remoting/server/ServerMethodExecutor.cs | 8 +- .../remoting/server/ServerPowerShellDriver.cs | 36 +- .../remoting/server/ServerRemoteHost.cs | 22 +- .../ServerRemoteHostRawUserInterface.cs | 2 +- .../server/ServerRemoteHostUserInterface.cs | 6 +- .../server/ServerRemotingProtocol2.cs | 36 +- .../server/ServerRunspacePoolDriver.cs | 114 ++--- .../server/ServerSteppablePipelineDriver.cs | 14 +- .../ServerSteppablePipelineSubscriber.cs | 10 +- .../remoting/server/WSManChannelEvents.cs | 4 +- .../remoting/server/serverremotesession.cs | 34 +- .../server/serverremotesessionstatemachine.cs | 10 +- .../serverremotingprotocolimplementation.cs | 6 +- .../engine/runtime/Binding/Binders.cs | 288 +++++------ .../engine/runtime/CompiledScriptBlock.cs | 102 ++-- .../engine/runtime/MutableTuple.cs | 8 +- .../engine/runtime/Operations/ArrayOps.cs | 12 +- .../engine/runtime/Operations/ClassOps.cs | 4 +- .../engine/runtime/Operations/MiscOps.cs | 196 ++++---- .../engine/runtime/Operations/StringOps.cs | 10 +- .../engine/runtime/Operations/VariableOps.cs | 26 +- .../engine/runtime/ScriptBlockToPowerShell.cs | 44 +- .../engine/scriptparameterbinder.cs | 8 +- .../engine/scriptparameterbindercontroller.cs | 2 +- .../engine/serialization.cs | 476 +++++++++--------- .../help/AliasHelpProvider.cs | 8 +- .../help/BaseCommandHelpInfo.cs | 16 +- .../help/CabinetAPI.cs | 2 +- .../help/CabinetNativeApi.cs | 4 +- .../help/CommandHelpProvider.cs | 92 ++-- .../help/DefaultCommandHelpObjectBuilder.cs | 36 +- .../help/DscResourceHelpProvider.cs | 24 +- .../help/HelpCategoryInvalidException.cs | 4 +- .../help/HelpCommands.cs | 42 +- .../help/HelpCommentsParser.cs | 34 +- .../help/HelpFileHelpInfo.cs | 4 +- .../help/HelpFileHelpProvider.cs | 10 +- .../help/HelpNotFoundException.cs | 4 +- .../help/HelpProvider.cs | 2 +- .../help/HelpProviderWithCache.cs | 2 +- .../help/HelpSystem.cs | 12 +- .../help/MUIFileSearcher.cs | 8 +- .../help/MamlClassHelpInfo.cs | 4 +- .../help/MamlCommandHelpInfo.cs | 12 +- .../help/MamlNode.cs | 14 +- .../help/MamlUtil.cs | 20 +- .../help/PSClassHelpProvider.cs | 22 +- .../help/ProviderCommandHelpInfo.cs | 4 +- .../help/ProviderContext.cs | 4 +- .../help/ProviderHelpInfo.cs | 8 +- .../help/ProviderHelpProvider.cs | 12 +- .../help/RemoteHelpInfo.cs | 8 +- .../help/SaveHelpCommand.cs | 22 +- .../help/UpdatableHelpCommandBase.cs | 30 +- .../help/UpdatableHelpInfo.cs | 12 +- .../help/UpdatableHelpModuleInfo.cs | 4 +- .../help/UpdatableHelpSystem.cs | 26 +- .../help/UpdatableHelpUri.cs | 2 +- .../help/UpdateHelpCommand.cs | 22 +- .../logging/LogProvider.cs | 8 +- .../logging/MshLog.cs | 18 +- .../logging/eventlog/EventLogLogProvider.cs | 12 +- .../namespaces/AliasProvider.cs | 16 +- .../namespaces/CoreCommandContext.cs | 70 +-- .../namespaces/DriveProviderBase.cs | 2 +- .../namespaces/EnvironmentProvider.cs | 4 +- .../namespaces/FileSystemContentStream.cs | 42 +- .../namespaces/FileSystemProvider.cs | 212 ++++---- .../namespaces/FunctionProvider.cs | 20 +- .../namespaces/LocationGlobber.cs | 118 ++--- .../namespaces/NavigationProviderBase.cs | 6 +- .../namespaces/PathInfo.cs | 2 +- .../namespaces/ProviderBase.cs | 78 +-- .../namespaces/RegistryProvider.cs | 52 +- .../namespaces/RegistrySecurity.cs | 4 +- .../namespaces/SessionStateProviderBase.cs | 20 +- .../namespaces/TransactedRegistryKey.cs | 28 +- .../namespaces/VariableProvider.cs | 10 +- .../security/Authenticode.cs | 12 +- .../security/CatalogHelper.cs | 8 +- .../security/SecureStringHelper.cs | 4 +- .../security/SecurityManager.cs | 2 +- .../security/SecuritySupport.cs | 28 +- .../security/nativeMethods.cs | 2 +- .../security/wldpNativeMethods.cs | 14 +- .../config/MshConsoleLoadException.cs | 4 +- .../singleshell/config/MshSnapinInfo.cs | 26 +- .../config/MshSnapinLoadException.cs | 2 +- .../utils/ClrFacade.cs | 2 +- .../utils/CommandDiscoveryExceptions.cs | 6 +- .../utils/CryptoUtils.cs | 16 +- .../utils/ExecutionExceptions.cs | 12 +- .../utils/ExtensionMethods.cs | 10 +- .../utils/FormatAndTypeDataHelper.cs | 2 +- .../utils/GraphicalHostReflectionWrapper.cs | 22 +- .../utils/IObjectWriter.cs | 2 +- .../utils/MshTraceSource.cs | 2 +- .../utils/ObjectReader.cs | 4 +- .../utils/ObjectStream.cs | 18 +- .../utils/ObjectWriter.cs | 2 +- .../utils/PSTelemetryMethods.cs | 28 +- .../utils/PSTelemetryWrapper.cs | 4 +- .../utils/ParameterBinderExceptions.cs | 24 +- .../utils/ParserException.cs | 2 +- .../utils/PathUtils.cs | 2 +- .../utils/PlatformInvokes.cs | 6 +- .../utils/PowerShellETWTracer.cs | 16 +- .../utils/PowerShellExecutionHelper.cs | 16 +- .../utils/PsUtils.cs | 8 +- .../utils/ResourceManagerCache.cs | 8 +- .../utils/RuntimeException.cs | 8 +- .../utils/SessionStateExceptions.cs | 6 +- .../utils/StringUtil.cs | 2 +- .../utils/StructuredTraceSource.cs | 14 +- .../utils/Verbs.cs | 2 +- .../perfCounters/CounterSetInstanceBase.cs | 8 +- .../utils/tracing/EtwActivity.cs | 16 +- .../utils/tracing/PSEtwLogProvider.cs | 4 +- .../utils/tracing/PSSysLogProvider.cs | 4 +- src/powershell/Program.cs | 2 +- test/tools/TestService/Service1.Designer.cs | 2 +- .../WebListener/Controllers/CertController.cs | 2 +- .../Controllers/ResumeController.cs | 4 +- test/xUnit/csharp/test_PSConfiguration.cs | 4 +- 789 files changed, 9276 insertions(+), 9276 deletions(-) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs index 0046b2a9a30..f323de6cf75 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs @@ -385,7 +385,7 @@ protected object GetBaseObject(object value) protected object GetReferenceOrReferenceArrayObject(object value, ref CimType referenceType) { PSReference cimReference = value as PSReference; - if (cimReference != null) + if (cimReference is not null) { object baseObject = GetBaseObject(cimReference.Value); CimInstance cimInstance = baseObject as CimInstance; @@ -516,7 +516,7 @@ private void Cleanup() } } - if (this.cimSessionProxyCache != null) + if (this.cimSessionProxyCache is not null) { List temporaryProxy; lock (this.cimSessionProxyCache) @@ -534,7 +534,7 @@ private void Cleanup() } this.moreActionEvent.Dispose(); - if (this.ackedEvent != null) + if (this.ackedEvent is not null) { this.ackedEvent.Dispose(); } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimBaseAction.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimBaseAction.cs index 345b27bb48b..cc8bea1da53 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimBaseAction.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimBaseAction.cs @@ -181,7 +181,7 @@ protected virtual void Dispose(bool disposing) if (disposing) { // Dispose managed resources. - if (this.completeEvent != null) + if (this.completeEvent is not null) { this.completeEvent.Dispose(); } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs index 87a6b3fda6a..e92dfedc3f4 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs @@ -450,7 +450,7 @@ internal string GetParameterSet() if ((entry.SetMandatoryParameterCount == entry.MandatoryParameterCount) && this.parametersetNamesList.Contains(parameterSetName)) { - if (boundParameterSetName != null) + if (boundParameterSetName is not null) { throw new PSArgumentException(CimCmdletStrings.UnableToResolveParameterSetName); } @@ -527,7 +527,7 @@ public class CimBaseCommand : Cmdlet, IDisposable /// internal void CheckParameterSet() { - if (this.parameterBinder != null) + if (this.parameterBinder is not null) { try { @@ -557,7 +557,7 @@ internal void SetParameter(object value, string parameterName) return; } - if (this.parameterBinder != null) + if (this.parameterBinder is not null) { this.parameterBinder.SetParameter(parameterName, this.AtBeginProcess); } @@ -663,7 +663,7 @@ protected void Dispose(bool disposing) protected virtual void DisposeInternal() { // Dispose managed resources. - if (this.operation != null) + if (this.operation is not null) { this.operation.Dispose(); } @@ -976,7 +976,7 @@ internal CimCredential CreateCimCredentials(PSCredential psCredentials, DebugHelper.WriteLogEx("PSCredential:{0}; PasswordAuthenticationMechanism:{1}; operationName:{2}; parameterName:{3}.", 0, psCredentials, passwordAuthentication, operationName, parameterName); CimCredential credentials = null; - if (psCredentials != null) + if (psCredentials is not null) { NetworkCredential networkCredential = psCredentials.GetNetworkCredential(); DebugHelper.WriteLog("Domain:{0}; UserName:{1}; Password:{2}.", 1, networkCredential.Domain, networkCredential.UserName, psCredentials.Password); diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetAssociatedInstance.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetAssociatedInstance.cs index fce4557432f..46a76c4a412 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetAssociatedInstance.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetAssociatedInstance.cs @@ -95,7 +95,7 @@ private void SetSessionProxyProperties( { proxy.OperationTimeout = cmdlet.OperationTimeoutSec; proxy.KeyOnly = cmdlet.KeyOnly; - if (cmdlet.ResourceUri != null) + if (cmdlet.ResourceUri is not null) { proxy.ResourceUri = cmdlet.ResourceUri; } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetInstance.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetInstance.cs index af3a6d41f86..c29feee2446 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetInstance.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetInstance.cs @@ -286,9 +286,9 @@ internal static bool IsClassNameQuerySet(CimBaseCommand cmdlet) { DebugHelper.WriteLogEx(); GetCimInstanceCommand cmd = cmdlet as GetCimInstanceCommand; - if (cmd != null) + if (cmd is not null) { - if (cmd.QueryDialect != null || cmd.SelectProperties != null || cmd.Filter != null) + if (cmd.QueryDialect is not null || cmd.SelectProperties is not null || cmd.Filter is not null) { return true; } @@ -301,7 +301,7 @@ protected static string CreateQuery(CimBaseCommand cmdlet) { DebugHelper.WriteLogEx(); GetCimInstanceCommand cmd = cmdlet as GetCimInstanceCommand; - if (cmd != null) + if (cmd is not null) { StringBuilder propertyList = new StringBuilder(); if (cmd.SelectProperties is null) @@ -385,7 +385,7 @@ private void SetSessionProxyProperties( proxy.KeyOnly = getCimInstance.KeyOnly; proxy.Shallow = getCimInstance.Shallow; proxy.OperationTimeout = getCimInstance.OperationTimeoutSec; - if (getCimInstance.ResourceUri != null) + if (getCimInstance.ResourceUri is not null) { proxy.ResourceUri = getCimInstance.ResourceUri; } @@ -394,7 +394,7 @@ private void SetSessionProxyProperties( { RemoveCimInstanceCommand removeCimInstance = cmdlet as RemoveCimInstanceCommand; proxy.OperationTimeout = removeCimInstance.OperationTimeoutSec; - if (removeCimInstance.ResourceUri != null) + if (removeCimInstance.ResourceUri is not null) { proxy.ResourceUri = removeCimInstance.ResourceUri; } @@ -408,7 +408,7 @@ private void SetSessionProxyProperties( { SetCimInstanceCommand setCimInstance = cmdlet as SetCimInstanceCommand; proxy.OperationTimeout = setCimInstance.OperationTimeoutSec; - if (setCimInstance.ResourceUri != null) + if (setCimInstance.ResourceUri is not null) { proxy.ResourceUri = setCimInstance.ResourceUri; } @@ -518,7 +518,7 @@ protected CimSessionProxy CreateSessionProxy( /// private void SetPreProcess(CimSessionProxy proxy, GetCimInstanceCommand cmdlet) { - if (cmdlet.KeyOnly || (cmdlet.SelectProperties != null)) + if (cmdlet.KeyOnly || (cmdlet.SelectProperties is not null)) { proxy.ObjectPreProcess = new FormatPartialCimInstance(); } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs index 331057a1ab2..97448b6df24 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs @@ -234,16 +234,16 @@ private void Initialize( private void NewSubscriptionResultHandler(object src, CimSubscriptionEventArgs args) { EventHandler temp = this.CimIndicationArrived; - if (temp != null) + if (temp is not null) { // raise the event CimSubscriptionResultEventArgs resultArgs = args as CimSubscriptionResultEventArgs; - if (resultArgs != null) + if (resultArgs is not null) temp(this, new CimIndicationEventInstanceEventArgs(resultArgs.Result)); else { CimSubscriptionExceptionEventArgs exceptionArgs = args as CimSubscriptionExceptionEventArgs; - if (exceptionArgs != null) + if (exceptionArgs is not null) temp(this, new CimIndicationEventExceptionEventArgs(exceptionArgs.Exception)); } } @@ -329,7 +329,7 @@ public void Stop() { if (status == Status.Started) { - if (this.cimRegisterCimIndication != null) + if (this.cimRegisterCimIndication is not null) { DebugHelper.WriteLog("Dispose CimRegisterCimIndication object", 4); this.cimRegisterCimIndication.Dispose(); @@ -348,7 +348,7 @@ public void Stop() /// internal void SetCmdlet(Cmdlet cmdlet) { - if (this.cimRegisterCimIndication != null) + if (this.cimRegisterCimIndication is not null) { this.cimRegisterCimIndication.Cmdlet = cmdlet; } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs index 94264208a4e..9393238cd0d 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs @@ -143,7 +143,7 @@ public void InvokeCimMethod(InvokeCimMethodCommand cmdlet) case CimBaseCommand.ResourceUriComputerSet: { string target = string.Format(CultureInfo.CurrentUICulture, targetClass, cmdlet.ClassName); - if (cmdlet.ResourceUri != null) + if (cmdlet.ResourceUri is not null) { nameSpace = cmdlet.Namespace; } @@ -210,7 +210,7 @@ public void InvokeCimMethod(InvokeCimMethodCommand cmdlet) case CimBaseCommand.CimInstanceSessionSet: { string target = cmdlet.CimInstance.ToString(); - if (cmdlet.ResourceUri != null) + if (cmdlet.ResourceUri is not null) { nameSpace = cmdlet.Namespace; } @@ -250,7 +250,7 @@ public void InvokeCimMethodOnCimInstance(CimInstance cimInstance, XOperationCont { DebugHelper.WriteLogEx(); CimInvokeCimMethodContext cimInvokeCimMethodContext = context as CimInvokeCimMethodContext; - Debug.Assert(cimInvokeCimMethodContext != null, "CimInvokeCimMethod::InvokeCimMethodOnCimInstance should has CimInvokeCimMethodContext != NULL."); + Debug.Assert(cimInvokeCimMethodContext is not null, "CimInvokeCimMethod::InvokeCimMethodOnCimInstance should has CimInvokeCimMethodContext is not null."); string action = string.Format(CultureInfo.CurrentUICulture, actionTemplate, cimInvokeCimMethodContext.MethodName); if (!operation.ShouldProcess(cimInstance.ToString(), action)) @@ -280,7 +280,7 @@ private void SetSessionProxyProperties( InvokeCimMethodCommand cmdlet) { proxy.OperationTimeout = cmdlet.OperationTimeoutSec; - if (cmdlet.ResourceUri != null) + if (cmdlet.ResourceUri is not null) { proxy.ResourceUri = cmdlet.ResourceUri; } @@ -385,7 +385,7 @@ private CimMethodParametersCollection CreateParametersCollection( CimMethodParameter parameter = null; CimMethodDeclaration declaration = null; string className = null; - if (cimClass != null) + if (cimClass is not null) { className = cimClass.CimSystemProperties.ClassName; declaration = cimClass.CimClassMethods[methodName]; @@ -395,13 +395,13 @@ private CimMethodParametersCollection CreateParametersCollection( CultureInfo.CurrentUICulture, CimCmdletStrings.InvalidMethod, methodName, className)); } } - else if (cimInstance != null) + else if (cimInstance is not null) { className = cimInstance.CimClass.CimSystemProperties.ClassName; declaration = cimInstance.CimClass.CimClassMethods[methodName]; } - if (declaration != null) + if (declaration is not null) { CimMethodParameterDeclaration paramDeclaration = declaration.Parameters[parameterName]; if (paramDeclaration is null) @@ -433,7 +433,7 @@ private CimMethodParametersCollection CreateParametersCollection( { CimType referenceType = CimType.Unknown; object referenceObject = GetReferenceOrReferenceArrayObject(parameterValue, ref referenceType); - if (referenceObject != null) + if (referenceObject is not null) { parameter = CimMethodParameter.Create( parameterName, @@ -451,7 +451,7 @@ private CimMethodParametersCollection CreateParametersCollection( } } - if (parameter != null) + if (parameter is not null) collection.Add(parameter); } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimNewCimInstance.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimNewCimInstance.cs index 22226fe908a..08f0a2ecae6 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimNewCimInstance.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimNewCimInstance.cs @@ -208,7 +208,7 @@ private void SetSessionProxyProperties( NewCimInstanceCommand cmdlet) { proxy.OperationTimeout = cmdlet.OperationTimeoutSec; - if (cmdlet.ResourceUri != null) + if (cmdlet.ResourceUri is not null) { proxy.ResourceUri = cmdlet.ResourceUri; } @@ -274,7 +274,7 @@ private CimInstance CreateCimInstance( } List keys = new List(); - if (key != null) + if (key is not null) { foreach (string keyName in key) { @@ -297,7 +297,7 @@ private CimInstance CreateCimInstance( DebugHelper.WriteLog("Create and add new property to ciminstance: name = {0}; value = {1}; flags = {2}", 5, propertyName, propertyValue, flag); PSReference cimReference = propertyValue as PSReference; - if (cimReference != null) + if (cimReference is not null) { CimProperty newProperty = CimProperty.Create(propertyName, GetBaseObject(cimReference.Value), CimType.Reference, flag); cimInstance.CimInstanceProperties.Add(newProperty); diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs index 9f9e72c6aab..68c9a6b47e5 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs @@ -217,7 +217,7 @@ private void CimIndicationHandler(object cimSession, CmdletActionEventArgs actio // NOTES: should move after this.Disposed, but need to log the exception CimWriteError cimWriteError = actionArgs.Action as CimWriteError; - if (cimWriteError != null) + if (cimWriteError is not null) { this.exception = cimWriteError.Exception; if (!this.ackedEvent.IsSet) @@ -229,7 +229,7 @@ private void CimIndicationHandler(object cimSession, CmdletActionEventArgs actio } EventHandler temp = this.OnNewSubscriptionResult; - if (temp != null) + if (temp is not null) { DebugHelper.WriteLog("Raise an exception event", 2); @@ -240,13 +240,13 @@ private void CimIndicationHandler(object cimSession, CmdletActionEventArgs actio } CimWriteResultObject cimWriteResultObject = actionArgs.Action as CimWriteResultObject; - if (cimWriteResultObject != null) + if (cimWriteResultObject is not null) { CimSubscriptionResult result = cimWriteResultObject.Result as CimSubscriptionResult; - if (result != null) + if (result is not null) { EventHandler temp = this.OnNewSubscriptionResult; - if (temp != null) + if (temp is not null) { DebugHelper.WriteLog("Raise an result event", 2); temp(this, new CimSubscriptionResultEventArgs(result)); @@ -276,10 +276,10 @@ private void WaitForAckMessage() { DebugHelper.WriteLogEx(); this.ackedEvent.Wait(); - if (this.exception != null) + if (this.exception is not null) { DebugHelper.WriteLogEx("error happened", 0); - if (this.Cmdlet != null) + if (this.Cmdlet is not null) { DebugHelper.WriteLogEx("Throw Terminating error", 1); diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRemoveCimInstance.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRemoveCimInstance.cs index 3dbae04b726..433061acc0a 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRemoveCimInstance.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRemoveCimInstance.cs @@ -88,7 +88,7 @@ public void RemoveCimInstance(RemoveCimInstanceCommand cmdlet) case CimBaseCommand.CimInstanceComputerSet: case CimBaseCommand.CimInstanceSessionSet: string nameSpace = null; - if (cmdlet.ResourceUri != null) + if (cmdlet.ResourceUri is not null) { nameSpace = GetCimInstanceParameter(cmdlet).CimSystemProperties.Namespace; } @@ -135,7 +135,7 @@ internal void RemoveCimInstance(CimInstance cimInstance, XOperationContextBase c } CimRemoveCimInstanceContext removeContext = context as CimRemoveCimInstanceContext; - Debug.Assert(removeContext != null, "CimRemoveCimInstance::RemoveCimInstance should has CimRemoveCimInstanceContext != NULL."); + Debug.Assert(removeContext is not null, "CimRemoveCimInstance::RemoveCimInstance should has CimRemoveCimInstanceContext is not null."); CimSessionProxy proxy = CreateCimSessionProxy(removeContext.Proxy); proxy.DeleteInstanceAsync(removeContext.Namespace, cimInstance); diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs index d9dca494c59..6a16400091a 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs @@ -448,7 +448,7 @@ public override void OnNext(CimMethodResultBase value) string resultObjectPSType = null; PSObject resultObject = null; CimMethodResult methodResult = value as CimMethodResult; - if (methodResult != null) + if (methodResult is not null) { resultObjectPSType = PSTypeCimMethodResult; resultObject = new PSObject(); @@ -460,7 +460,7 @@ public override void OnNext(CimMethodResultBase value) else { CimMethodStreamedResult methodStreamedResult = value as CimMethodStreamedResult; - if (methodStreamedResult != null) + if (methodStreamedResult is not null) { resultObjectPSType = PSTypeCimMethodStreamedResult; resultObject = new PSObject(); @@ -470,7 +470,7 @@ public override void OnNext(CimMethodResultBase value) } } - if (resultObject != null) + if (resultObject is not null) { resultObject.Properties.Add(new PSNoteProperty(@"PSComputerName", this.CurrentSession.ComputerName)); resultObject.TypeNames.Insert(0, resultObjectPSType); diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs index 846419b9939..5bf1417efe7 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs @@ -793,7 +793,7 @@ public CimSessionBase() CurrentRunspaceId, delegate (Guid instanceId) { - if (Runspace.DefaultRunspace != null) + if (Runspace.DefaultRunspace is not null) { Runspace.DefaultRunspace.StateChanged += DefaultRunspace_StateChanged; } @@ -838,7 +838,7 @@ private static Guid CurrentRunspaceId { get { - if (Runspace.DefaultRunspace != null) + if (Runspace.DefaultRunspace is not null) { return Runspace.DefaultRunspace.InstanceId; } @@ -1005,7 +1005,7 @@ internal void AddSessionToCache(CimSession cimSession, XOperationContextBase con CimTestCimSessionContext testCimSessionContext = context as CimTestCimSessionContext; uint sessionId = this.sessionState.GenerateSessionId(); string originalSessionName = testCimSessionContext.CimSessionWrapper.Name; - string sessionName = (originalSessionName != null) ? originalSessionName : string.Format(CultureInfo.CurrentUICulture, @"{0}{1}", CimSessionState.CimSessionClassName, sessionId); + string sessionName = (originalSessionName is not null) ? originalSessionName : string.Format(CultureInfo.CurrentUICulture, @"{0}{1}", CimSessionState.CimSessionClassName, sessionId); // detach CimSession from the proxy object CimSession createdCimSession = testCimSessionContext.Proxy.Detach(); @@ -1173,7 +1173,7 @@ public void GetCimSession(GetCimSessionCommand cmdlet) break; } - if (sessionToGet != null) + if (sessionToGet is not null) { foreach (PSObject psobject in sessionToGet) { @@ -1181,7 +1181,7 @@ public void GetCimSession(GetCimSessionCommand cmdlet) } } - if (errorRecords != null) + if (errorRecords is not null) { foreach (ErrorRecord errRecord in errorRecords) { @@ -1250,7 +1250,7 @@ public void RemoveCimSession(RemoveCimSessionCommand cmdlet) break; } - if (sessionToRemove != null) + if (sessionToRemove is not null) { foreach (PSObject psobject in sessionToRemove) { @@ -1261,7 +1261,7 @@ public void RemoveCimSession(RemoveCimSessionCommand cmdlet) } } - if (errorRecords != null) + if (errorRecords is not null) { foreach (ErrorRecord errRecord in errorRecords) { diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs index e6b65f0409b..2b9a3eaccc9 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs @@ -70,7 +70,7 @@ internal class InvocationContext /// internal InvocationContext(CimSessionProxy proxy) { - if (proxy != null) + if (proxy is not null) { this.ComputerName = proxy.CimSession.ComputerName; this.TargetCimInstance = proxy.TargetCimInstance; @@ -230,7 +230,7 @@ internal class CimSessionProxy : IDisposable /// CimSession to be added. internal static void AddCimSessionToTemporaryCache(CimSession session) { - if (session != null) + if (session is not null) { lock (temporarySessionCacheLock) { @@ -256,7 +256,7 @@ internal static void AddCimSessionToTemporaryCache(CimSession session) private static void RemoveCimSessionFromTemporaryCache(CimSession session, bool dispose) { - if (session != null) + if (session is not null) { bool removed = false; lock (temporarySessionCacheLock) @@ -402,14 +402,14 @@ public CimSessionProxy(string computerName, CimInstance cimInstance) return; } - Debug.Assert(cimInstance != null, "Caller should verify cimInstance != null"); + Debug.Assert(cimInstance is not null, "Caller should verify cimInstance is not null"); // computerName is null, fallback to create session from cimInstance CimSessionState state = CimSessionBase.GetCimSessionState(); - if (state != null) + if (state is not null) { CimSession session = state.QuerySession(cimInstance.GetCimSessionInstanceId()); - if (session != null) + if (session is not null) { DebugHelper.WriteLogEx("Found the session from cache with InstanceID={0}.", 0, cimInstance.GetCimSessionInstanceId()); CreateSetSession(null, session, null, null, false); @@ -494,14 +494,14 @@ private void CreateSetSession( this.protocol = ProtocolType.Wsman; this.isTemporaryCimSession = temporaryCimSession; - if (cimSession != null) + if (cimSession is not null) { this.session = cimSession; CimSessionState state = CimSessionBase.GetCimSessionState(); - if (state != null) + if (state is not null) { CimSessionWrapper wrapper = state.QuerySession(cimSession); - if (wrapper != null) + if (wrapper is not null) { this.protocol = wrapper.GetProtocolType(); } @@ -509,7 +509,7 @@ private void CreateSetSession( } else { - if (sessionOptions != null) + if (sessionOptions is not null) { if (sessionOptions is DComSessionOptions) { @@ -666,7 +666,7 @@ private void InitOption(CimOperationOptions operOptions) { DebugHelper.WriteLogEx(); - if (operOptions != null) + if (operOptions is not null) { this.options = new CimOperationOptions(operOptions); } @@ -730,12 +730,12 @@ private void RemoveOperation(IObservable operation) this.DisposeCancelOperation(); - if (this.operation != null) + if (this.operation is not null) { this.operation = null; } - if (this.session != null && this.ContextObject is null) + if (this.session is not null && this.ContextObject is null) { DebugHelper.WriteLog("Dispose this proxy object @ RemoveOperation"); this.Dispose(); @@ -760,7 +760,7 @@ protected void FireNewActionEvent(CimBaseAction action) } NewCmdletActionHandler temp = this.OnNewCmdletAction; - if (temp != null) + if (temp is not null) { temp(this.session, actionArgs); } @@ -788,7 +788,7 @@ private void FireOperationCreatedEvent( OperationEventArgs args = new OperationEventArgs( cancelOperation, operation, false); OperationEventHandler temp = this.OnOperationCreated; - if (temp != null) + if (temp is not null) { temp(this.session, args); } @@ -812,7 +812,7 @@ private void FireOperationDeletedEvent( null, operation, success); PreOperationDeleteEvent(args); OperationEventHandler temp = this.OnOperationDeleted; - if (temp != null) + if (temp is not null) { temp(this.session, args); } @@ -858,7 +858,7 @@ internal void WriteOperationStartMessage(string operation, Hashtable parameterLi { DebugHelper.WriteLogEx(); StringBuilder parameters = new StringBuilder(); - if (parameterList != null) + if (parameterList is not null) { foreach (string key in parameterList.Keys) { @@ -1024,7 +1024,7 @@ internal void ResultEventHandler( AddShowComputerNameMarker(resultObject); } - if (this.ObjectPreProcess != null) + if (this.ObjectPreProcess is not null) { resultObject = this.ObjectPreProcess.Process(resultObject); } @@ -1100,7 +1100,7 @@ private object PostProcessCimInstance(object resultObject) /// public void CreateInstanceAsync(string namespaceName, CimInstance instance) { - Debug.Assert(instance != null, "Caller should verify that instance != NULL."); + Debug.Assert(instance is not null, "Caller should verify that instance is not null."); DebugHelper.WriteLogEx("EnableMethodResultStreaming = {0}", 0, this.options.EnableMethodResultStreaming); this.CheckAvailability(); this.targetCimInstance = instance; @@ -1120,7 +1120,7 @@ public void CreateInstanceAsync(string namespaceName, CimInstance instance) /// public void DeleteInstanceAsync(string namespaceName, CimInstance instance) { - Debug.Assert(instance != null, "Caller should verify that instance != NULL."); + Debug.Assert(instance is not null, "Caller should verify that instance is not null."); DebugHelper.WriteLogEx("namespace = {0}; classname = {1};", 0, namespaceName, instance.CimSystemProperties.ClassName); this.CheckAvailability(); this.targetCimInstance = instance; @@ -1140,7 +1140,7 @@ public void DeleteInstanceAsync(string namespaceName, CimInstance instance) /// public void GetInstanceAsync(string namespaceName, CimInstance instance) { - Debug.Assert(instance != null, "Caller should verify that instance != NULL."); + Debug.Assert(instance is not null, "Caller should verify that instance is not null."); DebugHelper.WriteLogEx("namespace = {0}; classname = {1}; keyonly = {2}", 0, namespaceName, instance.CimSystemProperties.ClassName, this.options.KeysOnly); this.CheckAvailability(); this.targetCimInstance = instance; @@ -1160,7 +1160,7 @@ public void GetInstanceAsync(string namespaceName, CimInstance instance) /// public void ModifyInstanceAsync(string namespaceName, CimInstance instance) { - Debug.Assert(instance != null, "Caller should verify that instance != NULL."); + Debug.Assert(instance is not null, "Caller should verify that instance is not null."); DebugHelper.WriteLogEx("namespace = {0}; classname = {1}", 0, namespaceName, instance.CimSystemProperties.ClassName); this.CheckAvailability(); this.targetCimInstance = instance; @@ -1191,7 +1191,7 @@ public void EnumerateAssociatedInstancesAsync( string sourceRole, string resultRole) { - Debug.Assert(sourceInstance != null, "Caller should verify that sourceInstance != NULL."); + Debug.Assert(sourceInstance is not null, "Caller should verify that sourceInstance is not null."); DebugHelper.WriteLogEx("Instance class {0}, association class {1}", 0, sourceInstance.CimSystemProperties.ClassName, associationClassName); this.CheckAvailability(); this.targetCimInstance = sourceInstance; @@ -1343,7 +1343,7 @@ public void InvokeMethodAsync( string methodName, CimMethodParametersCollection methodParameters) { - Debug.Assert(instance != null, "Caller should verify that instance != NULL."); + Debug.Assert(instance is not null, "Caller should verify that instance is not null."); DebugHelper.WriteLogEx("EnableMethodResultStreaming = {0}", 0, this.options.EnableMethodResultStreaming); this.CheckAvailability(); this.targetCimInstance = instance; @@ -1589,7 +1589,7 @@ private void DisposeCancelOperation() DebugHelper.WriteLogEx("CancelOperation Disposed = {0}", 0, this._cancelOperationDisposed); if (Interlocked.CompareExchange(ref this._cancelOperationDisposed, 1, 0) == 0) { - if (this._cancelOperation != null) + if (this._cancelOperation is not null) { DebugHelper.WriteLog("CimSessionProxy::Dispose async operation.", 4); this._cancelOperation.Dispose(); @@ -1720,7 +1720,7 @@ protected virtual void Dispose(bool disposing) // Dispose managed resources. this.DisposeCancelOperation(); - if (this.options != null) + if (this.options is not null) { this.options.Dispose(); this.options = null; @@ -1746,7 +1746,7 @@ public bool IsDisposed /// private void DisposeTemporaryCimSession() { - if (this.isTemporaryCimSession && this.session != null) + if (this.isTemporaryCimSession && this.session is not null) { // remove the cimsession from temporary cache RemoveCimSessionFromTemporaryCache(this.session); @@ -1981,7 +1981,7 @@ internal static CimSessionOptions CreateCimSessionOption(string computerName, option.Timeout = TimeSpan.FromSeconds((double)timeout); } - if (credential != null) + if (credential is not null) { option.AddDestinationCredentials(credential); } @@ -2102,7 +2102,7 @@ protected override bool PreNewActionEvent(CmdletActionEventArgs args) DebugHelper.WriteLog("class name = {0}", 1, cimClass.CimSystemProperties.ClassName); CimGetCimClassContext context = this.ContextObject as CimGetCimClassContext; - Debug.Assert(context != null, "Caller should verify that CimGetCimClassContext != NULL."); + Debug.Assert(context is not null, "Caller should verify that CimGetCimClassContext is not null."); WildcardPattern pattern; if (WildcardPattern.ContainsWildcardCharacters(context.ClassName)) @@ -2114,10 +2114,10 @@ protected override bool PreNewActionEvent(CmdletActionEventArgs args) } } - if (context.PropertyName != null) + if (context.PropertyName is not null) { bool match = false; - if (cimClass.CimClassProperties != null) + if (cimClass.CimClassProperties is not null) { pattern = new WildcardPattern(context.PropertyName, WildcardOptions.IgnoreCase); foreach (CimPropertyDeclaration decl in cimClass.CimClassProperties) @@ -2138,10 +2138,10 @@ protected override bool PreNewActionEvent(CmdletActionEventArgs args) } } - if (context.MethodName != null) + if (context.MethodName is not null) { bool match = false; - if (cimClass.CimClassMethods != null) + if (cimClass.CimClassMethods is not null) { pattern = new WildcardPattern(context.MethodName, WildcardOptions.IgnoreCase); foreach (CimMethodDeclaration decl in cimClass.CimClassMethods) @@ -2162,10 +2162,10 @@ protected override bool PreNewActionEvent(CmdletActionEventArgs args) } } - if (context.QualifierName != null) + if (context.QualifierName is not null) { bool match = false; - if (cimClass.CimClassQualifiers != null) + if (cimClass.CimClassQualifiers is not null) { pattern = new WildcardPattern(context.QualifierName, WildcardOptions.IgnoreCase); foreach (CimQualifier qualifier in cimClass.CimClassQualifiers) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSetCimInstance.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSetCimInstance.cs index b156e5af79d..a1d0e4b539b 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSetCimInstance.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSetCimInstance.cs @@ -146,7 +146,7 @@ public void SetCimInstance(SetCimInstanceCommand cmdlet) Exception exception = null; CimInstance instance = cmdlet.CimInstance; // For CimInstance parameter sets, Property is an optional parameter - if (cmdlet.Property != null) + if (cmdlet.Property is not null) { if (!SetProperty(cmdlet.Property, ref instance, ref exception)) { @@ -226,7 +226,7 @@ private bool SetProperty(IDictionary properties, ref CimInstance cimInstance, re { CimProperty property = cimInstance.CimInstanceProperties[key]; // modify existing property value if found - if (property != null) + if (property is not null) { if ((property.Flags & CimFlags.ReadOnly) == CimFlags.ReadOnly) { @@ -255,7 +255,7 @@ private bool SetProperty(IDictionary properties, ref CimInstance cimInstance, re { CimType referenceType = CimType.Unknown; object referenceObject = GetReferenceOrReferenceArrayObject(value, ref referenceType); - if (referenceObject != null) + if (referenceObject is not 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..9fd9be56e07 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs @@ -37,16 +37,16 @@ internal static ErrorRecord ErrorRecordFromAnyException( Exception inner, CimResultContext cimResultContext) { - Debug.Assert(inner != null, "Caller should verify inner != null"); + Debug.Assert(inner is not null, "Caller should verify inner is not null"); CimException cimException = inner as CimException; - if (cimException != null) + if (cimException is not null) { return CreateFromCimException(context, cimException, cimResultContext); } var containsErrorRecord = inner as IContainsErrorRecord; - if (containsErrorRecord != null) + if (containsErrorRecord is not null) { return InitializeErrorRecord(context, exception: inner, @@ -77,7 +77,7 @@ internal static ErrorRecord CreateFromCimException( CimException cimException, CimResultContext cimResultContext) { - Debug.Assert(cimException != null, "Caller should verify cimException != null"); + Debug.Assert(cimException is not null, "Caller should verify cimException is not null"); return InitializeErrorRecord(context, cimException, cimResultContext); } @@ -125,7 +125,7 @@ internal static ErrorRecord InitializeErrorRecord( errorCategory: ConvertCimExceptionToErrorCategory(cimException), cimResultContext: cimResultContext); - if (cimException.ErrorData != null) + if (cimException.ErrorData is not null) { errorRecord.CategoryInfo.TargetName = cimException.ErrorSource; } @@ -150,16 +150,16 @@ internal static ErrorRecord InitializeErrorRecordCore( CimResultContext cimResultContext) { object theTargetObject = null; - if (cimResultContext != null) + if (cimResultContext is not null) { theTargetObject = cimResultContext.ErrorSource; } if (theTargetObject is null) { - if (context != null) + if (context is not null) { - if (context.TargetCimInstance != null) + if (context.TargetCimInstance is not null) { theTargetObject = context.TargetCimInstance; } @@ -198,7 +198,7 @@ internal static ErrorCategory ConvertCimExceptionToErrorCategory(CimException ci { ErrorCategory result = ErrorCategory.NotSpecified; - if (cimException.ErrorData != null) + if (cimException.ErrorData is not null) { result = ConvertCimErrorToErrorCategory(cimException.ErrorData); } @@ -345,10 +345,10 @@ public CimWriteError(Exception exception, InvocationContext context, CimResultCo /// public override void Execute(CmdletOperationBase cmdlet) { - Debug.Assert(cmdlet != null, "Caller should verify that cmdlet != null"); + Debug.Assert(cmdlet is not null, "Caller should verify that cmdlet is not null"); try { - Exception errorException = (error != null) ? new CimException(error) : this.Exception; + Exception errorException = (error is not null) ? new CimException(error) : this.Exception; // PS engine takes care of handling error action cmdlet.WriteError(ErrorToErrorRecord.ErrorRecordFromAnyException(this.invocationContext, errorException, this.cimResultContext)); diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs index bee7905cc52..d7ba837d0f7 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs @@ -232,7 +232,7 @@ public override void WriteObject(object sendToPipeline, XOperationContextBase co if (sendToPipeline is CimInstance) { CimSetCimInstanceContext setContext = context as CimSetCimInstanceContext; - if (setContext != null) + if (setContext is not null) { if (string.Equals(setContext.ParameterSetName, CimBaseCommand.QueryComputerSet, StringComparison.OrdinalIgnoreCase) || string.Equals(setContext.ParameterSetName, CimBaseCommand.QuerySessionSet, StringComparison.OrdinalIgnoreCase)) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimAssociatedInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimAssociatedInstanceCommand.cs index 36987d35bd9..e7c2f061b43 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimAssociatedInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimAssociatedInstanceCommand.cs @@ -260,7 +260,7 @@ protected override void ProcessRecord() protected override void EndProcessing() { CimGetAssociatedInstance operation = this.GetOperationAgent(); - if (operation != null) + if (operation is not null) operation.ProcessRemainActions(this.CmdletOperation); } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimClassCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimClassCommand.cs index a439e263f0d..b29ac115d63 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimClassCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimClassCommand.cs @@ -232,7 +232,7 @@ protected override void ProcessRecord() protected override void EndProcessing() { CimGetCimClass cimGetCimClass = this.GetOperationAgent(); - if (cimGetCimClass != null) + if (cimGetCimClass is not null) { cimGetCimClass.ProcessRemainActions(this.CmdletOperation); } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimInstanceCommand.cs index 9e38546793b..dc7c2f03593 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimInstanceCommand.cs @@ -472,7 +472,7 @@ protected override void ProcessRecord() protected override void EndProcessing() { CimGetInstance cimGetInstance = this.GetOperationAgent(); - if (cimGetInstance != null) + if (cimGetInstance is not null) { cimGetInstance.ProcessRemainActions(this.CmdletOperation); } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/InvokeCimMethodCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/InvokeCimMethodCommand.cs index e777987a87b..bff447c8ef7 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/InvokeCimMethodCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/InvokeCimMethodCommand.cs @@ -397,7 +397,7 @@ protected override void ProcessRecord() protected override void EndProcessing() { CimInvokeCimMethod cimInvokeMethod = this.GetOperationAgent(); - if (cimInvokeMethod != null) + if (cimInvokeMethod is not null) { cimInvokeMethod.ProcessRemainActions(this.CmdletOperation); } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimInstanceCommand.cs index 31b860777ea..0a6116b08f6 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimInstanceCommand.cs @@ -339,16 +339,16 @@ protected override void ProcessRecord() if (this.ClientOnly) { string conflictParameterName = null; - if (this.ComputerName != null) + if (this.ComputerName is not null) { conflictParameterName = @"ComputerName"; } - else if (this.CimSession != null) + else if (this.CimSession is not null) { conflictParameterName = @"CimSession"; } - if (conflictParameterName != null) + if (conflictParameterName is not null) { ThrowConflictParameterWasSet(@"New-CimInstance", conflictParameterName, @"ClientOnly"); return; @@ -367,7 +367,7 @@ protected override void ProcessRecord() protected override void EndProcessing() { CimNewCimInstance cimNewCimInstance = this.GetOperationAgent(); - if (cimNewCimInstance != null) + if (cimNewCimInstance is not null) { cimNewCimInstance.ProcessRemainActions(this.CmdletOperation); } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionCommand.cs index 89b9a674bf0..fd0b838359c 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionCommand.cs @@ -251,7 +251,7 @@ internal void BuildSessionOptions(out CimSessionOptions outputOptions, out CimCr DebugHelper.WriteLogEx(); CimSessionOptions options = null; - if (this.SessionOption != null) + if (this.SessionOption is not null) { // clone the sessionOption object if (this.SessionOption is WSManSessionOptions) @@ -266,14 +266,14 @@ internal void BuildSessionOptions(out CimSessionOptions outputOptions, out CimCr outputOptions = null; outputCredential = null; - if (options != null) + if (options is not null) { DComSessionOptions dcomOptions = (options as DComSessionOptions); - if (dcomOptions != null) + if (dcomOptions is not null) { bool conflict = false; string parameterName = string.Empty; - if (this.CertificateThumbprint != null) + if (this.CertificateThumbprint is not null) { conflict = true; parameterName = @"CertificateThumbprint"; @@ -293,7 +293,7 @@ internal void BuildSessionOptions(out CimSessionOptions outputOptions, out CimCr } } - if (portSet || (this.CertificateThumbprint != null)) + if (portSet || (this.CertificateThumbprint is not null)) { WSManSessionOptions wsmanOptions = (options is null) ? new WSManSessionOptions() : options as WSManSessionOptions; if (portSet) @@ -302,7 +302,7 @@ internal void BuildSessionOptions(out CimSessionOptions outputOptions, out CimCr portSet = false; } - if (this.CertificateThumbprint != null) + if (this.CertificateThumbprint is not null) { CimCredential credentials = new CimCredential(CertificateAuthenticationMechanism.Default, this.CertificateThumbprint); wsmanOptions.AddDestinationCredentials(credentials); @@ -313,13 +313,13 @@ internal void BuildSessionOptions(out CimSessionOptions outputOptions, out CimCr if (this.operationTimeoutSet) { - if (options != null) + if (options is not null) { options.Timeout = TimeSpan.FromSeconds((double)this.OperationTimeoutSec); } } - if (this.authenticationSet || (this.credential != null)) + if (this.authenticationSet || (this.credential is not null)) { PasswordAuthenticationMechanism authentication = this.authenticationSet ? this.Authentication : PasswordAuthenticationMechanism.Default; if (this.authenticationSet) @@ -335,7 +335,7 @@ internal void BuildSessionOptions(out CimSessionOptions outputOptions, out CimCr DebugHelper.WriteLog("Credentials: {0}", 1, credentials); outputCredential = credentials; - if (options != null) + if (options is not null) { DebugHelper.WriteLog("Add credentials to option: {0}", 1, options); options.AddDestinationCredentials(credentials); @@ -368,7 +368,7 @@ protected override void DisposeInternal() base.DisposeInternal(); // Dispose managed resources. - if (this.cimNewSession != null) + if (this.cimNewSession is not null) { this.cimNewSession.Dispose(); } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionOptionCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionOptionCommand.cs index aba99d9401c..7df688c2029 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionOptionCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionOptionCommand.cs @@ -490,14 +490,14 @@ protected override void ProcessRecord() return; } - if (options != null) + if (options is not null) { - if (this.Culture != null) + if (this.Culture is not null) { options.Culture = this.Culture; } - if (this.UICulture != null) + if (this.UICulture is not null) { options.UICulture = this.UICulture; } @@ -622,7 +622,7 @@ internal WSManSessionOptions CreateWSMANSessionOptions() wsmanoptions.PacketEncoding = PacketEncoding.Utf8; } - if (this.HttpPrefix != null) + if (this.HttpPrefix is not null) { wsmanoptions.HttpUrlPrefix = this.HttpPrefix; } @@ -647,7 +647,7 @@ internal WSManSessionOptions CreateWSMANSessionOptions() this.proxyauthenticationSet = false; DebugHelper.WriteLogEx("create credential", 1); CimCredential credentials = CreateCimCredentials(this.ProxyCredential, this.ProxyAuthentication, @"New-CimSessionOption", @"ProxyAuthentication"); - if (credentials != null) + if (credentials is not null) { try { diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs index 911e4156e08..d642cf4ad18 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs @@ -226,7 +226,7 @@ protected override object GetSourceObject() break; } - if (watcher != null) + if (watcher is not null) { watcher.SetCmdlet(this); } @@ -254,7 +254,7 @@ protected override void EndProcessing() // Register for the "Unsubscribed" event so that we can stop the // Cimindication event watcher. PSEventSubscriber newSubscriber = NewSubscriber; - if (newSubscriber != null) + if (newSubscriber is not null) { DebugHelper.WriteLog("RegisterCimIndicationCommand::EndProcessing subscribe to Unsubscribed event", 4); newSubscriber.Unsubscribed += newSubscriber_Unsubscribed; @@ -274,7 +274,7 @@ private static void newSubscriber_Unsubscribed( DebugHelper.WriteLogEx(); CimIndicationWatcher watcher = sender as CimIndicationWatcher; - if (watcher != null) + if (watcher is not null) { watcher.Stop(); } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimInstanceCommand.cs index 60b152055b9..87217cbc938 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimInstanceCommand.cs @@ -267,7 +267,7 @@ protected override void ProcessRecord() protected override void EndProcessing() { CimRemoveCimInstance cimRemoveInstance = this.GetOperationAgent(); - if (cimRemoveInstance != null) + if (cimRemoveInstance is not null) { cimRemoveInstance.ProcessRemainActions(this.CmdletOperation); } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/SetCimInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/SetCimInstanceCommand.cs index 7237352b61a..6aff40c0bc8 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/SetCimInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/SetCimInstanceCommand.cs @@ -324,7 +324,7 @@ protected override void ProcessRecord() protected override void EndProcessing() { CimSetCimInstance cimSetCimInstance = this.GetOperationAgent(); - if (cimSetCimInstance != null) + if (cimSetCimInstance is not null) { cimSetCimInstance.ProcessRemainActions(this.CmdletOperation); } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs index d7ba928f6fa..7dd9cab71ed 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs @@ -420,7 +420,7 @@ public static void ValidateNoNullorWhiteSpaceArgument(string obj, string argumen public static string ValidateArgumentIsValidName(string parameterName, string value) { DebugHelper.WriteLogEx(); - if (value != null) + if (value is not null) { string trimed = value.Trim(); // The first character should be contained in set: [A-Za-z_] @@ -447,12 +447,12 @@ public static string ValidateArgumentIsValidName(string parameterName, string va /// Throw if the given value contains any invalid name (class name or property name). public static string[] ValidateArgumentIsValidName(string parameterName, string[] value) { - if (value != null) + if (value is not null) { foreach (string propertyName in value) { // * is wild char supported in select properties - if ((propertyName != null) && string.Equals(propertyName.Trim(), "*", StringComparison.OrdinalIgnoreCase)) + if ((propertyName is not null) && string.Equals(propertyName.Trim(), "*", StringComparison.OrdinalIgnoreCase)) { continue; } diff --git a/src/Microsoft.Management.UI.Internal/HelpWindow/HelpParagraphBuilder.cs b/src/Microsoft.Management.UI.Internal/HelpWindow/HelpParagraphBuilder.cs index 1d4bcacd893..f9c57505ea0 100644 --- a/src/Microsoft.Management.UI.Internal/HelpWindow/HelpParagraphBuilder.cs +++ b/src/Microsoft.Management.UI.Internal/HelpWindow/HelpParagraphBuilder.cs @@ -60,7 +60,7 @@ private enum HelpCategory /// The string value of a property or null if it could not be retrieved. internal static string GetPropertyString(PSObject psObj, string propertyName) { - Debug.Assert(psObj != null, "ensured by caller"); + Debug.Assert(psObj is not null, "ensured by caller"); object value = GetPropertyObject(psObj, propertyName); if (value == null) @@ -138,7 +138,7 @@ internal void AddTextToParagraphBuilder() /// The object property or null if it could not be retrieved. private static PSPropertyInfo GetProperty(PSObject psObj, string propertyName) { - Debug.Assert(psObj != null, "ensured by caller"); + Debug.Assert(psObj is not null, "ensured by caller"); return psObj.Properties[propertyName]; } @@ -151,7 +151,7 @@ private static PSPropertyInfo GetProperty(PSObject psObj, string propertyName) /// The string from the inner psObject property or null if it could not be retrieved. private static string GetInnerPSObjectPropertyString(PSObject psObj, string psObjectName, string propertyName) { - Debug.Assert(psObj != null, "ensured by caller"); + Debug.Assert(psObj is not null, "ensured by caller"); PSObject innerPsObj = GetPropertyObject(psObj, psObjectName) as PSObject; if (innerPsObj == null) @@ -177,7 +177,7 @@ private static string GetInnerPSObjectPropertyString(PSObject psObj, string psOb /// The value of a property or null if the value could not be retrieved. private static object GetPropertyObject(PSObject psObj, string propertyName) { - Debug.Assert(psObj != null, "ensured by caller"); + Debug.Assert(psObj is not null, "ensured by caller"); PSPropertyInfo property = HelpParagraphBuilder.GetProperty(psObj, propertyName); if (property == null) { @@ -206,7 +206,7 @@ private static object GetPropertyObject(PSObject psObj, string propertyName) private static string GetTextFromArray(PSObject psObj, string propertyText) { PSObject[] introductionObjects = HelpParagraphBuilder.GetPropertyObject(psObj, propertyText) as PSObject[]; - if (introductionObjects != null && introductionObjects.Length > 0) + if (introductionObjects is not null && introductionObjects.Length > 0) { return GetPropertyString(introductionObjects[0], "text"); } @@ -225,7 +225,7 @@ private static int LargestSize(params string[] strs) foreach (string str in strs) { - if (str != null && str.Length > returnValue) + if (str is not null && str.Length > returnValue) { returnValue = str.Length; } @@ -520,7 +520,7 @@ private void AddExamples(bool setting, string sectionTitle) continue; } - if (title != null) + if (title is not null) { this.AddText(HelpParagraphBuilder.AddIndent(title), false); this.AddText("\r\n", false); @@ -598,10 +598,10 @@ private void AddMembers(bool setting, string sectionTitle) { PSObject fieldData = HelpParagraphBuilder.GetPropertyObject(member, "fieldData") as PSObject; - if (fieldData != null) + if (fieldData is not null) { PSObject propertyTypeObject = HelpParagraphBuilder.GetPropertyObject(fieldData, "type") as PSObject; - if (propertyTypeObject != null) + if (propertyTypeObject is not null) { propertyType = GetPropertyString(propertyTypeObject, "name"); description = GetPropertyString(propertyTypeObject, "description"); @@ -620,7 +620,7 @@ private void AddMembers(bool setting, string sectionTitle) this.AddText(HelpParagraphBuilder.AddIndent(string.Empty), false); this.AddText(memberText, true); - if (description != null) + if (description is not null) { this.AddText(HelpParagraphBuilder.AddIndent(description, 2), false); this.AddText("\r\n", false); @@ -646,10 +646,10 @@ private static void FormatMethodData(PSObject member, string name, out string me // Get method return type PSObject returnTypeObject = HelpParagraphBuilder.GetPropertyObject(member, "returnValue") as PSObject; - if (returnTypeObject != null) + if (returnTypeObject is not null) { PSObject returnTypeData = HelpParagraphBuilder.GetPropertyObject(returnTypeObject, "type") as PSObject; - if (returnTypeData != null) + if (returnTypeData is not null) { returnType = GetPropertyString(returnTypeData, "name"); } @@ -657,7 +657,7 @@ private static void FormatMethodData(PSObject member, string name, out string me // Get method description. PSObject[] methodDescriptions = HelpParagraphBuilder.GetPropertyObject(member, "introduction") as PSObject[]; - if (methodDescriptions != null) + if (methodDescriptions is not null) { foreach (var methodDescription in methodDescriptions) { @@ -673,11 +673,11 @@ private static void FormatMethodData(PSObject member, string name, out string me // Get method parameters. PSObject parametersObject = HelpParagraphBuilder.GetPropertyObject(member, "parameters") as PSObject; - if (parametersObject != null) + if (parametersObject is not null) { PSObject[] paramObject = HelpParagraphBuilder.GetPropertyObject(parametersObject, "parameter") as PSObject[]; - if (paramObject != null) + if (paramObject is not null) { foreach (var param in paramObject) { @@ -686,7 +686,7 @@ private static void FormatMethodData(PSObject member, string name, out string me PSObject parameterTypeData = HelpParagraphBuilder.GetPropertyObject(param, "type") as PSObject; - if (parameterTypeData != null) + if (parameterTypeData is not null) { parameterType = GetPropertyString(parameterTypeData, "name"); @@ -787,7 +787,7 @@ private void AddParameters(bool setting, string sectionTitle, string paramProper this.AddText(parameterText, false); - if (description != null) + if (description is not null) { this.AddText(HelpParagraphBuilder.AddIndent(description, 2), false); this.AddText("\r\n", false); @@ -950,7 +950,7 @@ private void AddInputOrOutputEntries(bool setting, string sectionTitle, string i this.AddText(HelpParagraphBuilder.AddIndent(type), false); this.AddText("\r\n", false); - if (description != null) + if (description is not null) { this.AddText(HelpParagraphBuilder.AddIndent(description), false); this.AddText("\r\n", false); diff --git a/src/Microsoft.Management.UI.Internal/HelpWindow/HelpViewModel.cs b/src/Microsoft.Management.UI.Internal/HelpWindow/HelpViewModel.cs index 7cbe4b0c74e..e72c1fc1afa 100644 --- a/src/Microsoft.Management.UI.Internal/HelpWindow/HelpViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/HelpWindow/HelpViewModel.cs @@ -55,8 +55,8 @@ internal class HelpViewModel : INotifyPropertyChanged /// Paragraph in which help text is built/searched. internal HelpViewModel(PSObject psObj, Paragraph documentParagraph) { - Debug.Assert(psObj != null, "ensured by caller"); - Debug.Assert(documentParagraph != null, "ensured by caller"); + Debug.Assert(psObj is not null, "ensured by caller"); + Debug.Assert(documentParagraph is not null, "ensured by caller"); this.helpBuilder = new HelpParagraphBuilder(documentParagraph, psObj); this.helpBuilder.BuildParagraph(); @@ -274,7 +274,7 @@ private void SetMatchesLabel() private void OnNotifyPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = this.PropertyChanged; - if (handler != null) + if (handler is not null) { handler(this, new PropertyChangedEventArgs(propertyName)); } diff --git a/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs b/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs index 822e4c05026..d7eb1984d6c 100644 --- a/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs +++ b/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs @@ -302,7 +302,7 @@ private void AddHighlight(int start, int length) private void OnNotifyPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = this.PropertyChanged; - if (handler != null) + if (handler is not null) { handler(this, new PropertyChangedEventArgs(propertyName)); } diff --git a/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphSearcher.cs b/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphSearcher.cs index e71a27bac8b..48e1e0d2a4b 100644 --- a/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphSearcher.cs +++ b/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphSearcher.cs @@ -43,13 +43,13 @@ internal ParagraphSearcher() /// The next highlight starting at the . internal Run MoveAndHighlightNextNextMatch(bool forward, TextPointer caretPosition) { - Debug.Assert(caretPosition != null, "a caret position is allways valid"); - Debug.Assert(caretPosition.Parent != null && caretPosition.Parent is Run, "a caret PArent is allways a valid Run"); + Debug.Assert(caretPosition is not null, "a caret position is allways valid"); + Debug.Assert(caretPosition.Parent is not null && caretPosition.Parent is Run, "a caret PArent is allways a valid Run"); Run caretRun = (Run)caretPosition.Parent; Run currentRun; - if (this.currentHighlightedMatch != null) + if (this.currentHighlightedMatch is not null) { // restore the curent highlighted background to plain highlighted this.currentHighlightedMatch.Background = ParagraphSearcher.HighlightBrush; @@ -84,7 +84,7 @@ internal Run MoveAndHighlightNextNextMatch(bool forward, TextPointer caretPositi } this.currentHighlightedMatch = currentRun; - if (this.currentHighlightedMatch != null) + if (this.currentHighlightedMatch is not null) { // restore the curent highligthed background to current highlighted this.currentHighlightedMatch.Background = ParagraphSearcher.CurrentHighlightBrush; @@ -114,7 +114,7 @@ private static bool Ishighlighted(Run run) } SolidColorBrush background = run.Background as SolidColorBrush; - if (background != null && background == ParagraphSearcher.HighlightBrush) + if (background is not null && background == ParagraphSearcher.HighlightBrush) { return true; } @@ -136,11 +136,11 @@ private static Run GetNextRun(Run currentRun, bool forward) if (forward) { - nextInline = parentBold != null ? ((Inline)parentBold).NextInline : currentRun.NextInline; + nextInline = parentBold is not null ? ((Inline)parentBold).NextInline : currentRun.NextInline; } else { - nextInline = parentBold != null ? ((Inline)parentBold).PreviousInline : currentRun.PreviousInline; + nextInline = parentBold is not null ? ((Inline)parentBold).PreviousInline : currentRun.PreviousInline; } return GetRun(nextInline); @@ -155,7 +155,7 @@ private static Run GetNextRun(Run currentRun, bool forward) private static Run GetRun(Inline inline) { Bold inlineBold = inline as Bold; - if (inlineBold != null) + if (inlineBold is not null) { return (Run)inlineBold.Inlines.FirstInline; } @@ -175,7 +175,7 @@ private static Run GetRun(Inline inline) /// private static Run GetNextMatch(Run currentRun, bool forward) { - while (currentRun != null) + while (currentRun is not null) { if (ParagraphSearcher.Ishighlighted(currentRun)) { @@ -196,8 +196,8 @@ private static Run GetNextMatch(Run currentRun, bool forward) private static Paragraph GetParagraph(Run run) { Bold parentBold = run.Parent as Bold; - Paragraph parentParagraph = (parentBold != null ? parentBold.Parent : run.Parent) as Paragraph; - Debug.Assert(parentParagraph != null, "the documents we are saerching are built with ParagraphBuilder, which builds the document like this"); + Paragraph parentParagraph = (parentBold is not null ? parentBold.Parent : run.Parent) as Paragraph; + Debug.Assert(parentParagraph is not null, "the documents we are saerching are built with ParagraphBuilder, which builds the document like this"); return parentParagraph; } @@ -221,7 +221,7 @@ private static bool IsFirstRun(Run run) /// The first or last run in the paragraph containing . private static Run GetFirstOrLastRun(Run caretRun, bool forward) { - Debug.Assert(caretRun != null, "a caret run is allways valid"); + Debug.Assert(caretRun is not null, "a caret run is allways valid"); Paragraph paragraph = GetParagraph(caretRun); diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/CommandHelper.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/CommandHelper.cs index c9c8606f899..b577205fd74 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/CommandHelper.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/CommandHelper.cs @@ -15,7 +15,7 @@ internal static class CommandHelper internal static void ExecuteCommand(ICommand command, object parameter, IInputElement target) { RoutedCommand command2 = command as RoutedCommand; - if (command2 != null) + if (command2 is not null) { if (command2.CanExecute(parameter, target)) { @@ -37,7 +37,7 @@ internal static bool CanExecuteCommand(ICommand command, object parameter, IInpu RoutedCommand command2 = command as RoutedCommand; - if (command2 != null) + if (command2 is not null) { return command2.CanExecute(parameter, target); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/DismissiblePopup.Generated.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/DismissiblePopup.Generated.cs index 76e3206f1f5..abadcf99eef 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/DismissiblePopup.Generated.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/DismissiblePopup.Generated.cs @@ -247,7 +247,7 @@ protected virtual void OnSetFocusOnCloseElementChanged(PropertyChangedEventArgs< /// private void RaisePropertyChangedEvent(EventHandler> eh, PropertyChangedEventArgs e) { - if (eh != null) + if (eh is not null) { eh(this,e); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/DismissiblePopup.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/DismissiblePopup.cs index 582be1c7ecd..7f765dc9960 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/DismissiblePopup.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/DismissiblePopup.cs @@ -57,12 +57,12 @@ protected override void OnClosed(EventArgs e) if (this.SetFocusOnClose) { // Find a control to set focus on. - if (this.SetFocusOnCloseElement != null) + if (this.SetFocusOnCloseElement is not null) { // The focus target is set explicitly. this.SetFocus(this.SetFocusOnCloseElement); } - else if (this.PlacementTarget != null) + else if (this.PlacementTarget is not null) { // Use PlacementTarget as a first chance option. this.SetFocus(this.PlacementTarget); @@ -71,7 +71,7 @@ protected override void OnClosed(EventArgs e) { // Use parent UIObject when neither FocusOnCloseTarget nor PlacementTarget is set. UIElement parent = this.Parent as UIElement; - if (parent != null) + if (parent is not null) { this.SetFocus(parent); } @@ -110,7 +110,7 @@ private FrameworkElement FindPopupRoot() element = VisualTreeHelper.GetParent(element); } - Debug.Assert(element != null, "element not null"); + Debug.Assert(element is not null, "element not null"); return (FrameworkElement)element; } @@ -141,7 +141,7 @@ partial void OnDismissPopupExecutedImplementation(ExecutedRoutedEventArgs e) private void FocusChild() { - if (this.Child != null) + if (this.Child is not null) { this.Child.MoveFocus(new TraversalRequest(FocusNavigationDirection.First)); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/IntegralConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/IntegralConverter.cs index dff537f00bb..f04695bb98f 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/IntegralConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/IntegralConverter.cs @@ -52,7 +52,7 @@ public object Convert(object[] values, Type targetType, object parameter, System double padding = 0; - if (parameter != null) + if (parameter is not null) { padding = double.Parse((string)parameter, CultureInfo.InvariantCulture); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/IsNotNullConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/IsNotNullConverter.cs index 265e0266c53..3b6d29722ab 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/IsNotNullConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/IsNotNullConverter.cs @@ -25,7 +25,7 @@ public class IsNotNullConverter : IValueConverter /// Returns true if value is not null, false otherwise. public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { - return value != null; + return value is not null; } /// diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/KeyboardHelp.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/KeyboardHelp.cs index 90684f3f6cc..707fd458e73 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/KeyboardHelp.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/KeyboardHelp.cs @@ -27,7 +27,7 @@ internal static class KeyboardHelp /// The logical direction. public static LogicalDirection GetLogicalDirection(DependencyObject element, Key key) { - Debug.Assert(element != null, "element not null"); + Debug.Assert(element is not null, "element not null"); bool rightToLeft = IsElementRightToLeft(element); @@ -66,7 +66,7 @@ public static LogicalDirection GetLogicalDirection(DependencyObject element, Key /// The focus direction. public static FocusNavigationDirection GetNavigationDirection(DependencyObject element, Key key) { - Debug.Assert(element != null, "element not null"); + Debug.Assert(element is not null, "element not null"); Debug.Assert(IsFlowDirectionKey(key)); bool rightToLeft = IsElementRightToLeft(element); diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizer.Generated.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizer.Generated.cs index 799cd260e12..4b076e68097 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizer.Generated.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizer.Generated.cs @@ -440,7 +440,7 @@ protected virtual void OnTextContentPropertyNameChanged(PropertyChangedEventArgs /// private void RaisePropertyChangedEvent(EventHandler> eh, PropertyChangedEventArgs e) { - if (eh != null) + if (eh is not null) { eh(this,e); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizerItem.Generated.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizerItem.Generated.cs index e51172095a1..b4142b978fa 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizerItem.Generated.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizerItem.Generated.cs @@ -103,7 +103,7 @@ protected virtual void OnTextContentPropertyNameChanged(PropertyChangedEventArgs /// private void RaisePropertyChangedEvent(EventHandler> eh, PropertyChangedEventArgs e) { - if (eh != null) + if (eh is not null) { eh(this,e); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizerItem.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizerItem.cs index 469ed5aec77..993aab8c82e 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizerItem.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizerItem.cs @@ -35,7 +35,7 @@ public bool IsInEditMode { get { - return (this.renameButton != null) ? this.renameButton.IsChecked.Value : false; + return (this.renameButton is not null) ? this.renameButton.IsChecked.Value : false; } } @@ -234,7 +234,7 @@ private void AttachToVisualTree() this.editBox.LostFocus += this.EditBox_LostFocus; this.templatedParent = this.TemplatedParent as FrameworkElement; - if (this.templatedParent != null) + if (this.templatedParent is not null) { this.templatedParent.KeyDown += this.TemplatedParent_OnKeyDown; } @@ -242,14 +242,14 @@ private void AttachToVisualTree() private void DetachFromVisualTree() { - if (this.editBox != null) + if (this.editBox is not null) { this.editBox.IsVisibleChanged -= this.EditBox_IsVisibleChanged; this.editBox.KeyDown -= this.EditBox_KeyDown; this.editBox.LostFocus -= this.EditBox_LostFocus; } - if (this.templatedParent != null) + if (this.templatedParent is not null) { this.templatedParent.KeyDown -= this.TemplatedParent_OnKeyDown; } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/MessageTextBox.Generated.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/MessageTextBox.Generated.cs index e204886880a..30998a4d316 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/MessageTextBox.Generated.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/MessageTextBox.Generated.cs @@ -122,7 +122,7 @@ protected virtual void OnIsBackgroundTextShownChanged(PropertyChangedEventArgs private void RaisePropertyChangedEvent(EventHandler> eh, PropertyChangedEventArgs e) { - if (eh != null) + if (eh is not null) { eh(this,e); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/PickerBase.Generated.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/PickerBase.Generated.cs index f8b8bec0a5a..152db92f5ef 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/PickerBase.Generated.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/PickerBase.Generated.cs @@ -214,7 +214,7 @@ protected virtual void OnIsOpenChanged(PropertyChangedEventArgs e) /// private void RaisePropertyChangedEvent(EventHandler> eh, PropertyChangedEventArgs e) { - if (eh != null) + if (eh is not null) { eh(this,e); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/PickerBase.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/PickerBase.cs index bb4b6c61511..73caf1c5ded 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/PickerBase.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/PickerBase.cs @@ -51,7 +51,7 @@ private void ApplyDropDownButtonTemplate() return; } - if (this.DropDownButtonTemplate != null && !ReferenceEquals(this.dropDownButton.Template, this.DropDownButtonTemplate)) + if (this.DropDownButtonTemplate is not null && !ReferenceEquals(this.dropDownButton.Template, this.DropDownButtonTemplate)) { this.dropDownButton.Template = this.DropDownButtonTemplate; } @@ -79,7 +79,7 @@ private void FocusDropDown() this.dropDown.Loaded += this.DropDown_Loaded_FocusDropDown; } - if (this.dropDown.Child != null && !this.dropDown.IsAncestorOf((DependencyObject)Keyboard.FocusedElement)) + if (this.dropDown.Child is not null && !this.dropDown.IsAncestorOf((DependencyObject)Keyboard.FocusedElement)) { this.dropDown.Child.MoveFocus(new TraversalRequest(FocusNavigationDirection.First)); } @@ -122,7 +122,7 @@ private void AttachToVisualTree() private void DetachFromVisualTree() { - if (this.dropDown != null) + if (this.dropDown is not null) { this.dropDown.Opened -= this.DropDown_Opened; this.dropDown.Closed -= this.DropDown_Closed; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/PopupControlButton.Generated.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/PopupControlButton.Generated.cs index c358ce69985..86c1ef1b117 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/PopupControlButton.Generated.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/PopupControlButton.Generated.cs @@ -72,7 +72,7 @@ protected virtual void OnIsPopupOpenChanged(PropertyChangedEventArgs e) /// private void RaisePropertyChangedEvent(EventHandler> eh, PropertyChangedEventArgs e) { - if (eh != null) + if (eh is not null) { eh(this,e); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ReadOnlyObservableAsyncCollection.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ReadOnlyObservableAsyncCollection.cs index 7734bc4903c..0ec7a2d629a 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ReadOnlyObservableAsyncCollection.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ReadOnlyObservableAsyncCollection.cs @@ -101,7 +101,7 @@ private void OnCollectionChanged(NotifyCollectionChangedEventArgs args) { NotifyCollectionChangedEventHandler eh = this.CollectionChanged; - if (eh != null) + if (eh is not null) { eh(this, args); } @@ -111,7 +111,7 @@ private void OnPropertyChanged(PropertyChangedEventArgs args) { PropertyChangedEventHandler eh = this.PropertyChanged; - if (eh != null) + if (eh is not null) { eh(this, args); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ScalableImage.Generated.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ScalableImage.Generated.cs index 6d682160e49..166d1ecee4a 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ScalableImage.Generated.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ScalableImage.Generated.cs @@ -70,7 +70,7 @@ protected virtual void OnSourceChanged(PropertyChangedEventArgs private void RaisePropertyChangedEvent(EventHandler> eh, PropertyChangedEventArgs e) { - if (eh != null) + if (eh is not null) { eh(this,e); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ScalableImage.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ScalableImage.cs index b994bb1a29a..f46a9e3f0a9 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ScalableImage.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ScalableImage.cs @@ -40,7 +40,7 @@ public ScalableImage() protected override Size ArrangeOverride(Size finalSize) { // If a vector is provided, specify that the control will use all available area \\ - if (this.Source != null && this.Source.Brush != null) + if (this.Source is not null && this.Source.Brush is not null) { return finalSize; } @@ -64,11 +64,11 @@ protected override void OnRender(DrawingContext drawingContext) } // Prefer the vector if it's provided \\ - if (this.Source.Brush != null) + if (this.Source.Brush is not null) { drawingContext.DrawRectangle(this.Source.Brush, null, renderArea); } - else if (this.Source.Image != null) + else if (this.Source.Image is not null) { drawingContext.DrawImage(this.Source.Image, renderArea); } @@ -91,7 +91,7 @@ protected override Geometry GetLayoutClip(Size layoutSlotSize) partial void OnSourceChangedImplementation(PropertyChangedEventArgs e) { - if (e.NewValue != null) + if (e.NewValue is not null) { // If a width was provided in the source, use it now \\ if (!e.NewValue.Size.Width.Equals(double.NaN)) diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ScalableImageSource.Generated.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ScalableImageSource.Generated.cs index aaafd913976..7d4760d4056 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ScalableImageSource.Generated.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ScalableImageSource.Generated.cs @@ -217,7 +217,7 @@ protected virtual void OnSizeChanged(PropertyChangedEventArgs e) /// private void RaisePropertyChangedEvent(EventHandler> eh, PropertyChangedEventArgs e) { - if (eh != null) + if (eh is not null) { eh(this,e); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/TextBlockService.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/TextBlockService.cs index 888c03944a2..20a44283d2e 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/TextBlockService.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/TextBlockService.cs @@ -49,7 +49,7 @@ private static void OnTextBlockPropertyChanged(object sender, EventArgs e) private static void UpdateIsTextTrimmed(TextBlock textBlock) { - Debug.Assert(textBlock != null, "textblock not null"); + Debug.Assert(textBlock is not null, "textblock not null"); if (textBlock.TextWrapping != TextWrapping.NoWrap || textBlock.TextTrimming == TextTrimming.None) { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/WpfHelp.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/WpfHelp.cs index 23ff80d9974..c62704de62c 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/WpfHelp.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/WpfHelp.cs @@ -166,7 +166,7 @@ public static void RemoveFromParent(FrameworkElement element) ContentControl parentContentControl = element.Parent as ContentControl; - if (parentContentControl != null) + if (parentContentControl is not null) { parentContentControl.Content = null; return; @@ -174,7 +174,7 @@ public static void RemoveFromParent(FrameworkElement element) var parentDecorator = element.Parent as Decorator; - if (parentDecorator != null) + if (parentDecorator is not null) { parentDecorator.Child = null; return; @@ -182,7 +182,7 @@ public static void RemoveFromParent(FrameworkElement element) ItemsControl parentItemsControl = element.Parent as ItemsControl; - if (parentItemsControl != null) + if (parentItemsControl is not null) { parentItemsControl.Items.Remove(element); return; @@ -190,7 +190,7 @@ public static void RemoveFromParent(FrameworkElement element) Panel parentPanel = element.Parent as Panel; - if (parentPanel != null) + if (parentPanel is not null) { parentPanel.Children.Remove(element); return; @@ -198,7 +198,7 @@ public static void RemoveFromParent(FrameworkElement element) var parentAdorner = element.Parent as UIElementAdorner; - if (parentAdorner != null) + if (parentAdorner is not null) { parentAdorner.Child = null; return; @@ -227,7 +227,7 @@ public static void AddChild(FrameworkElement parent, FrameworkElement element) ContentControl parentContentControl = parent as ContentControl; - if (parentContentControl != null) + if (parentContentControl is not null) { parentContentControl.Content = element; return; @@ -235,7 +235,7 @@ public static void AddChild(FrameworkElement parent, FrameworkElement element) var parentDecorator = parent as Decorator; - if (parentDecorator != null) + if (parentDecorator is not null) { parentDecorator.Child = element; return; @@ -243,7 +243,7 @@ public static void AddChild(FrameworkElement parent, FrameworkElement element) ItemsControl parentItemsControl = parent as ItemsControl; - if (parentItemsControl != null) + if (parentItemsControl is not null) { parentItemsControl.Items.Add(element); return; @@ -251,7 +251,7 @@ public static void AddChild(FrameworkElement parent, FrameworkElement element) Panel parentPanel = parent as Panel; - if (parentPanel != null) + if (parentPanel is not null) { parentPanel.Children.Add(element); return; @@ -284,7 +284,7 @@ public static T GetVisualChild(DependencyObject obj) where T : DependencyObje var element = elementQueue.Dequeue(); T item = element as T; - if (item != null) + if (item is not null) { return item; } @@ -309,7 +309,7 @@ public static T GetVisualChild(DependencyObject obj) where T : DependencyObje public static List FindVisualChildren(DependencyObject obj) where T : DependencyObject { - Debug.Assert(obj != null, "obj is null"); + Debug.Assert(obj is not null, "obj is null"); if (obj == null) { throw new ArgumentNullException("obj"); @@ -323,7 +323,7 @@ public static List FindVisualChildren(DependencyObject obj) DependencyObject childObj = VisualTreeHelper.GetChild(obj, i); T child = childObj as T; - if (child != null) + if (child is not null) { childrenOfType.Add(child); } @@ -355,11 +355,11 @@ public static T FindVisualAncestorData(this DependencyObject obj) FrameworkElement parent = obj.FindVisualAncestor(); - if (parent != null) + if (parent is not null) { T data = parent.DataContext as T; - if (data != null) + if (data is not null) { return data; } @@ -388,11 +388,11 @@ public static T FindVisualAncestor(this DependencyObject @object) where T : c DependencyObject parent = VisualTreeHelper.GetParent(@object); - if (parent != null) + if (parent is not null) { T parentObj = parent as T; - if (parentObj != null) + if (parentObj is not null) { return parentObj; } @@ -450,7 +450,7 @@ public static T GetOptionalTemplateChild(Control templateParent, string child object templatePart = templateParent.Template.FindName(childName, templateParent); T item = templatePart as T; - if (item == null && templatePart != null) + if (item == null && templatePart is not null) { HandleWrongTemplatePartType(childName); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/ExpanderButton.cs b/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/ExpanderButton.cs index b641811444e..cdabccfbd32 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/ExpanderButton.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/ExpanderButton.cs @@ -64,7 +64,7 @@ protected void OnIsCheckedChanged(DependencyPropertyChangedEventArgs args) { var peer = UIElementAutomationPeer.CreatePeerForElement(this); - if (peer != null) + if (peer is not null) { var oldValue = (bool?)args.OldValue; var newValue = (bool?)args.NewValue; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/Resizer.Generated.cs b/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/Resizer.Generated.cs index 5e2c18129e6..2e6207812ab 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/Resizer.Generated.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/Resizer.Generated.cs @@ -370,7 +370,7 @@ protected virtual void OnVisibleGripWidthChanged(PropertyChangedEventArgs private void RaisePropertyChangedEvent(EventHandler> eh, PropertyChangedEventArgs e) { - if (eh != null) + if (eh is not null) { eh(this,e); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/Resizer.cs b/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/Resizer.cs index 19c0671bf21..2113350df22 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/Resizer.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/Resizer.cs @@ -78,14 +78,14 @@ internal static Thickness CreateGripThickness(double visibleGripWidth, ResizeGri partial void PreOnApplyTemplate() { - if (this.rightGrip != null) + if (this.rightGrip is not null) { this.rightGrip.DragDelta -= this.OnRightGripDragDelta; this.rightGrip.DragStarted -= this.OnRightGripDragStarted; this.rightGrip.DragCompleted -= this.OnRightGripDragCompleted; } - if (this.leftGrip != null) + if (this.leftGrip is not null) { this.leftGrip.DragDelta -= this.OnLeftGripDragDelta; this.leftGrip.DragStarted -= this.OnLeftGripDragStarted; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/UIElementAdorner.Generated.cs b/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/UIElementAdorner.Generated.cs index 7e60d4c6ffc..ff7b9dbfd75 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/UIElementAdorner.Generated.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/UIElementAdorner.Generated.cs @@ -59,7 +59,7 @@ static private void ChildProperty_PropertyChanged(DependencyObject o, Dependency private void RaiseChildChanged(PropertyChangedEventArgs e) { var eh = this.ChildChanged; - if (eh != null) + if (eh is not null) { eh(this,e); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/UIElementAdorner.cs b/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/UIElementAdorner.cs index 987a1170890..a37e92df21e 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/UIElementAdorner.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/UIElementAdorner.cs @@ -56,7 +56,7 @@ protected override int VisualChildrenCount /// A Size object representing the amount of layout space needed by the popupAdorner. protected override Size MeasureOverride(Size constraint) { - if (this.Child != null) + if (this.Child is not null) { this.Child.Measure(constraint); return this.Child.DesiredSize; @@ -74,7 +74,7 @@ protected override Size MeasureOverride(Size constraint) /// The actual size used. protected override Size ArrangeOverride(Size finalSize) { - if (this.Child != null) + if (this.Child is not null) { Point location = new Point(0, 0); Rect rect = new Rect(location, finalSize); @@ -89,13 +89,13 @@ protected override Size ArrangeOverride(Size finalSize) partial void OnChildChangedImplementation(PropertyChangedEventArgs e) { - if (e.OldValue != null) + if (e.OldValue is not null) { this.children.Remove(e.OldValue); this.RemoveLogicalChild(e.OldValue); } - if (this.Child != null) + if (this.Child is not null) { this.children.Add(this.Child); this.AddLogicalChild(this.Child); diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/DefaultFilterRuleCustomizationFactory.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/DefaultFilterRuleCustomizationFactory.cs index bd5faf32d63..6d779538f81 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/DefaultFilterRuleCustomizationFactory.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/DefaultFilterRuleCustomizationFactory.cs @@ -201,7 +201,7 @@ private bool TryGetGenericParameterForComparableValueFilterRule(FilterRule rule, genericParameter = null; TextFilterRule textRule = rule as TextFilterRule; - if (textRule != null) + if (textRule is not null) { genericParameter = typeof(string); return true; @@ -219,7 +219,7 @@ private bool TryGetGenericParameterForComparableValueFilterRule(FilterRule rule, private object GetValueFromValidatingValue(FilterRule rule, string propertyName) { - Debug.Assert(rule != null && !string.IsNullOrEmpty(propertyName), "rule and propertyname are not null"); + Debug.Assert(rule is not null && !string.IsNullOrEmpty(propertyName), "rule and propertyname are not null"); // NOTE: This isn't needed but OACR is complaining if (rule == null) @@ -238,7 +238,7 @@ private object GetValueFromValidatingValue(FilterRule rule, string propertyName) private void SetValueOnValidatingValue(FilterRule rule, string propertyName, object value) { - Debug.Assert(rule != null && !string.IsNullOrEmpty(propertyName), "rule and propertyname are not null"); + Debug.Assert(rule is not null && !string.IsNullOrEmpty(propertyName), "rule and propertyname are not null"); // NOTE: This isn't needed but OACR is complaining if (rule == null) @@ -261,7 +261,7 @@ private void SetValueOnValidatingValue(FilterRule rule, string propertyName, obj private bool TryTransferValuesAsSingleValueComparableValueFilterRule(FilterRule oldRule, FilterRule newRule) { - Debug.Assert(oldRule != null && newRule != null, "oldrule and newrule are not null"); + Debug.Assert(oldRule is not null && newRule is not null, "oldrule and newrule are not null"); bool areCorrectType = this.IsSingleValueComparableValueFilterRule(oldRule) && this.IsSingleValueComparableValueFilterRule(newRule); @@ -278,7 +278,7 @@ private bool TryTransferValuesAsSingleValueComparableValueFilterRule(FilterRule private bool TryClearValueFromSingleValueComparableValueFilterRule(FilterRule rule) { - Debug.Assert(rule != null, "rule is not null"); + Debug.Assert(rule is not null, "rule is not null"); if (!this.IsSingleValueComparableValueFilterRule(rule)) { @@ -292,7 +292,7 @@ private bool TryClearValueFromSingleValueComparableValueFilterRule(FilterRule ru private bool IsSingleValueComparableValueFilterRule(FilterRule rule) { - Debug.Assert(rule != null, "rule is not null"); + Debug.Assert(rule is not null, "rule is not null"); Type genericParameter; if (!this.TryGetGenericParameterForComparableValueFilterRule(rule, out genericParameter)) @@ -313,7 +313,7 @@ private bool IsSingleValueComparableValueFilterRule(FilterRule rule) private bool TryClearIsBetweenFilterRule(FilterRule rule) { - Debug.Assert(rule != null, "rule is not null"); + Debug.Assert(rule is not null, "rule is not null"); if (!this.IsIsBetweenFilterRule(rule)) { @@ -328,7 +328,7 @@ private bool TryClearIsBetweenFilterRule(FilterRule rule) private bool IsIsBetweenFilterRule(FilterRule rule) { - Debug.Assert(rule != null, "rule is not null"); + Debug.Assert(rule is not null, "rule is not null"); Type genericParameter; if (!this.TryGetGenericParameterForComparableValueFilterRule(rule, out genericParameter)) diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterEvaluator.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterEvaluator.cs index 2b33153a983..d2988537dc1 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterEvaluator.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterEvaluator.cs @@ -127,7 +127,7 @@ public FilterExpressionNode FilterExpression foreach (IFilterExpressionProvider provider in this.FilterExpressionProviders) { FilterExpressionNode node = provider.FilterExpression; - if (node != null) + if (node is not null) { andNode.Children.Add(node); } @@ -185,7 +185,7 @@ protected void NotifyPropertyChanged(string propertyName) PropertyChangedEventHandler eh = this.PropertyChanged; - if (eh != null) + if (eh is not null) { eh(this, new PropertyChangedEventArgs(propertyName)); } @@ -208,7 +208,7 @@ protected void NotifyPropertyChanged(string propertyName) protected virtual void NotifyFilterExpressionChanged() { EventHandler eh = this.FilterExpressionChanged; - if (eh != null) + if (eh is not null) { eh(this, new EventArgs()); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionNode.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionNode.cs index e9e41b93f20..7b322723ed5 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionNode.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionNode.cs @@ -38,7 +38,7 @@ public ICollection FindAll() var ts = new List(); var operandNode = this as FilterExpressionOperandNode; - if (operandNode != null) + if (operandNode is not null) { if (typeof(T).IsInstanceOfType(operandNode.Rule)) { @@ -49,7 +49,7 @@ public ICollection FindAll() } var operatorAndNode = this as FilterExpressionAndOperatorNode; - if (operatorAndNode != null) + if (operatorAndNode is not null) { foreach (var childNode in operatorAndNode.Children) { @@ -58,7 +58,7 @@ public ICollection FindAll() } var operatorOrNode = this as FilterExpressionOrOperatorNode; - if (operatorOrNode != null) + if (operatorOrNode is not null) { foreach (var childNode in operatorOrNode.Children) { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionOperandNode.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionOperandNode.cs index f6bfd17377b..95eae582bba 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionOperandNode.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionOperandNode.cs @@ -62,7 +62,7 @@ public FilterExpressionOperandNode(FilterRule rule) /// public override bool Evaluate(object item) { - Debug.Assert(this.Rule != null, "rule is not null"); + Debug.Assert(this.Rule is not null, "rule is not null"); return this.Rule.Evaluate(item); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRuleCustomizationFactory.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRuleCustomizationFactory.cs index 75019cdbf5d..374ac3d08c3 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRuleCustomizationFactory.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRuleCustomizationFactory.cs @@ -26,7 +26,7 @@ public static FilterRuleCustomizationFactory FactoryInstance { get { - Debug.Assert(factoryInstance != null, "factoryInstance not null"); + Debug.Assert(factoryInstance is not null, "factoryInstance not null"); return factoryInstance; } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/FilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/FilterRule.cs index 1c2fc523e86..7d0d9680f46 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/FilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/FilterRule.cs @@ -68,7 +68,7 @@ protected void NotifyEvaluationResultInvalidated() { var eh = this.EvaluationResultInvalidated; - if (eh != null) + if (eh is not null) { eh(this, new EventArgs()); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertiesTextContainsFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertiesTextContainsFilterRule.cs index c29715419ce..5872c88934f 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertiesTextContainsFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertiesTextContainsFilterRule.cs @@ -64,7 +64,7 @@ public override bool Evaluate(object item) continue; } - if (propertyValue != null) + if (propertyValue is not null) { string data = propertyValue.ToString(); diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertyValueSelectorFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertyValueSelectorFilterRule.cs index e8927c74826..961dd077f77 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertyValueSelectorFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertyValueSelectorFilterRule.cs @@ -139,7 +139,7 @@ private bool TryGetPropertyValue(object item, out T propertyValue) { propertyValue = default(T); - Debug.Assert(item != null, "item not null"); + Debug.Assert(item is not null, "item not null"); return FilterRuleCustomizationFactory.FactoryInstance.PropertyValueGetter.TryGetPropertyValue(this.PropertyName, item, out propertyValue); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterUtilities.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterUtilities.cs index f4827d1b454..5a57ba665b6 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterUtilities.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterUtilities.cs @@ -21,7 +21,7 @@ internal static bool TryCastItem(object item, out T castItem) return false; } - bool shouldCastToString = item != null && typeof(string) == typeof(T); + bool shouldCastToString = item is not null && typeof(string) == typeof(T); if (shouldCastToString) { // NOTE: string => T doesn't compile. We confuse the type system diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ItemsControlFilterEvaluator.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ItemsControlFilterEvaluator.cs index d68ead8bc4b..bd958ec9675 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ItemsControlFilterEvaluator.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ItemsControlFilterEvaluator.cs @@ -31,7 +31,7 @@ public ItemsControl FilterTarget set { - if (this.filterTarget != null) + if (this.filterTarget is not null) { this.StopFilter(); } @@ -73,7 +73,7 @@ public override void StartFilter() // Cache the expression for filtering so subsequent changes are ignored \\ this.CachedFilterExpression = this.FilterExpression; - if (this.CachedFilterExpression != null) + if (this.CachedFilterExpression is not null) { this.FilterTarget.Items.Filter = this.FilterExpressionAdapter; this.FilterStatus = FilterStatus.Applied; @@ -95,7 +95,7 @@ public override void StopFilter() } // Only clear the filter if necessary, since clearing it causes sorting to be re-evaluated \\ - if (this.FilterTarget.Items.Filter != null) + if (this.FilterTarget.Items.Filter is not null) { this.FilterTarget.Items.Filter = null; } @@ -109,7 +109,7 @@ public override void StopFilter() private bool FilterExpressionAdapter(object item) { - Debug.Assert(this.CachedFilterExpression != null, "not null"); + Debug.Assert(this.CachedFilterExpression is not null, "not null"); try { @@ -129,7 +129,7 @@ private bool FilterExpressionAdapter(object item) private bool TryNotifyFilterException(Exception e) { EventHandler eh = this.FilterExceptionOccurred; - if (eh != null) + if (eh is not null) { eh(this, new FilterExceptionEventArgs(e)); return true; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingSelectorValue.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingSelectorValue.cs index ed5389668e6..ee20dc7b628 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingSelectorValue.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingSelectorValue.cs @@ -130,7 +130,7 @@ public IValueConverter DisplayNameConverter set { - if (value != null && !value.GetType().IsSerializable) + if (value is not null && !value.GetType().IsSerializable) { throw new ArgumentException("The DisplayNameConverter must be serializable.", "value"); } @@ -216,7 +216,7 @@ protected void NotifySelectedValueChanged(T oldValue, T newValue) { EventHandler> eh = this.SelectedValueChanged; - if (eh != null) + if (eh is not null) { eh(this, new PropertyChangedEventArgs(oldValue, newValue)); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValue.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValue.cs index cf9c553f6b4..1207b2825f7 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValue.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValue.cs @@ -192,7 +192,7 @@ private bool TryGetCastValue(object rawValue, out T castValue) private bool TryGetEnumValue(object rawValue, out T castValue) { - Debug.Assert(rawValue != null, "rawValue not null"); + Debug.Assert(rawValue is not null, "rawValue not null"); Debug.Assert(typeof(T).IsEnum, "is enum"); castValue = default(T); diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValueBase.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValueBase.cs index f3959685349..827ba0b69e7 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValueBase.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValueBase.cs @@ -262,7 +262,7 @@ protected void NotifyPropertyChanged(string propertyName) { PropertyChangedEventHandler eh = this.PropertyChanged; - if (eh != null) + if (eh is not null) { eh(this, new PropertyChangedEventArgs(propertyName)); } @@ -304,7 +304,7 @@ private void UpdateValidationResult(string columnName) private void NotifyValidationResultUpdated() { - Debug.Assert(this.cachedValidationResult != null, "not null"); + Debug.Assert(this.cachedValidationResult is not null, "not null"); this.NotifyPropertyChanged("IsValid"); this.NotifyPropertyChanged("Error"); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/AddFilterRulePicker.Generated.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/AddFilterRulePicker.Generated.cs index e326f6542e0..ffbb8bd09f7 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/AddFilterRulePicker.Generated.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/AddFilterRulePicker.Generated.cs @@ -234,7 +234,7 @@ protected virtual void OnIsOpenChanged(PropertyChangedEventArgs e) /// private void RaisePropertyChangedEvent(EventHandler> eh, PropertyChangedEventArgs e) { - if (eh != null) + if (eh is not null) { eh(this,e); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/AddFilterRulePicker.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/AddFilterRulePicker.cs index d41b0a3e532..dc5adcfd9ba 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/AddFilterRulePicker.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/AddFilterRulePicker.cs @@ -49,7 +49,7 @@ public ObservableCollection ColumnFilterRules partial void OnOkAddFilterRulesCanExecuteImplementation(System.Windows.Input.CanExecuteRoutedEventArgs e) { - e.CanExecute = (this.AddFilterRulesCommand != null) + e.CanExecute = (this.AddFilterRulesCommand is not null) ? CommandHelper.CanExecuteCommand(this.AddFilterRulesCommand, null, this.AddFilterRulesCommandTarget) : false; } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/AddFilterRulePickerItem.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/AddFilterRulePickerItem.cs index 24c6eec1889..0dec3bf345a 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/AddFilterRulePickerItem.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/AddFilterRulePickerItem.cs @@ -72,7 +72,7 @@ protected void NotifyPropertyChanged(string propertyName) { PropertyChangedEventHandler eh = this.PropertyChanged; - if (eh != null) + if (eh is not null) { eh(this, new PropertyChangedEventArgs(propertyName)); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanel.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanel.cs index bcc9a01a92c..71331cbf3e9 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanel.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanel.cs @@ -214,7 +214,7 @@ public void ClearContentTemplates() protected virtual void NotifyFilterExpressionChanged() { EventHandler eh = this.FilterExpressionChanged; - if (eh != null) + if (eh is not null) { eh(this, new EventArgs()); } @@ -235,7 +235,7 @@ private void Controller_FilterExpressionChanged(object sender, EventArgs e) partial void OnAddRulesExecutedImplementation(ExecutedRoutedEventArgs e) { - Debug.Assert(e != null, "not null"); + Debug.Assert(e is not null, "not null"); if (e.Parameter == null) { @@ -270,7 +270,7 @@ partial void OnAddRulesExecutedImplementation(ExecutedRoutedEventArgs e) partial void OnRemoveRuleExecutedImplementation(ExecutedRoutedEventArgs e) { - Debug.Assert(e != null, "not null"); + Debug.Assert(e is not null, "not null"); if (e.Parameter == null) { @@ -339,13 +339,13 @@ private void InitializeTemplatesForInputTypes() private void AddFilterRulePanelItemContentTemplate(Type type, string resourceName) { - Debug.Assert(type != null, "not null"); + Debug.Assert(type is not null, "not null"); Debug.Assert(!string.IsNullOrEmpty(resourceName), "not null"); var templateInfo = new ComponentResourceKey(typeof(FilterRulePanel), resourceName); DataTemplate template = (DataTemplate)this.TryFindResource(templateInfo); - Debug.Assert(template != null, "not null"); + Debug.Assert(template is not null, "not null"); this.AddFilterRulePanelItemContentTemplate(type, template); } @@ -356,7 +356,7 @@ private void AddFilterRulePanelItemContentTemplate(Type type, string resourceNam private void AddFilterRuleInternal(FilterRulePanelItem item) { - Debug.Assert(item != null, "not null"); + Debug.Assert(item is not null, "not null"); FilterRulePanelItem newItem = new FilterRulePanelItem(item.Rule.DeepCopy(), item.GroupId); this.Controller.AddFilterRulePanelItem(newItem); @@ -364,7 +364,7 @@ private void AddFilterRuleInternal(FilterRulePanelItem item) private void RemoveFilterRuleInternal(FilterRulePanelItem item) { - Debug.Assert(item != null, "not null"); + Debug.Assert(item is not null, "not null"); this.Controller.RemoveFilterRulePanelItem(item); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelController.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelController.cs index dcec5022d98..10d06b09836 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelController.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelController.cs @@ -48,7 +48,7 @@ public bool HasFilterExpression { get { - return this.FilterExpression != null; + return this.FilterExpression is not null; } } @@ -220,7 +220,7 @@ private FilterExpressionOrOperatorNode CreateFilterExpressionForGroup(int startI private int GetInsertionIndex(FilterRulePanelItem item) { - Debug.Assert(item != null, "not null"); + Debug.Assert(item is not null, "not null"); for (int i = this.filterRulePanelItems.Count - 1; i >= 0; i--) { @@ -267,7 +267,7 @@ private void UpdateFilterRulePanelItemTypes() protected virtual void NotifyFilterExpressionChanged() { EventHandler eh = this.FilterExpressionChanged; - if (eh != null) + if (eh is not null) { eh(this, new EventArgs()); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelItem.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelItem.cs index a1a873cdbc7..a6ad72a9081 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelItem.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelItem.cs @@ -108,7 +108,7 @@ protected void NotifyPropertyChanged(string propertyName) Debug.Assert(!string.IsNullOrEmpty(propertyName), "not null"); PropertyChangedEventHandler eh = this.PropertyChanged; - if (eh != null) + if (eh is not null) { eh(this, new PropertyChangedEventArgs(propertyName)); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRuleTemplateSelector.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRuleTemplateSelector.cs index fc40c3c5768..92bc1d6bfd2 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRuleTemplateSelector.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRuleTemplateSelector.cs @@ -63,7 +63,7 @@ public override DataTemplate SelectTemplate(object item, System.Windows.Dependen type = type.BaseType; } - while (type != null); + while (type is not null); return base.SelectTemplate(item, container); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/InputFieldBackgroundTextConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/InputFieldBackgroundTextConverter.cs index 0017f2a4340..93b616f5e14 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/InputFieldBackgroundTextConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/InputFieldBackgroundTextConverter.cs @@ -71,7 +71,7 @@ public object ConvertBack(object value, Type targetType, object parameter, Syste private bool IsOfTypeValidatingValue(object value) { - Debug.Assert(value != null, "not null"); + Debug.Assert(value is not null, "not null"); Type type = value.GetType(); if (type.IsGenericType == false) @@ -86,7 +86,7 @@ private bool IsOfTypeValidatingValue(object value) private Type GetGenericParameter(object value, CultureInfo culture) { - Debug.Assert(value != null, "not null"); + Debug.Assert(value is not null, "not null"); Debug.Assert(this.IsOfTypeValidatingValue(value), "not null"); return value.GetType().GetGenericArguments()[0]; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchBox.Generated.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchBox.Generated.cs index 3a6c7fedae8..e88eb60d7b5 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchBox.Generated.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchBox.Generated.cs @@ -163,7 +163,7 @@ protected virtual void OnTextChanged(PropertyChangedEventArgs e) /// private void RaisePropertyChangedEvent(EventHandler> eh, PropertyChangedEventArgs e) { - if (eh != null) + if (eh is not null) { eh(this,e); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchBox.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchBox.cs index 25830150939..230cdefddb6 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchBox.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchBox.cs @@ -61,7 +61,7 @@ public bool HasFilterExpression protected virtual void NotifyFilterExpressionChanged() { EventHandler eh = this.FilterExpressionChanged; - if (eh != null) + if (eh is not null) { eh(this, new EventArgs()); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParser.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParser.cs index 04ba32ece6d..b5c8ffdbfd8 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParser.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParser.cs @@ -52,7 +52,7 @@ public bool TryAddSearchableRule(SelectorFilterRule selectorRule) T textRule = selectorRule.AvailableRules.AvailableValues.Find(); - if (textRule != null) + if (textRule is not null) { SearchableRule rule = new SearchableRule("RULE_" + this.SearchableRules.Count.ToString(CultureInfo.InvariantCulture), selectorRule, textRule); @@ -150,7 +150,7 @@ private List ParseMatches(MatchCollection matches) { string value = match.Groups[ValueGroupName].Value; - if (match.Groups[FullTextRuleGroupName].Success && this.FullTextRule != null) + if (match.Groups[FullTextRuleGroupName].Success && this.FullTextRule is not null) { TextFilterRule fullTextRule = (TextFilterRule)this.FullTextRule.DeepCopy(); fullTextRule.Value.Value = value; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ColumnPicker.xaml.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ColumnPicker.xaml.cs index 470a7670860..66e1b57d4ac 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ColumnPicker.xaml.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ColumnPicker.xaml.cs @@ -201,7 +201,7 @@ internal void MoveDownButtonClick(object sender, RoutedEventArgs e) internal void AddButtonClick(object sender, RoutedEventArgs e) { InnerListColumn column = (InnerListColumn)this.PART_NotSelectedList.SelectedItem; - Debug.Assert(column != null, "not null"); + Debug.Assert(column is not null, "not null"); this.SelectedColumns.Add(column); this.NotSelectedColumns.Remove(column); @@ -231,7 +231,7 @@ internal void AddButtonClick(object sender, RoutedEventArgs e) internal void RemoveButtonClick(object sender, RoutedEventArgs e) { InnerListColumn column = (InnerListColumn)this.PART_SelectedList.SelectedItem; - Debug.Assert(column != null, "not null"); + Debug.Assert(column is not null, "not null"); int selectedIndex = this.PART_SelectedList.SelectedIndex; Debug.Assert(selectedIndex >= 0, "greater than or equal to 0"); diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/InnerList.Generated.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/InnerList.Generated.cs index d53c8eb8daf..d468bd9797b 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/InnerList.Generated.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/InnerList.Generated.cs @@ -198,7 +198,7 @@ static private void IsPrimarySortColumnProperty_PropertyChanged(DependencyObject /// private void RaisePropertyChangedEvent(EventHandler> eh, PropertyChangedEventArgs e) { - if (eh != null) + if (eh is not null) { eh(this,e); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/InnerListGridView.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/InnerListGridView.cs index 73222cae639..b51c9ca08e4 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/InnerListGridView.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/InnerListGridView.cs @@ -155,7 +155,7 @@ internal void OnColumnPicker(object sender, RoutedEventArgs e) { this.Columns.Clear(); ObservableCollection newColumns = columnPicker.SelectedColumns; - Debug.Assert(newColumns != null, "SelectedColumns not found"); + Debug.Assert(newColumns is not null, "SelectedColumns not found"); foreach (InnerListColumn column in newColumns) { Debug.Assert(column.Visible, "is visible"); @@ -229,7 +229,7 @@ private void AddOrRemoveNotifications(NotifyCollectionChangedEventArgs e) { if (e.Action != NotifyCollectionChangedAction.Move) { - if (e.OldItems != null) + if (e.OldItems is not null) { foreach (InnerListColumn oldColumn in e.OldItems) { @@ -237,7 +237,7 @@ private void AddOrRemoveNotifications(NotifyCollectionChangedEventArgs e) } } - if (e.NewItems != null) + if (e.NewItems is not null) { foreach (InnerListColumn newColumn in e.NewItems) { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/Innerlist.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/Innerlist.cs index 03c7acdf008..93434f9747c 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/Innerlist.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/Innerlist.cs @@ -271,7 +271,7 @@ public void ClearSort() } // If columns are shown, update them to show none are sorted \\ - if (this.InnerGrid != null) + if (this.InnerGrid is not null) { this.UpdatePrimarySortColumn(); } @@ -294,10 +294,10 @@ protected override void OnItemsSourceChanged(System.Collections.IEnumerable oldV { base.OnItemsSourceChanged(oldValue, newValue); - this.itemsSourceIsEmpty = this.ItemsSource != null && this.ItemsSource.GetEnumerator().MoveNext() == false; + this.itemsSourceIsEmpty = this.ItemsSource is not null && this.ItemsSource.GetEnumerator().MoveNext() == false; // A view can be created if there is data to auto-generate columns, or columns are added programatically \\ - bool canCreateView = (this.ItemsSource != null) && + bool canCreateView = (this.ItemsSource is not null) && (this.itemsSourceIsEmpty == false || this.AutoGenerateColumns == false); if (canCreateView) @@ -328,7 +328,7 @@ protected override void OnItemsChanged(NotifyCollectionChangedEventArgs e) { base.OnItemsChanged(e); - if (e.NewItems != null) + if (e.NewItems is not null) { // If the items source now has items, select the first item \\ if (this.itemsSourceIsEmpty && this.Items.Count > 0) @@ -361,7 +361,7 @@ protected override void OnKeyDown(KeyEventArgs e) // If pressing Left or Right on a column header, move the focus \\ GridViewColumnHeader header = e.OriginalSource as GridViewColumnHeader; - if (header != null) + if (header is not null) { header.MoveFocus(new TraversalRequest(KeyboardHelp.GetNavigationDirection(this, e.Key))); e.Handled = true; @@ -383,7 +383,7 @@ private static void InnerList_OnViewChanged(DependencyObject obj, DependencyProp InnerList thisList = (InnerList)obj; GridView newGrid = e.NewValue as GridView; InnerListGridView innerGrid = e.NewValue as InnerListGridView; - if (newGrid != null && innerGrid == null) + if (newGrid is not null && innerGrid == null) { throw new NotSupportedException(string.Format( CultureInfo.InvariantCulture, @@ -425,7 +425,7 @@ private void SetCollectionView(System.Collections.IEnumerable newValue) else { CollectionViewSource newValueViewSource = newValue as CollectionViewSource; - if (newValueViewSource != null && newValueViewSource.View != null) + if (newValueViewSource is not null && newValueViewSource.View is not null) { this.CollectionView = newValueViewSource.View; } @@ -442,7 +442,7 @@ private void SetCollectionView(System.Collections.IEnumerable newValue) /// InnerList object. private void UpdateViewAndCollectionView(IEnumerable value) { - Debug.Assert(value != null, "value should be non-null"); + Debug.Assert(value is not null, "value should be non-null"); // SetCollectionView deals with a null newEnumerable this.SetCollectionView(value); @@ -450,7 +450,7 @@ private void UpdateViewAndCollectionView(IEnumerable value) this.UpdateView(value); // Generate property changed event. - if (this.ItemSourcesPropertyChanged != null) + if (this.ItemSourcesPropertyChanged is not null) { this.ItemSourcesPropertyChanged(this, new PropertyChangedEventArgs("ItemsSource")); } @@ -482,7 +482,7 @@ private void UpdateView(IEnumerable value) this.View = this.innerGrid; this.SetColumnHeaderActions(); - if (sortedColumn != null && this.Columns.Contains(sortedColumn)) + if (sortedColumn is not null && this.Columns.Contains(sortedColumn)) { this.ApplySort(sortedColumn, false); } @@ -493,7 +493,7 @@ private void UpdateView(IEnumerable value) /// private void ReleaseInnerGridReferences() { - if (this.innerGrid != null) + if (this.innerGrid is not null) { // Tell the inner grid to release its references \\ this.innerGrid.ReleaseReferences(); @@ -503,7 +503,7 @@ private void ReleaseInnerGridReferences() { GridViewColumnHeader header = column.Header as GridViewColumnHeader; - if (header != null) + if (header is not null) { header.Click -= this.Header_Click; header.PreviewKeyDown -= this.Header_KeyDown; @@ -531,7 +531,7 @@ internal void SetColumnHeaderActions() // A string header needs an explicit GridViewColumnHeader // so we can hook up our events string headerString = column.Header as string; - if (headerString != null) + if (headerString is not null) { GridViewColumnHeader columnHeader = new GridViewColumnHeader(); columnHeader.Content = headerString; @@ -540,7 +540,7 @@ internal void SetColumnHeaderActions() GridViewColumnHeader header = column.Header as GridViewColumnHeader; - if (header != null) + if (header is not null) { // header Click header.Click += this.Header_Click; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementList.Generated.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementList.Generated.cs index 3ffb8993185..bb2dd11efef 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementList.Generated.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementList.Generated.cs @@ -786,7 +786,7 @@ protected virtual void OnViewSaverUserActionStateChanged(PropertyChangedEventArg /// private void RaisePropertyChangedEvent(EventHandler> eh, PropertyChangedEventArgs e) { - if (eh != null) + if (eh is not null) { eh(this,e); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementListStateDescriptor.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementListStateDescriptor.cs index 841175c97da..bc14b06e80c 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementListStateDescriptor.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementListStateDescriptor.cs @@ -382,7 +382,7 @@ private void SaveSortOrder(ManagementList subject) } // NOTE : We only support sorting on one property. - if (subject.List.SortedColumn != null) + if (subject.List.SortedColumn is not null) { this.sortOrderPropertyName = subject.List.SortedColumn.DataDescription.PropertyName; } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementListTitle.Generated.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementListTitle.Generated.cs index 6aa6d584e65..43b015ce035 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementListTitle.Generated.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementListTitle.Generated.cs @@ -217,7 +217,7 @@ protected virtual void OnTotalItemCountChanged(PropertyChangedEventArgs e) /// private void RaisePropertyChangedEvent(EventHandler> eh, PropertyChangedEventArgs e) { - if (eh != null) + if (eh is not null) { eh(this,e); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueComparer.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueComparer.cs index 5c9f56daa81..23bab69379f 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueComparer.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueComparer.cs @@ -117,7 +117,7 @@ private int CompareData(object firstValue, object secondValue, StringComparison // If the values are strings, compare them considering stringComparison string firstString = firstValue as string; - if (firstString != null) + if (firstString is not null) { string secondString = secondValue as string; return string.Compare(firstString, secondString, stringComparison); @@ -127,7 +127,7 @@ private int CompareData(object firstValue, object secondValue, StringComparison IComparable firstComparable = firstValue as IComparable; // If the values are comparable use CompareTo(), otherwise compare as string considering stringComparison - if (firstComparable != null) + if (firstComparable is not null) { return firstComparable.CompareTo(secondValue); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueGetter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueGetter.cs index 61a1a71938c..4bce7f715d0 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueGetter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueGetter.cs @@ -97,7 +97,7 @@ private PropertyDescriptor GetPropertyDescriptor(string propertyName, object val PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value); descriptor = properties[propertyName]; - if (descriptor != null) + if (descriptor is not null) { this.cachedProperties.Rows.Add(dataType, propertyName, descriptor); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/managementlist.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/managementlist.cs index 7c36244e0f1..fd9f02bc2d8 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/managementlist.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/managementlist.cs @@ -124,7 +124,7 @@ protected override IEnumerator LogicalChildren partial void OnEvaluatorChangedImplementation(PropertyChangedEventArgs e) { // Unregister the previous evaluator \\ - if (e.OldValue != null) + if (e.OldValue is not null) { e.OldValue.RemoveFilterExpressionProvider(this.SearchBox); e.OldValue.RemoveFilterExpressionProvider(this.FilterRulePanel); @@ -387,7 +387,7 @@ private void ViewManager_ItemDeleted(object sender, DataRoutedEventArgs partial void PreOnApplyTemplate() { - if (this.viewManager != null) + if (this.viewManager is not null) { this.viewManager.ItemSelected -= this.ViewManager_ItemSelected; this.viewManager.ItemDeleted -= this.ViewManager_ItemDeleted; diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButton.xaml.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButton.xaml.cs index 05247f46ff0..3603dde72e6 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButton.xaml.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButton.xaml.cs @@ -31,13 +31,13 @@ public ImageButton() private void ImageButton_Loaded(object sender, System.Windows.RoutedEventArgs e) { object thisAutomationId = this.GetValue(AutomationProperties.AutomationIdProperty); - if (thisAutomationId != null) + if (thisAutomationId is not null) { this.innerButton.SetValue(AutomationProperties.AutomationIdProperty, thisAutomationId); } object thisAutomationName = this.GetValue(AutomationProperties.NameProperty); - if (thisAutomationName != null) + if (thisAutomationName is not null) { this.innerButton.SetValue(AutomationProperties.NameProperty, thisAutomationName); } diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButtonToolTipConverter.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButtonToolTipConverter.cs index bec10afc6b7..c606f123b10 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButtonToolTipConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButtonToolTipConverter.cs @@ -42,12 +42,12 @@ public object Convert(object value, Type targetType, object parameter, System.Gl } object toolTipObj = imageButtonBase.GetValue(Button.ToolTipProperty); - if (toolTipObj != null) + if (toolTipObj is not null) { return toolTipObj.ToString(); } - if (imageButtonBase.Command != null && !string.IsNullOrEmpty(imageButtonBase.Command.Text)) + if (imageButtonBase.Command is not null && !string.IsNullOrEmpty(imageButtonBase.Command.Text)) { return imageButtonBase.Command.Text.Replace("_", string.Empty); } diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageToggleButton.xaml.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageToggleButton.xaml.cs index adc1e1a6421..aea23d3d66c 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageToggleButton.xaml.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageToggleButton.xaml.cs @@ -45,13 +45,13 @@ public bool IsChecked private void ImageButton_Loaded(object sender, System.Windows.RoutedEventArgs e) { object thisAutomationId = this.GetValue(AutomationProperties.AutomationIdProperty); - if (thisAutomationId != null) + if (thisAutomationId is not null) { this.toggleInnerButton.SetValue(AutomationProperties.AutomationIdProperty, thisAutomationId); } object thisAutomationName = this.GetValue(AutomationProperties.NameProperty); - if (thisAutomationName != null) + if (thisAutomationName is not null) { this.toggleInnerButton.SetValue(AutomationProperties.NameProperty, thisAutomationName); } diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ParameterSetControl.xaml.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ParameterSetControl.xaml.cs index c258a2819ac..bed2dfa139b 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ParameterSetControl.xaml.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ParameterSetControl.xaml.cs @@ -49,7 +49,7 @@ public ParameterSetControl() /// public void FocusFirstElement() { - if (this.firstFocusableElement != null) + if (this.firstFocusableElement is not null) { this.firstFocusableElement.Focus(); } @@ -317,7 +317,7 @@ private void ParameterSetControl_DataContextChanged(object sender, DependencyPro control = ParameterSetControl.CreateTextBoxControl(parameter, rowNumber); } - if (control != null) + if (control is not null) { this.AddControlToMainGrid(control); } diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/AllModulesViewModel.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/AllModulesViewModel.cs index 34159c8f837..30f619699b4 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/AllModulesViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/AllModulesViewModel.cs @@ -210,7 +210,7 @@ public string CommandNameFilter } this.commandNameFilter = value; - if (this.selectedModule != null) + if (this.selectedModule is not null) { this.selectedModule.RefreshFilteredCommands(this.CommandNameFilter); this.selectedModule.SelectedCommand = null; @@ -237,7 +237,7 @@ public ModuleViewModel SelectedModule return; } - if (this.selectedModule != null) + if (this.selectedModule is not null) { this.selectedModule.SelectedCommandNeedsImportModule -= this.SelectedModule_SelectedCommandNeedsImportModule; this.selectedModule.SelectedCommandNeedsHelp -= this.SelectedModule_SelectedCommandNeedsHelp; @@ -249,7 +249,7 @@ public ModuleViewModel SelectedModule this.SetCanRun(); this.SetCanCopy(); - if (this.selectedModule != null) + if (this.selectedModule is not null) { this.selectedModule.RefreshFilteredCommands(this.CommandNameFilter); this.selectedModule.SelectedCommandNeedsImportModule += this.SelectedModule_SelectedCommandNeedsImportModule; @@ -401,7 +401,7 @@ public string GetScript() internal void OnRefresh() { EventHandler handler = this.Refresh; - if (handler != null) + if (handler is not null) { handler(this, new EventArgs()); } @@ -445,7 +445,7 @@ private void SelectedModule_PropertyChanged(object sender, PropertyChangedEventA /// private void SetCanRun() { - bool newValue = this.selectedModule != null && this.MainGridDisplayed && + bool newValue = this.selectedModule is not null && this.MainGridDisplayed && this.selectedModule.IsThereASelectedImportedCommandWhereAllMandatoryParametersHaveValues; if (this.canRun == newValue) @@ -465,7 +465,7 @@ private void SetCanRun() /// private void SetCanCopy() { - bool newValue = this.selectedModule != null && this.MainGridDisplayed && this.selectedModule.IsThereASelectedCommand; + bool newValue = this.selectedModule is not null && this.MainGridDisplayed && this.selectedModule.IsThereASelectedCommand; if (this.canCopy == newValue) { @@ -600,7 +600,7 @@ private void SelectedModule_SelectedCommandNeedsImportModule(object sender, Impo private void OnSelectedCommandInSelectedModuleNeedsHelp(HelpNeededEventArgs e) { EventHandler handler = this.SelectedCommandInSelectedModuleNeedsHelp; - if (handler != null) + if (handler is not null) { handler(this, e); } @@ -613,7 +613,7 @@ private void OnSelectedCommandInSelectedModuleNeedsHelp(HelpNeededEventArgs e) private void OnSelectedCommandInSelectedModuleNeedsImportModule(ImportModuleEventArgs e) { EventHandler handler = this.SelectedCommandInSelectedModuleNeedsImportModule; - if (handler != null) + if (handler is not null) { handler(this, e); } @@ -636,7 +636,7 @@ private void SelectedModule_RunSelectedCommand(object sender, CommandEventArgs e private void OnRunSelectedCommandInSelectedModule(CommandEventArgs e) { EventHandler handler = this.RunSelectedCommandInSelectedModule; - if (handler != null) + if (handler is not null) { handler(this, e); } @@ -649,7 +649,7 @@ private void OnRunSelectedCommandInSelectedModule(CommandEventArgs e) private void OnNotifyPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = this.PropertyChanged; - if (handler != null) + if (handler is not null) { handler(this, new PropertyChangedEventArgs(propertyName)); } diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandViewModel.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandViewModel.cs index e5eb1be800d..59b4ccbcf78 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandViewModel.cs @@ -166,13 +166,13 @@ public ParameterSetViewModel SelectedParameterSet { if (this.selectedParameterSet != value) { - if (this.selectedParameterSet != null) + if (this.selectedParameterSet is not null) { this.selectedParameterSet.PropertyChanged -= this.SelectedParameterSet_PropertyChanged; } this.selectedParameterSet = value; - if (this.selectedParameterSet != null) + if (this.selectedParameterSet is not null) { this.selectedParameterSet.PropertyChanged += this.SelectedParameterSet_PropertyChanged; this.SelectedParameterSetAllMandatoryParametersHaveValues = this.SelectedParameterSet.AllMandatoryParametersHaveValues; @@ -313,7 +313,7 @@ public string Name { get { - if (this.commandInfo != null) + if (this.commandInfo is not null) { return this.commandInfo.Name; } @@ -329,7 +329,7 @@ public string ModuleName { get { - if (this.commandInfo != null && this.commandInfo.ModuleName != null) + if (this.commandInfo is not null && this.commandInfo.ModuleName is not null) { return this.commandInfo.ModuleName; } @@ -440,13 +440,13 @@ public string GetScript() builder.Append(" "); - if (this.SelectedParameterSet != null) + if (this.SelectedParameterSet is not null) { builder.Append(this.SelectedParameterSet.GetScript()); builder.Append(" "); } - if (this.CommonParameters != null) + if (this.CommonParameters is not null) { builder.Append(this.CommonParameters.GetScript()); } @@ -559,7 +559,7 @@ internal static CommandViewModel GetCommandViewModel(ModuleViewModel module, Sho internal void OnHelpNeeded() { EventHandler handler = this.HelpNeeded; - if (handler != null) + if (handler is not null) { handler(this, new HelpNeededEventArgs(this.Name)); } @@ -571,7 +571,7 @@ internal void OnHelpNeeded() internal void OnImportModule() { EventHandler handler = this.ImportModule; - if (handler != null) + if (handler is not null) { handler(this, new EventArgs()); } @@ -594,7 +594,7 @@ private void SetCommonParametersHeight() /// 0 if they are the same, -1 if source is smaller, 1 if source is larger. private int Compare(ParameterSetViewModel source, ParameterSetViewModel target) { - if (this.defaultParameterSetName != null) + if (this.defaultParameterSetName is not null) { if (source.Name.Equals(this.defaultParameterSetName) && target.Name.Equals(this.defaultParameterSetName)) { @@ -622,7 +622,7 @@ private int Compare(ParameterSetViewModel source, ParameterSetViewModel target) private void OnNotifyPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = this.PropertyChanged; - if (handler != null) + if (handler is not null) { handler(this, new PropertyChangedEventArgs(propertyName)); } diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ModuleViewModel.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ModuleViewModel.cs index 38925e458a9..4b1617b38c3 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ModuleViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ModuleViewModel.cs @@ -186,7 +186,7 @@ public CommandViewModel SelectedCommand return; } - if (this.selectedCommand != null) + if (this.selectedCommand is not null) { this.selectedCommand.PropertyChanged -= this.SelectedCommand_PropertyChanged; this.selectedCommand.HelpNeeded -= this.SelectedCommand_HelpNeeded; @@ -197,7 +197,7 @@ public CommandViewModel SelectedCommand this.SetIsThereASelectedImportedCommandWhereAllMandatoryParametersHaveValues(); - if (this.selectedCommand != null) + if (this.selectedCommand is not null) { this.selectedCommand.PropertyChanged += this.SelectedCommand_PropertyChanged; this.selectedCommand.HelpNeeded += this.SelectedCommand_HelpNeeded; @@ -354,7 +354,7 @@ internal void RefreshFilteredCommands(string filter) continue; } - if (filterPattern != null) + if (filterPattern is not null) { continue; } @@ -378,7 +378,7 @@ internal void RefreshFilteredCommands(string filter) internal void OnRunSelectedCommand() { EventHandler handler = this.RunSelectedCommand; - if (handler != null) + if (handler is not null) { handler(this, new CommandEventArgs(this.SelectedCommand)); } @@ -391,7 +391,7 @@ internal void OnRunSelectedCommand() internal void OnSelectedCommandNeedsHelp(HelpNeededEventArgs e) { EventHandler handler = this.SelectedCommandNeedsHelp; - if (handler != null) + if (handler is not null) { handler(this, e); } @@ -403,7 +403,7 @@ internal void OnSelectedCommandNeedsHelp(HelpNeededEventArgs e) internal void OnSelectedCommandNeedsImportModule() { EventHandler handler = this.SelectedCommandNeedsImportModule; - if (handler != null) + if (handler is not null) { handler(this, new ImportModuleEventArgs(this.SelectedCommand.Name, this.SelectedCommand.ModuleName, this.Name)); } @@ -419,7 +419,7 @@ internal void OnSelectedCommandNeedsImportModule() /// True if coparisonText matches str or pattern. private static bool Matches(WildcardPattern filterPattern, string commandName, string filter) { - if (filterPattern != null) + if (filterPattern is not null) { return filterPattern.IsMatch(commandName); } @@ -498,7 +498,7 @@ private void SelectedCommand_PropertyChanged(object sender, PropertyChangedEvent private void SetIsThereASelectedImportedCommandWhereAllMandatoryParametersHaveValues() { this.IsThereASelectedImportedCommandWhereAllMandatoryParametersHaveValues = - this.selectedCommand != null && + this.selectedCommand is not null && this.selectedCommand.IsImported && this.selectedCommand.SelectedParameterSetAllMandatoryParametersHaveValues; } @@ -522,7 +522,7 @@ private int Compare(CommandViewModel source, CommandViewModel target) private void OnNotifyPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = this.PropertyChanged; - if (handler != null) + if (handler is not null) { handler(this, new PropertyChangedEventArgs(propertyName)); } diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterSetViewModel.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterSetViewModel.cs index 756f58c62c8..c5c4cc89c30 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterSetViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterSetViewModel.cs @@ -304,7 +304,7 @@ private static char ParameterNeedsDelimitation(string parameterValue, bool requi } StringConstantExpressionAst stringValue = commandAst.CommandElements[2] as StringConstantExpressionAst; - if (stringValue != null) + if (stringValue is not null) { if (errors.Length == 0) { @@ -370,7 +370,7 @@ private void EvaluateAllMandatoryParametersHaveValues() private void OnNotifyPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = this.PropertyChanged; - if (handler != null) + if (handler is not null) { handler(this, new PropertyChangedEventArgs(propertyName)); } diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterViewModel.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterViewModel.cs index 2c6931eb08e..a221889eadf 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterViewModel.cs @@ -269,7 +269,7 @@ internal static string EvaluateTooltip(string typeName, int position, bool manda private void OnNotifyPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = this.PropertyChanged; - if (handler != null) + if (handler is not null) { handler(this, new PropertyChangedEventArgs(propertyName)); } diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/ShowAllModulesWindow.xaml.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/ShowAllModulesWindow.xaml.cs index b644264376b..5d5f9a65260 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/ShowAllModulesWindow.xaml.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/ShowAllModulesWindow.xaml.cs @@ -44,7 +44,7 @@ public ShowAllModulesWindow() { this.InitializeComponent(); - if (this.AllModulesControl != null && this.AllModulesControl.ShowModuleControl != null) + if (this.AllModulesControl is not null && this.AllModulesControl.ShowModuleControl is not null) { this.AllModulesControl.ShowModuleControl.Owner = this; } diff --git a/src/Microsoft.Management.UI.Internal/commandHelpers/HelpWindowHelper.cs b/src/Microsoft.Management.UI.Internal/commandHelpers/HelpWindowHelper.cs index efed820e71c..336e9c4c534 100644 --- a/src/Microsoft.Management.UI.Internal/commandHelpers/HelpWindowHelper.cs +++ b/src/Microsoft.Management.UI.Internal/commandHelpers/HelpWindowHelper.cs @@ -26,7 +26,7 @@ internal static class HelpWindowHelper private static void ShowHelpWindow(PSObject helpObj, PSCmdlet cmdlet) { Window ownerWindow = ShowCommandHelper.GetHostWindow(cmdlet); - if (ownerWindow != null) + if (ownerWindow is not null) { ownerWindow.Dispatcher.Invoke( new SendOrPostCallback( diff --git a/src/Microsoft.Management.UI.Internal/commandHelpers/OutGridView.cs b/src/Microsoft.Management.UI.Internal/commandHelpers/OutGridView.cs index 85ecd95a36f..9f74810b089 100644 --- a/src/Microsoft.Management.UI.Internal/commandHelpers/OutGridView.cs +++ b/src/Microsoft.Management.UI.Internal/commandHelpers/OutGridView.cs @@ -182,7 +182,7 @@ private void StartWindow(string invocation, string outputModeOptions, AutoResetE catch (Exception e) { // Store the exception in a local variable that will be checked later. - if (e.InnerException != null) + if (e.InnerException is not null) { this.exception = e.InnerException; } @@ -216,7 +216,7 @@ private void ZoomEventHandlerPlus(object sender, ExecutedRoutedEventArgs e) this.zoomLevel = this.zoomLevel + ZOOM_INCREMENT; Grid g = this.gridViewWindow.Content as Grid; - if (g != null) + if (g is not null) { g.LayoutTransform = new ScaleTransform(this.zoomLevel, this.zoomLevel, 0, 0); } @@ -234,7 +234,7 @@ private void ZoomEventHandlerMinus(object sender, ExecutedRoutedEventArgs e) { this.zoomLevel = this.zoomLevel - ZOOM_INCREMENT; Grid g = this.gridViewWindow.Content as Grid; - if (g != null) + if (g is not null) { g.LayoutTransform = new ScaleTransform(this.zoomLevel, this.zoomLevel, 0, 0); } @@ -400,7 +400,7 @@ public void CloseWindow() private void AddColumns(string[] propertyNames, string[] displayNames, Type[] types) { // Wait for the gridViewWindow thread to signal that loading of Window is done - if (this.gridViewWindowLoaded != null) + if (this.gridViewWindowLoaded is not null) { this.gridViewWindowLoaded.WaitOne(); this.gridViewWindowLoaded = null; @@ -465,7 +465,7 @@ private void AddColumns(string[] propertyNames, string[] displayNames, Type[] ty catch (Exception e) { // Store the exception in a local variable that will be checked later. - if (e.InnerException != null) + if (e.InnerException is not null) { this.exception = e.InnerException; } @@ -501,7 +501,7 @@ private void AddItem(PSObject value) catch (Exception e) { // Store the exception in a local variable that will be checked later. - if (e.InnerException != null) + if (e.InnerException is not null) { this.exception = e.InnerException; } @@ -537,7 +537,7 @@ private Exception GetLastException() { Exception local = this.exception; - if (local != null) + if (local is not null) { // Clear the caught exception. this.exception = null; @@ -558,7 +558,7 @@ private Exception GetLastException() /// Event Args. private void GridViewWindowClosed(object sender, EventArgs e) { - if (this.closedEvent != null && !this.closedEvent.SafeWaitHandle.IsClosed) + if (this.closedEvent is not null && !this.closedEvent.SafeWaitHandle.IsClosed) { try { diff --git a/src/Microsoft.Management.UI.Internal/commandHelpers/ShowCommandHelper.cs b/src/Microsoft.Management.UI.Internal/commandHelpers/ShowCommandHelper.cs index 5d401fc94c6..f36e0f41b1f 100644 --- a/src/Microsoft.Management.UI.Internal/commandHelpers/ShowCommandHelper.cs +++ b/src/Microsoft.Management.UI.Internal/commandHelpers/ShowCommandHelper.cs @@ -402,7 +402,7 @@ private bool HasHostWindow { get { - return this.hostWindow != null; + return this.hostWindow is not null; } } #endregion properties called using reflection @@ -542,7 +542,7 @@ internal static Dictionary GetImportedModulesDict { ShowCommandModuleInfo wrappedModule = null; PSModuleInfo module = rawModule.BaseObject as PSModuleInfo; - if (module != null) + if (module is not null) { wrappedModule = new ShowCommandModuleInfo(module); } @@ -573,14 +573,14 @@ internal static List GetCommandList(object[] commandObje foreach (PSObject rawCommand in commandObjects) { CommandInfo command = rawCommand.BaseObject as CommandInfo; - if (command != null) + if (command is not null) { returnValue.Add(new ShowCommandCommandInfo(command)); } else { PSObject obj = rawCommand as PSObject; - if (obj != null) + if (obj is not null) { returnValue.Add(new ShowCommandCommandInfo(obj)); } @@ -620,7 +620,7 @@ internal static AllModulesViewModel GetNewAllModulesViewModel(AllModulesViewMode { string oldFilter = null; - if (oldViewModel.SelectedModule != null) + if (oldViewModel.SelectedModule is not null) { // this will allow the old view model to stop listening for events before we // replace it with a new view model @@ -996,7 +996,7 @@ private void ShowCommandWindow(PSCmdlet cmdlet, object commandViewModelObj, doub private void ImportModuleDone(Dictionary importedModules, IEnumerable commands) { this.allModulesViewModel.WaitMessageDisplayed = false; - if (this.window != null) + if (this.window is not null) { this.window.Dispatcher.Invoke( new SendOrPostCallback( @@ -1023,7 +1023,7 @@ private void ImportModuleDone(Dictionary imported private void ImportModuleFailed(Exception reason) { this.allModulesViewModel.WaitMessageDisplayed = false; - if (this.window != null) + if (this.window is not null) { this.window.Dispatcher.Invoke( new SendOrPostCallback( @@ -1046,7 +1046,7 @@ private void ImportModuleFailed(Exception reason) [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called using reflection")] private void DisplayHelp(Collection getHelpResults) { - if (this.window != null && getHelpResults != null && getHelpResults.Count > 0) + if (this.window is not null && getHelpResults is not null && getHelpResults.Count > 0) { this.window.Dispatcher.Invoke( new SendOrPostCallback( @@ -1066,7 +1066,7 @@ private void DisplayHelp(Collection getHelpResults) [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called using reflection")] private void ActivateWindow() { - if (this.window != null) + if (this.window is not null) { ShowCommandHelper.ActivateWindow(this.window); } @@ -1133,7 +1133,7 @@ private void CommandNeedsHelp(object sender, HelpNeededEventArgs e) /// Event arguments. private void Window_Closed(object sender, EventArgs e) { - if (this.hostWindow != null) + if (this.hostWindow is not null) { this.hostWindow.Focus(); } @@ -1233,7 +1233,7 @@ private void CloseWindow() this.window.Dispatcher.Invoke(new ThreadStart(delegate { // This can happen if ISE is closed while show-command is up - if (this.window != null) + if (this.window is not null) { this.window.Close(); } @@ -1246,7 +1246,7 @@ private void CloseWindow() /// Error message. private void ShowErrorString(string errorString) { - if (errorString != null && errorString.Trim().Length > 0) + if (errorString is not null && errorString.Trim().Length > 0) { MessageBox.Show( string.Format( @@ -1265,7 +1265,7 @@ private void ShowErrorString(string errorString) /// The script to execute. private string InternalGetScript() { - if (this.allModulesViewModel != null) + if (this.allModulesViewModel is not null) { return this.allModulesViewModel.GetScript(); } diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/ExportCounterCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/ExportCounterCommand.cs index 9385e55909f..6f4ae714125 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/ExportCounterCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/ExportCounterCommand.cs @@ -233,7 +233,7 @@ protected override void StopProcessing() // protected override void ProcessRecord() { - Debug.Assert(_counterSampleSets.Length != 0 && _counterSampleSets[0] != null); + Debug.Assert(_counterSampleSets.Length != 0 && _counterSampleSets[0] is not null); ResolvePath(); diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs index 459d553e27a..11c7b406338 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs @@ -339,7 +339,7 @@ private void ProcessListSetPerMachine(string machine) bool bMatched = false; string normalizedPattern = pattern; - if (characterReplacementList != null) + if (characterReplacementList is not null) { foreach (Tuple pair in characterReplacementList) { @@ -460,7 +460,7 @@ private void ProcessGetCounter() localizedPath = path; } } - else if (characterReplacementList != null) + else if (characterReplacementList is not null) { foreach (Tuple pair in characterReplacementList) { diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs index a596f861cfd..4916ebc3ed9 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs @@ -1283,7 +1283,7 @@ private string BuildStructuredQueryFromHashTable(EventLogSession eventLogSession // Build xpath for // Hashtable suppresshash = hash[hashkey_supress_lc] as Hashtable; - if (suppresshash != null) + if (suppresshash is not null) { xpathStringSuppress = BuildXPathFromHashTable(suppresshash); } @@ -1351,7 +1351,7 @@ private string HandleEventIdHashValue(object value) { StringBuilder ret = new StringBuilder(); Array idsArray = value as Array; - if (idsArray != null) + if (idsArray is not null) { ret.Append("("); for (int i = 0; i < idsArray.Length; i++) @@ -1381,7 +1381,7 @@ private string HandleLevelHashValue(object value) { StringBuilder ret = new StringBuilder(); Array levelsArray = value as Array; - if (levelsArray != null) + if (levelsArray is not null) { ret.Append("("); for (int i = 0; i < levelsArray.Length; i++) @@ -1413,7 +1413,7 @@ private string HandleKeywordHashValue(object value) Int64 keywordLong = 0; Array keywordArray = value as Array; - if (keywordArray != null) + if (keywordArray is not null) { foreach (object keyword in keywordArray) { @@ -1569,7 +1569,7 @@ private string HandleDataHashValue(object value) { StringBuilder ret = new StringBuilder(); Array dataArray = value as Array; - if (dataArray != null) + if (dataArray is not null) { ret.Append("("); for (int i = 0; i < dataArray.Length; i++) @@ -1600,7 +1600,7 @@ private string HandleNamedDataHashValue(string key, object value) { StringBuilder ret = new StringBuilder(); Array dataArray = value as Array; - if (dataArray != null) + if (dataArray is not null) { ret.Append("("); for (int i = 0; i < dataArray.Length; i++) @@ -1848,7 +1848,7 @@ private void CheckHashTablesForNullValues() else { Array eltArray = value as Array; - if (eltArray != null) + if (eltArray is not null) { foreach (object elt in eltArray) { diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/NewWinEventCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/NewWinEventCommand.cs index 4147fe309d5..d8bde8bea7c 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/NewWinEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/NewWinEventCommand.cs @@ -244,7 +244,7 @@ private void LoadEventDescriptor() private bool VerifyTemplate(EventMetadata emd) { - if (emd.Template != null) + if (emd.Template is not null) { XmlReaderSettings readerSettings = new XmlReaderSettings { @@ -271,7 +271,7 @@ private bool VerifyTemplate(EventMetadata emd) } if ((_payload is null && definedParameterCount != 0) - || ((_payload != null) && _payload.Length != definedParameterCount)) + || ((_payload is not null) && _payload.Length != definedParameterCount)) { string warning = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("PayloadMismatch"), _id, emd.Template); WriteWarning(warning); @@ -318,7 +318,7 @@ protected override void ProcessRecord() { EventDescriptor ed = _eventDescriptor.Value; - if (_payload != null && _payload.Length > 0) + if (_payload is not null && _payload.Length > 0) { for (int i = 0; i < _payload.Length; i++) { @@ -344,7 +344,7 @@ protected override void ProcessRecord() /// protected override void EndProcessing() { - if (_providerMetadata != null) + if (_providerMetadata is not null) _providerMetadata.Dispose(); base.EndProcessing(); diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs index e535535d25e..e111d0e1cae 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs @@ -402,17 +402,17 @@ private static extern uint PdhExpandWildCardPathH(PdhSafeDataSourceHandle hDataS // public void Dispose() { - if (_hDataSource != null && !_hDataSource.IsInvalid) + if (_hDataSource is not null && !_hDataSource.IsInvalid) { _hDataSource.Dispose(); } - if (_hOutputLog != null && !_hOutputLog.IsInvalid) + if (_hOutputLog is not null && !_hOutputLog.IsInvalid) { _hOutputLog.Dispose(); } - if (_hQuery != null && !_hQuery.IsInvalid) + if (_hQuery is not null && !_hQuery.IsInvalid) { _hQuery.Dispose(); } @@ -462,7 +462,7 @@ private uint GetCounterInfoPlus(IntPtr hCounter, out UInt32 counterType, out UIn defaultScale = 0; timeBase = 0; - Debug.Assert(hCounter != null); + Debug.Assert(hCounter is not null); IntPtr pBufferSize = new IntPtr(0); res = PdhGetCounterInfo(hCounter, false, ref pBufferSize, IntPtr.Zero); @@ -500,7 +500,7 @@ private uint GetCounterInfoPlus(IntPtr hCounter, out UInt32 counterType, out UIn public uint ConnectToDataSource() { - if (_hDataSource != null && !_hDataSource.IsInvalid) + if (_hDataSource is not null && !_hDataSource.IsInvalid) { _hDataSource.Dispose(); } @@ -521,7 +521,7 @@ public uint ConnectToDataSource() /// public uint ConnectToDataSource(string dataSourceName) { - if (_hDataSource != null && !_hDataSource.IsInvalid) + if (_hDataSource is not null && !_hDataSource.IsInvalid) { _hDataSource.Dispose(); } @@ -567,7 +567,7 @@ public uint OpenQuery() public uint OpenLogForWriting(string logName, PdhLogFileType logFileType, bool bOverwrite, UInt32 maxSize, bool bCircular, string caption) { - Debug.Assert(_hQuery != null); + Debug.Assert(_hQuery is not null); UInt32 accessFlags = PdhLogAccess.PDH_LOG_WRITE_ACCESS; accessFlags |= bCircular ? PdhLogOpenOption.PDH_LOG_OPT_CIRCULAR : 0; @@ -586,7 +586,7 @@ public uint OpenLogForWriting(string logName, PdhLogFileType logFileType, bool b public uint SetQueryTimeRange(DateTime startTime, DateTime endTime) { - Debug.Assert(_hQuery != null); + Debug.Assert(_hQuery is not null); Debug.Assert(endTime >= startTime); PDH_TIME_INFO pTimeInfo = new PDH_TIME_INFO(); @@ -748,7 +748,7 @@ public uint EnumObjectItems(string machineName, string objectName, ref StringCol public uint GetValidPathsFromFiles(ref StringCollection validPaths) { - Debug.Assert(_hDataSource != null && !_hDataSource.IsInvalid, "Call ConnectToDataSource before GetValidPathsFromFiles"); + Debug.Assert(_hDataSource is not null && !_hDataSource.IsInvalid, "Call ConnectToDataSource before GetValidPathsFromFiles"); StringCollection machineNames = new StringCollection(); uint res = this.EnumBlgFilesMachines(ref machineNames); @@ -1100,7 +1100,7 @@ public uint GetValidPaths(string machineName, public uint AddCounters(ref StringCollection validPaths, bool bFlushOldCounters) { - Debug.Assert(_hQuery != null && !_hQuery.IsInvalid); + Debug.Assert(_hQuery is not null && !_hQuery.IsInvalid); if (bFlushOldCounters) { @@ -1122,7 +1122,7 @@ public uint AddCounters(ref StringCollection validPaths, bool bFlushOldCounters) PDH_COUNTER_PATH_ELEMENTS pathElts = new PDH_COUNTER_PATH_ELEMENTS(); res = ParsePath(counterPath, ref pathElts); - if (res == 0 && pathElts.InstanceName != null) + if (res == 0 && pathElts.InstanceName is not null) { chi.InstanceName = pathElts.InstanceName.ToLowerInvariant(); } @@ -1147,7 +1147,7 @@ public string GetCounterSetHelp(string szMachineName, string szObjectName) public uint ReadNextSet(out PerformanceCounterSampleSet nextSet, bool bSkipReading) { - Debug.Assert(_hQuery != null && !_hQuery.IsInvalid); + Debug.Assert(_hQuery is not null && !_hQuery.IsInvalid); uint res = 0; nextSet = null; @@ -1190,7 +1190,7 @@ public uint ReadNextSet(out PerformanceCounterSampleSet nextSet, bool bSkipReadi UInt64 timeBase = 0; IntPtr hCounter = _consumerPathToHandleAndInstanceMap[path].hCounter; - Debug.Assert(hCounter != null); + Debug.Assert(hCounter is not null); res = GetCounterInfoPlus(hCounter, out counterType, out defaultScale, out timeBase); if (res != 0) diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs index ab74e6f1a38..e5f119cb798 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs @@ -54,7 +54,7 @@ protected virtual void Dispose(bool disposing) { if (disposing) { - if (_parentJob != null) + if (_parentJob is not null) { _parentJob.Dispose(); _parentJob = null; @@ -137,14 +137,14 @@ private StartableJob DoCreateQueryJob(TSession sessionForJob, QueryBuilder query { StartableJob queryJob = this.CreateQueryJob(sessionForJob, query); - if (queryJob != null) + if (queryJob is not null) { - if (actionAgainstResults != null) + if (actionAgainstResults is not null) { queryJob.SuppressOutputForwarding = true; } - bool discardNonPipelineResults = (actionAgainstResults != null) || !this.AsJob.IsPresent; + bool discardNonPipelineResults = (actionAgainstResults is not null) || !this.AsJob.IsPresent; HandleJobOutput( queryJob, sessionForJob, @@ -188,7 +188,7 @@ private StartableJob DoCreateInstanceMethodInvocationJob(TSession sessionForJob, { StartableJob methodInvocationJob = this.CreateInstanceMethodInvocationJob(sessionForJob, objectInstance, methodInvocationInfo, passThru); - if (methodInvocationJob != null) + if (methodInvocationJob is not null) { bool discardNonPipelineResults = !asJob; HandleJobOutput( @@ -223,7 +223,7 @@ private StartableJob DoCreateStaticMethodInvocationJob(TSession sessionForJob, M { StartableJob methodInvocationJob = this.CreateStaticMethodInvocationJob(sessionForJob, methodInvocationInfo); - if (methodInvocationJob != null) + if (methodInvocationJob is not null) { bool discardNonPipelineResults = !this.AsJob.IsPresent; HandleJobOutput( @@ -246,7 +246,7 @@ private void HandleJobOutput(Job job, TSession sessionForJob, bool discardNonPip return; } - if (outputAction != null) + if (outputAction is not null) { outputAction(pso); } @@ -380,7 +380,7 @@ public override void ProcessRecord(QueryBuilder query) foreach (TSession sessionForJob in this.GetSessionsToActAgainst(query)) { StartableJob childJob = this.DoCreateQueryJob(sessionForJob, query, actionAgainstResults: null); - if (childJob != null) + if (childJob is not null) { if (!this.AsJob.IsPresent) { @@ -421,13 +421,13 @@ public override void ProcessRecord(QueryBuilder query, MethodInvocationInfo meth passThru, closureOverAsJob.IsPresent); - if (methodInvocationJob != null) + if (methodInvocationJob is not null) { closureOverParentJob.AddChildJobAndPotentiallyBlock(methodInvocationJob, ThrottlingJob.ChildJobFlags.None); } }); - if (queryJob != null) + if (queryJob is not null) { if (!this.AsJob.IsPresent) { @@ -449,7 +449,7 @@ private IEnumerable GetSessionsToActAgainst(TObjectInstance objectInst } TSession associatedSession = this.GetSessionOfOriginFromInstance(objectInstance); - if (associatedSession != null) + if (associatedSession is not null) { return new[] { associatedSession }; } @@ -495,17 +495,17 @@ private IEnumerable GetSessionsToActAgainst(QueryBuilder queryBuilder) } var sessionBoundQueryBuilder = queryBuilder as ISessionBoundQueryBuilder; - if (sessionBoundQueryBuilder != null) + if (sessionBoundQueryBuilder is not null) { TSession sessionOfTheQueryBuilder = sessionBoundQueryBuilder.GetTargetSession(); - if (sessionOfTheQueryBuilder != null) + if (sessionOfTheQueryBuilder is not null) { return new[] { sessionOfTheQueryBuilder }; } } TSession sessionAssociatedWithPipelineObject = this.GetSessionAssociatedWithPipelineObject(); - if (sessionAssociatedWithPipelineObject != null) + if (sessionAssociatedWithPipelineObject is not null) { return new[] { sessionAssociatedWithPipelineObject }; } @@ -524,7 +524,7 @@ private IEnumerable GetSessionsToActAgainst(MethodInvocationInfo metho foreach (TObjectInstance objectInstance in methodInvocationInfo.GetArgumentsOfType()) { TSession associatedSession = this.GetSessionOfOriginFromInstance(objectInstance); - if (associatedSession != null) + if (associatedSession is not null) { associatedSessions.Add(associatedSession); } @@ -536,7 +536,7 @@ private IEnumerable GetSessionsToActAgainst(MethodInvocationInfo metho } TSession sessionAssociatedWithPipelineObject = this.GetSessionAssociatedWithPipelineObject(); - if (sessionAssociatedWithPipelineObject != null) + if (sessionAssociatedWithPipelineObject is not null) { return new[] { sessionAssociatedWithPipelineObject }; } @@ -558,7 +558,7 @@ private TSession GetImpliedSession() TSession sessionFromImportModule; // When being called from a CIM activity, this will be invoked as // a function so there will be no module info - if (this.PSModuleInfo != null) + if (this.PSModuleInfo is not null) { if (PSPrimitiveDictionary.TryPathGet( this.PSModuleInfo.PrivateData as IDictionary, @@ -587,7 +587,7 @@ public override void ProcessRecord(TObjectInstance objectInstance, MethodInvocat foreach (TSession sessionForJob in this.GetSessionsToActAgainst(objectInstance)) { StartableJob childJob = this.DoCreateInstanceMethodInvocationJob(sessionForJob, objectInstance, methodInvocationInfo, passThru, this.AsJob.IsPresent); - if (childJob != null) + if (childJob is not null) { if (!this.AsJob.IsPresent) { @@ -612,7 +612,7 @@ public override void ProcessRecord(MethodInvocationInfo methodInvocationInfo) foreach (TSession sessionForJob in this.GetSessionsToActAgainst(methodInvocationInfo)) { StartableJob childJob = this.DoCreateStaticMethodInvocationJob(sessionForJob, methodInvocationInfo); - if (childJob != null) + if (childJob is not null) { if (!this.AsJob.IsPresent) { @@ -644,7 +644,7 @@ public override void BeginProcessing() conflictingParameter = "Confirm"; } - if (conflictingParameter != null) + if (conflictingParameter is not null) { string errorMessage = string.Format( CultureInfo.InvariantCulture, @@ -687,7 +687,7 @@ public override void EndProcessing() public override void StopProcessing() { Job jobToStop = _parentJob; - if (jobToStop != null) + if (jobToStop is not null) { jobToStop.StopJob(); } 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..e1ea9998313 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs @@ -85,9 +85,9 @@ internal static CimJobException CreateFromCimException( CimJobContext jobContext, CimException cimException) { - Dbg.Assert(!string.IsNullOrEmpty(jobDescription), "Caller should verify jobDescription != null"); - Dbg.Assert(jobContext != null, "Caller should verify jobContext != null"); - Dbg.Assert(cimException != null, "Caller should verify cimException != null"); + Dbg.Assert(!string.IsNullOrEmpty(jobDescription), "Caller should verify jobDescription is not null"); + Dbg.Assert(jobContext is not null, "Caller should verify jobContext is not null"); + Dbg.Assert(cimException is not null, "Caller should verify cimException is not null"); string message = BuildErrorMessage(jobDescription, jobContext, cimException.Message); CimJobException cimJobException = new CimJobException(message, cimException); @@ -100,12 +100,12 @@ internal static CimJobException CreateFromAnyException( CimJobContext jobContext, Exception inner) { - Dbg.Assert(!string.IsNullOrEmpty(jobDescription), "Caller should verify jobDescription != null"); - Dbg.Assert(jobContext != null, "Caller should verify jobContext != null"); - Dbg.Assert(inner != null, "Caller should verify inner != null"); + Dbg.Assert(!string.IsNullOrEmpty(jobDescription), "Caller should verify jobDescription is not null"); + Dbg.Assert(jobContext is not null, "Caller should verify jobContext is not null"); + Dbg.Assert(inner is not null, "Caller should verify inner is not null"); CimException cimException = inner as CimException; - if (cimException != null) + if (cimException is not null) { return CreateFromCimException(jobDescription, jobContext, cimException); } @@ -113,7 +113,7 @@ internal static CimJobException CreateFromAnyException( string message = BuildErrorMessage(jobDescription, jobContext, inner.Message); CimJobException cimJobException = new CimJobException(message, inner); var containsErrorRecord = inner as IContainsErrorRecord; - if (containsErrorRecord != null) + if (containsErrorRecord is not null) { cimJobException.InitializeErrorRecord( jobContext, @@ -138,9 +138,9 @@ internal static CimJobException CreateWithFullControl( ErrorCategory errorCategory, Exception inner = null) { - Dbg.Assert(jobContext != null, "Caller should verify jobContext != null"); - Dbg.Assert(!string.IsNullOrEmpty(message), "Caller should verify message != null"); - Dbg.Assert(!string.IsNullOrEmpty(errorId), "Caller should verify errorId != null"); + Dbg.Assert(jobContext is not null, "Caller should verify jobContext is not null"); + Dbg.Assert(!string.IsNullOrEmpty(message), "Caller should verify message is not null"); + Dbg.Assert(!string.IsNullOrEmpty(errorId), "Caller should verify errorId is not null"); CimJobException cimJobException = new CimJobException(jobContext.PrependComputerNameToMessage(message), inner); cimJobException.InitializeErrorRecord(jobContext, errorId, errorCategory); @@ -153,8 +153,8 @@ internal static CimJobException CreateWithoutJobContext( ErrorCategory errorCategory, Exception inner = null) { - Dbg.Assert(!string.IsNullOrEmpty(message), "Caller should verify message != null"); - Dbg.Assert(!string.IsNullOrEmpty(errorId), "Caller should verify errorId != null"); + Dbg.Assert(!string.IsNullOrEmpty(message), "Caller should verify message is not null"); + Dbg.Assert(!string.IsNullOrEmpty(errorId), "Caller should verify errorId is not null"); CimJobException cimJobException = new CimJobException(message, inner); cimJobException.InitializeErrorRecord(null, errorId, errorCategory); @@ -201,9 +201,9 @@ private void InitializeErrorRecordCore(CimJobContext jobContext, Exception excep exception: exception, errorId: errorId, errorCategory: errorCategory, - targetObject: jobContext != null ? jobContext.TargetObject : null); + targetObject: jobContext is not null ? jobContext.TargetObject : null); - if (jobContext != null) + if (jobContext is not null) { System.Management.Automation.Remoting.OriginInfo originInfo = new System.Management.Automation.Remoting.OriginInfo( jobContext.Session.ComputerName, @@ -239,10 +239,10 @@ private void InitializeErrorRecord(CimJobContext jobContext, CimException cimExc errorId: cimException.MessageId ?? "MiClientApiError_" + cimException.NativeErrorCode, errorCategory: ConvertCimExceptionToErrorCategory(cimException)); - if (cimException.ErrorData != null) + if (cimException.ErrorData is not null) { _errorRecord.CategoryInfo.TargetName = cimException.ErrorSource; - _errorRecord.CategoryInfo.TargetType = jobContext != null ? jobContext.CmdletizationClassName : null; + _errorRecord.CategoryInfo.TargetType = jobContext is not null ? jobContext.CmdletizationClassName : null; } } @@ -250,7 +250,7 @@ private static ErrorCategory ConvertCimExceptionToErrorCategory(CimException cim { ErrorCategory result = ErrorCategory.NotSpecified; - if (cimException.ErrorData != null) + if (cimException.ErrorData is not null) { result = ConvertCimErrorToErrorCategory(cimException.ErrorData); } 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..bcfd0f9544e 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CreateInstanceJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CreateInstanceJob.cs @@ -19,7 +19,7 @@ internal class CreateInstanceJob : PropertySettingJob private static CimInstance GetEmptyInstance(CimJobContext jobContext) { - Dbg.Assert(jobContext != null, "Caller should verify jobContext != null"); + Dbg.Assert(jobContext is not null, "Caller should verify jobContext is not null"); var result = new CimInstance(jobContext.ClassName, jobContext.Namespace); return result; @@ -44,7 +44,7 @@ private IObservable GetCreateInstanceOperation() private IObservable GetGetInstanceOperation() { - Dbg.Assert(_resultFromCreateInstance != null, "GetInstance should only be called after CreteInstance came back with a keyed instance"); + Dbg.Assert(_resultFromCreateInstance is not null, "GetInstance should only be called after CreteInstance came back with a keyed instance"); IObservable observable = this.JobContext.Session.GetInstanceAsync( this.JobContext.Namespace, _resultFromCreateInstance, @@ -87,7 +87,7 @@ internal override IObservable GetCimOperation() public override void OnNext(CimInstance item) { - Dbg.Assert(item != null, "CreateInstance and GetInstance should never return null"); + Dbg.Assert(item is not null, "CreateInstance and GetInstance should never return null"); if (_resultFromCreateInstance is null) { _resultFromCreateInstance = item; @@ -116,11 +116,11 @@ public override void OnError(Exception exception) public override void OnCompleted() { - Dbg.Assert(this.DidUserSuppressTheOperation || (_resultFromCreateInstance != null), "OnNext should always be called before OnComplete by CreateInstance"); + Dbg.Assert(this.DidUserSuppressTheOperation || (_resultFromCreateInstance is not null), "OnNext should always be called before OnComplete by CreateInstance"); #if DEBUG Dbg.Assert( - !_getInstanceOperationGotStarted || this.DidUserSuppressTheOperation || (_resultFromGetInstance != null), - // <=> (this._getInstanceOperationGotStarted => (this._resultFromGetInstance != null)) + !_getInstanceOperationGotStarted || this.DidUserSuppressTheOperation || (_resultFromGetInstance is not null), + // <=> (this._getInstanceOperationGotStarted => (this._resultFromGetInstance is not null)) "GetInstance should cause OnNext to be called which should set this._resultFromGetInstance to non-null"); #endif if (this.IsPassThruObjectNeeded() && (_resultFromGetInstance is null)) diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/DeleteInstanceJob.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/DeleteInstanceJob.cs index 327fb83affa..131c80016ea 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/DeleteInstanceJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/DeleteInstanceJob.cs @@ -23,7 +23,7 @@ internal DeleteInstanceJob(CimJobContext jobContext, bool passThru, CimInstance objectToDelete.ToString(), methodInvocationInfo) { - Dbg.Assert(objectToDelete != null, "Caller should verify objectToDelete != null"); + Dbg.Assert(objectToDelete is not null, "Caller should verify objectToDelete is not null"); _objectToDelete = objectToDelete; } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/EnumerateAssociatedInstancesJob.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/EnumerateAssociatedInstancesJob.cs index bd024b7d76a..08682b373ae 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/EnumerateAssociatedInstancesJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/EnumerateAssociatedInstancesJob.cs @@ -25,16 +25,16 @@ internal EnumerateAssociatedInstancesJob(CimJobContext jobContext, CimQuery cimQ : base(jobContext, cimQuery) { _associatedObject = associatedObject; - Dbg.Assert(_associatedObject != null, "Caller should verify that associatedObject is not null"); + Dbg.Assert(_associatedObject is not null, "Caller should verify that associatedObject is not null"); _associationName = associationName; - Dbg.Assert(_associationName != null, "Caller should verify that associationName is not null"); + Dbg.Assert(_associationName is not null, "Caller should verify that associationName is not null"); _resultRole = resultRole; - Dbg.Assert(_resultRole != null, "Caller should verify that resultRole is not null"); + Dbg.Assert(_resultRole is not null, "Caller should verify that resultRole is not null"); _sourceRole = sourceRole; - Dbg.Assert(_sourceRole != null, "Caller should verify that sourceRole is not null"); + Dbg.Assert(_sourceRole is not null, "Caller should verify that sourceRole is not null"); } internal override IObservable GetCimOperation() 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..6fc95465910 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ExtrinsicMethodInvocationJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ExtrinsicMethodInvocationJob.cs @@ -50,12 +50,12 @@ internal CimMethodParametersCollection GetCimMethodParametersCollection() private void ProcessOutParameter(CimMethodResult methodResult, MethodParameter methodParameter, IDictionary cmdletOutput) { - Dbg.Assert(methodResult != null, "Caller should verify methodResult != null"); - Dbg.Assert(methodParameter != null, "Caller should verify methodParameter != null"); + Dbg.Assert(methodResult is not null, "Caller should verify methodResult is not null"); + Dbg.Assert(methodParameter is not null, "Caller should verify methodParameter is not null"); Dbg.Assert(0 != (methodParameter.Bindings & (MethodParameterBindings.Out | MethodParameterBindings.Error)), "Caller should verify that this is an out parameter"); - Dbg.Assert(cmdletOutput != null, "Caller should verify cmdletOutput != null"); + Dbg.Assert(cmdletOutput is not null, "Caller should verify cmdletOutput is not null"); - Dbg.Assert(this.MethodSubject != null, "MethodSubject property should be initialized before starting main job processing"); + Dbg.Assert(this.MethodSubject is not 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; @@ -67,7 +67,7 @@ private void ProcessOutParameter(CimMethodResult methodResult, MethodParameter m cmdletOutput.Add(methodParameter.Name, methodParameter); var cimInstances = dotNetValue as CimInstance[]; - if (cimInstances != null) + if (cimInstances is not null) { foreach (var instance in cimInstances) { @@ -76,7 +76,7 @@ private void ProcessOutParameter(CimMethodResult methodResult, MethodParameter m } var cimInstance = dotNetValue as CimInstance; - if (cimInstance != null) + if (cimInstance is not null) { CimCmdletAdapter.AssociateSessionOfOriginWithInstance(cimInstance, this.JobContext.Session); } @@ -95,7 +95,7 @@ private void ProcessOutParameter(CimMethodResult methodResult, MethodParameter m private void OnNext(CimMethodResult methodResult) { - Dbg.Assert(this.MethodSubject != null, "MethodSubject property should be initialized before starting main job processing"); + Dbg.Assert(this.MethodSubject is not null, "MethodSubject property should be initialized before starting main job processing"); var cmdletOutput = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (MethodParameter methodParameter in this.GetMethodOutputParameters()) @@ -112,7 +112,7 @@ private void OnNext(CimMethodResult methodResult) } IEnumerable enumerable = LanguagePrimitives.GetEnumerable(singleOutputParameter.Value); - if (enumerable != null) + if (enumerable is not null) { foreach (object o in enumerable) { @@ -158,7 +158,7 @@ private void OnNext(CimMethodStreamedResult streamedResult) } var array = LanguagePrimitives.GetEnumerable(streamedResult.ItemValue); - if (array != null) + if (array is not null) { foreach (var element in array) { @@ -173,8 +173,8 @@ private void OnNext(CimMethodStreamedResult streamedResult) private void WriteObject(object cmdletOutput, MethodParameter methodParameter) { - Dbg.Assert(methodParameter != null, "Caller should verify that methodParameter != null"); - if ((cmdletOutput != null) && (!string.IsNullOrEmpty(methodParameter.ParameterTypeName))) + Dbg.Assert(methodParameter is not null, "Caller should verify that methodParameter is not null"); + if ((cmdletOutput is not null) && (!string.IsNullOrEmpty(methodParameter.ParameterTypeName))) { PSObject pso = PSObject.AsPSObject(cmdletOutput); if (!pso.TypeNames.Contains(methodParameter.ParameterTypeName, StringComparer.OrdinalIgnoreCase)) @@ -192,14 +192,14 @@ public override void OnNext(CimMethodResultBase item) delegate { var methodResult = item as CimMethodResult; - if (methodResult != null) + if (methodResult is not null) { this.OnNext(methodResult); return; } var streamedResult = item as CimMethodStreamedResult; - if (streamedResult != null) + if (streamedResult is not null) { this.OnNext(streamedResult); return; diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/InstanceMethodInvocationJob.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/InstanceMethodInvocationJob.cs index cd1eb78d81c..a21c76f71a2 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/InstanceMethodInvocationJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/InstanceMethodInvocationJob.cs @@ -24,7 +24,7 @@ internal InstanceMethodInvocationJob(CimJobContext jobContext, bool passThru, Ci targetInstance.ToString(), methodInvocationInfo) { - Dbg.Assert(targetInstance != null, "Caller should verify targetInstance != null"); + Dbg.Assert(targetInstance is not null, "Caller should verify targetInstance is not null"); _targetInstance = targetInstance; } 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..919ed7b1a27 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/MethodInvocationJobBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/MethodInvocationJobBase.cs @@ -23,8 +23,8 @@ internal abstract class MethodInvocationJobBase : CimChildJobBase internal MethodInvocationJobBase(CimJobContext jobContext, bool passThru, string methodSubject, MethodInvocationInfo methodInvocationInfo) : base(jobContext) { - Dbg.Assert(methodInvocationInfo != null, "Caller should verify methodInvocationInfo != null"); - Dbg.Assert(methodSubject != null, "Caller should verify methodSubject != null"); + Dbg.Assert(methodInvocationInfo is not null, "Caller should verify methodInvocationInfo is not null"); + Dbg.Assert(methodSubject is not null, "Caller should verify methodSubject is not null"); _passThru = passThru; MethodSubject = methodSubject; @@ -98,7 +98,7 @@ internal override CimCustomOptionsDictionary CalculateJobSpecificCustomOptions() internal IEnumerable GetMethodOutputParameters() { IEnumerable allParameters_plus_returnValue = _methodInvocationInfo.Parameters; - if (_methodInvocationInfo.ReturnValue != null) + if (_methodInvocationInfo.ReturnValue is not null) { allParameters_plus_returnValue = allParameters_plus_returnValue.Append(_methodInvocationInfo.ReturnValue); } @@ -113,7 +113,7 @@ internal IEnumerable GetMethodOutputParameters() internal bool ShouldProcess() { - Dbg.Assert(this.MethodSubject != null, "MethodSubject property should be initialized before starting main job processing"); + Dbg.Assert(this.MethodSubject is not null, "MethodSubject property should be initialized before starting main job processing"); if (!this.JobContext.CmdletInvocationContext.CmdletDefinitionContext.ClientSideShouldProcess) { return true; @@ -164,12 +164,12 @@ public override void OnCompleted() this.ExceptionSafeWrapper( delegate { - Dbg.Assert(this.MethodSubject != null, "MethodSubject property should be initialized before starting main job processing"); + Dbg.Assert(this.MethodSubject is not null, "MethodSubject property should be initialized before starting main job processing"); if (this.IsPassThruObjectNeeded()) { object passThruObject = this.PassThruObject; - if (passThruObject != null) + if (passThruObject is not null) { this.WriteObject(passThruObject); } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ModifyInstanceJob.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ModifyInstanceJob.cs index f0d07fc201d..4303edd3e5d 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ModifyInstanceJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ModifyInstanceJob.cs @@ -23,7 +23,7 @@ internal class ModifyInstanceJob : PropertySettingJob internal ModifyInstanceJob(CimJobContext jobContext, bool passThru, CimInstance managementObject, MethodInvocationInfo methodInvocationInfo) : base(jobContext, passThru, managementObject, methodInvocationInfo) { - Dbg.Assert(this.MethodSubject != null, "Caller should verify managementObject != null"); + Dbg.Assert(this.MethodSubject is not null, "Caller should verify managementObject is not null"); _originalInstance = managementObject; } @@ -46,13 +46,13 @@ internal override IObservable GetCimOperation() public override void OnNext(CimInstance item) { - Dbg.Assert(item != null, "ModifyInstance and GetInstance should not return a null instance"); + Dbg.Assert(item is not null, "ModifyInstance and GetInstance should not return a null instance"); _resultFromModifyInstance = item; } public override void OnCompleted() { - Dbg.Assert(_resultFromModifyInstance != null, "ModifyInstance should return an instance over DCOM and WSMan"); + Dbg.Assert(_resultFromModifyInstance is not null, "ModifyInstance should return an instance over DCOM and WSMan"); ModifyLocalCimInstance(_originalInstance); /* modify input CimInstance only upon success (fix for bug WinBlue #) */ base.OnCompleted(); } @@ -61,7 +61,7 @@ internal override object PassThruObject { get { - Dbg.Assert(_resultFromModifyInstance != null, "ModifyInstance should return an instance over DCOM and WSMan"); + Dbg.Assert(_resultFromModifyInstance is not null, "ModifyInstance should return an instance over DCOM and WSMan"); if (IsShowComputerNameMarkerPresent(_originalInstance)) { PSObject pso = PSObject.AsPSObject(_resultFromModifyInstance); @@ -82,13 +82,13 @@ internal override CimCustomOptionsDictionary CalculateJobSpecificCustomOptions() protected override void Dispose(bool disposing) { - if (!_resultFromModifyInstanceHasBeenPassedThru && _resultFromModifyInstance != null) + if (!_resultFromModifyInstanceHasBeenPassedThru && _resultFromModifyInstance is not null) { _resultFromModifyInstance.Dispose(); _resultFromModifyInstance = null; } - if (_temporaryInstance != null) + if (_temporaryInstance is not null) { _temporaryInstance.Dispose(); _temporaryInstance = null; diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/PropertySettingJob.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/PropertySettingJob.cs index f5bdc0745cd..a8152171681 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/PropertySettingJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/PropertySettingJob.cs @@ -26,7 +26,7 @@ internal void ModifyLocalCimInstance(CimInstance cimInstance) { CimValueConverter.AssertIntrinsicCimType(methodParameter.ParameterType); CimProperty propertyBeingModified = cimInstance.CimInstanceProperties[methodParameter.Name]; - if (propertyBeingModified != null) + if (propertyBeingModified is not null) { propertyBeingModified.Value = methodParameter.Value; } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/QueryJob.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/QueryJob.cs index 4297c00616c..3029796c1a3 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/QueryJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/QueryJob.cs @@ -22,7 +22,7 @@ internal class QueryInstancesJob : QueryJobBase internal QueryInstancesJob(CimJobContext jobContext, CimQuery cimQuery, string wqlCondition) : base(jobContext, cimQuery) { - Dbg.Assert(wqlCondition != null, "Caller should verify that wqlCondition is not null"); + Dbg.Assert(wqlCondition is not null, "Caller should verify that wqlCondition is not null"); var wqlQueryBuilder = new StringBuilder(); wqlQueryBuilder.Append("SELECT * FROM "); 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..1560bfa060d 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/QueryJobBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/QueryJobBase.cs @@ -19,7 +19,7 @@ internal abstract class QueryJobBase : CimChildJobBase internal QueryJobBase(CimJobContext jobContext, CimQuery cimQuery) : base(jobContext) { - Dbg.Assert(cimQuery != null, "Caller should verify cimQuery != null"); + Dbg.Assert(cimQuery is not null, "Caller should verify cimQuery is not null"); _cimQuery = cimQuery; } @@ -28,7 +28,7 @@ public override void OnNext(CimInstance item) this.ExceptionSafeWrapper( delegate { - Dbg.Assert(item != null, "When OnNext is called from our IObservable, item parameter should always be != null"); + Dbg.Assert(item is not null, "When OnNext is called from our IObservable, item parameter should always be is not null"); if (item is 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..b5bd2e59efe 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/TerminatingErrorTracker.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/TerminatingErrorTracker.cs @@ -54,7 +54,7 @@ private static int GetNumberOfSessions(InvocationInfo invocationInfo) foreach (object cmdletArgument in invocationInfo.BoundParameters.Values) { CimInstance[] array = cmdletArgument as CimInstance[]; - if (array != null) + if (array is not null) { int numberOfSessionsAssociatedWithArgument = array .Select(CimCmdletAdapter.GetSessionOfOriginFromCimInstance) @@ -150,7 +150,7 @@ internal Exception GetExceptionIfBrokenSession( } } - if (sessionException != null) + if (sessionException is not null) { MarkSessionAsTerminated(potentiallyBrokenSession, out sessionWasAlreadyTerminated); return sessionException; 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..2bccc569881 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs @@ -176,7 +176,7 @@ private void SleepAndRetry_OnWakeup(object state) { lock (_jobStateLock) { - if (_sleepAndRetryTimer != null) + if (_sleepAndRetryTimer is not null) { _sleepAndRetryTimer.Dispose(); _sleepAndRetryTimer = null; @@ -316,7 +316,7 @@ internal override void StartJob() this.ExceptionSafeWrapper(delegate { IObservable observable = this.GetCimOperation(); - if (observable != null) + if (observable is not null) { observable.Subscribe(this); } @@ -346,7 +346,7 @@ internal void ExceptionSafeWrapper(Action action) { try { - Dbg.Assert(action != null, "Caller should verify action != null"); + Dbg.Assert(action is not null, "Caller should verify action is not null"); action(); } catch (CimJobException e) @@ -414,7 +414,7 @@ internal CimOperationOptions CreateOperationOptions() operationOptions.Flags |= this.JobContext.CmdletInvocationContext.CmdletDefinitionContext.SchemaConformanceLevel; - if (this.JobContext.CmdletInvocationContext.CmdletDefinitionContext.ResourceUri != null) + if (this.JobContext.CmdletInvocationContext.CmdletDefinitionContext.ResourceUri is not null) { operationOptions.ResourceUri = this.JobContext.CmdletInvocationContext.CmdletDefinitionContext.ResourceUri; } @@ -499,7 +499,7 @@ internal CimOperationOptions CreateOperationOptions() CimSensitiveValueConverter); } - if (this.JobContext.CmdletizationModuleVersion != null) + if (this.JobContext.CmdletizationModuleVersion is not null) { CimOperationOptionsHelper.SetCustomOption( operationOptions, @@ -523,7 +523,7 @@ internal CimOperationOptions CreateOperationOptions() } CimCustomOptionsDictionary jobSpecificCustomOptions = this.GetJobSpecificCustomOptions(); - if (jobSpecificCustomOptions != null) + if (jobSpecificCustomOptions is not null) { jobSpecificCustomOptions.Apply(operationOptions, CimSensitiveValueConverter); } @@ -564,7 +564,7 @@ public override void StopJob() { this.SetCompletedJobState(JobState.Stopped, null); } - else if (_sleepAndRetryTimer != null) + else if (_sleepAndRetryTimer is not null) { _sleepAndRetryTimer.Dispose(); _sleepAndRetryTimer = null; @@ -614,7 +614,7 @@ internal void ReportJobFailure(IContainsErrorRecord exception) } } - if (brokenSessionException != null) + if (brokenSessionException is not null) { string brokenSessionMessage = string.Format( CultureInfo.InvariantCulture, @@ -631,7 +631,7 @@ internal void ReportJobFailure(IContainsErrorRecord exception) else { CimJobException cje = exception as CimJobException; - if ((cje != null) && (cje.IsTerminatingError)) + if ((cje is not null) && (cje.IsTerminatingError)) { terminatingErrorTracker.MarkSessionAsTerminated(this.JobContext.Session, out sessionWasAlreadyTerminated); isThisTerminatingError = true; @@ -706,7 +706,7 @@ internal void SetCompletedJobState(JobState state, Exception reason) _alreadyReachedCompletedState = true; - if ((state == JobState.Failed) || (reason != null)) + if ((state == JobState.Failed) || (reason is not null)) { _jobHadErrors = true; } @@ -861,7 +861,7 @@ private CimResponseType BlockingWriteError(ErrorRecord errorRecord) this.WriteError(errorRecord, out exceptionThrownOnCmdletThread); }); - return (exceptionThrownOnCmdletThread != null) + return (exceptionThrownOnCmdletThread is not null) ? CimResponseType.NoToAll : CimResponseType.Yes; } @@ -940,7 +940,7 @@ internal CimResponseType ShouldProcess( Exception exceptionThrownOnCmdletThread; ShouldProcessReason shouldProcessReason; bool shouldProcessResponse = this.ShouldProcess(verboseDescription, verboseWarning, caption, out shouldProcessReason, out exceptionThrownOnCmdletThread); - if (exceptionThrownOnCmdletThread != null) + if (exceptionThrownOnCmdletThread is not null) { return CimResponseType.NoToAll; } @@ -992,7 +992,7 @@ private CimResponseType PromptUserCallback(string message, CimPromptType promptT break; } - if (exceptionThrownOnCmdletThread != null) + if (exceptionThrownOnCmdletThread is not null) { result = CimResponseType.NoToAll; } @@ -1022,7 +1022,7 @@ internal static bool IsShowComputerNameMarkerPresent(CimInstance cimInstance) internal static void AddShowComputerNameMarker(PSObject pso) { PSPropertyInfo psShowComputerNameProperty = pso.InstanceMembers[RemotingConstants.ShowComputerNameNoteProperty] as PSPropertyInfo; - if (psShowComputerNameProperty != null) + if (psShowComputerNameProperty is not null) { psShowComputerNameProperty.Value = true; } @@ -1047,7 +1047,7 @@ internal override void WriteObject(object outputObject) cimInstance = outputObject as CimInstance; } - if (cimInstance != null) + if (cimInstance is not null) { CimCmdletAdapter.AssociateSessionOfOriginWithInstance(cimInstance, this.JobContext.Session); CimCustomOptionsDictionary.AssociateCimInstanceWithCustomOptions(cimInstance, this.GetJobSpecificCustomOptions()); diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletDefinitionContext.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletDefinitionContext.cs index 6fa40516322..5da7d7eb028 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletDefinitionContext.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletDefinitionContext.cs @@ -48,7 +48,7 @@ public bool UseEnumerateInstancesInsteadOfWql { bool newValue = false; string queryLanguage; - if (_privateData != null && + if (_privateData is not null && _privateData.TryGetValue(QueryLanguageKey, out queryLanguage) && queryLanguage.Equals("None", StringComparison.OrdinalIgnoreCase)) { @@ -123,7 +123,7 @@ public Uri ResourceUri { string newResourceUriString; Uri newResourceUri; - if (_privateData != null && + if (_privateData is not null && _privateData.TryGetValue("ResourceUri", out newResourceUriString) && Uri.TryCreate(newResourceUriString, UriKind.RelativeOrAbsolute, out newResourceUri)) { @@ -153,7 +153,7 @@ public CimOperationFlags SchemaConformanceLevel CimOperationFlags newSchemaConformanceLevel = 0; string schemaConformanceFromCdxml; - if (_privateData != null && + if (_privateData is not null && _privateData.TryGetValue("TypeInformation", out schemaConformanceFromCdxml)) { if (schemaConformanceFromCdxml.Equals("Basic", StringComparison.OrdinalIgnoreCase)) diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletInvocationContext.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletInvocationContext.cs index cfa26ca0e05..c7ad2a6c04f 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletInvocationContext.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletInvocationContext.cs @@ -26,7 +26,7 @@ internal CimCmdletInvocationContext( this.CmdletInvocationInfo = cmdlet.MyInvocation; var runtime = cmdlet.CommandRuntime as MshCommandRuntime; - Dbg.Assert(runtime != null, "CIM cmdlets should only be run from within PS runtime"); + Dbg.Assert(runtime is not null, "CIM cmdlets should only be run from within PS runtime"); this.DebugActionPreference = runtime.DebugPreference; WarnAboutUnsupportedActionPreferences( 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..b7f5b382564 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs @@ -197,7 +197,7 @@ internal object ConvertFromDotNetToCim(object dotNetObject) if (dotNetType.IsArray) { Type dotNetElementType = CimValueConverter.GetElementType(dotNetType); - if (dotNetElementType != null) + if (dotNetElementType is not null) { var dotNetArray = (Array)psObject.BaseObject; Type cimElementType = GetCimType(dotNetElementType); @@ -274,7 +274,7 @@ internal static object ConvertFromDotNetToCim(object dotNetObject) if (dotNetType.IsArray) { Type dotNetElementType = GetElementType(dotNetType); - if (dotNetElementType != null) + if (dotNetElementType is not null) { var dotNetArray = (Array)psObject.BaseObject; Type cimElementType = CimValueConverter.GetCimType(dotNetElementType); @@ -290,7 +290,7 @@ internal static object ConvertFromDotNetToCim(object dotNetObject) } Type convertibleCimType = GetConvertibleCimType(dotNetType); - if (convertibleCimType != null) + if (convertibleCimType is not null) { object cimIntrinsicValue = LanguagePrimitives.ConvertTo(dotNetObject, convertibleCimType, CultureInfo.InvariantCulture); return cimIntrinsicValue; @@ -377,7 +377,7 @@ internal static object ConvertFromCimToDotNet(object cimObject, Type expectedDot if (expectedDotNetType.IsArray) { Type dotNetElementType = GetElementType(expectedDotNetType); - if (dotNetElementType != null) + if (dotNetElementType is not null) { var cimArray = (Array)LanguagePrimitives.ConvertTo(cimObject, typeof(Array), CultureInfo.InvariantCulture); Array dotNetArray = Array.CreateInstance(dotNetElementType, cimArray.Length); @@ -392,7 +392,7 @@ internal static object ConvertFromCimToDotNet(object cimObject, Type expectedDot } Type convertibleCimType = GetConvertibleCimType(expectedDotNetType); - if (convertibleCimType != null) + if (convertibleCimType is not null) { object cimIntrinsicValue = LanguagePrimitives.ConvertTo(cimObject, convertibleCimType, CultureInfo.InvariantCulture); object dotNetObject = LanguagePrimitives.ConvertTo(cimIntrinsicValue, expectedDotNetType, CultureInfo.InvariantCulture); @@ -490,7 +490,7 @@ internal static object ConvertFromCimToDotNet(object cimObject, Type expectedDot internal static CimType GetCimTypeEnum(Type dotNetType) { - Dbg.Assert(dotNetType != null, "Caller should make sure that dotNetType != null"); + Dbg.Assert(dotNetType is not null, "Caller should make sure that dotNetType is not null"); if (typeof(PSReference).IsAssignableFrom(dotNetType)) { @@ -535,7 +535,7 @@ internal static Type GetCimType(Type dotNetType) } Type result = CimValueConverter.GetConvertibleCimType(dotNetType); - if (result != null) + if (result is not null) { return result; } @@ -619,7 +619,7 @@ private static Type GetConvertibleCimType(Type dotNetType) internal static Type GetElementType(Type arrayType) { - Dbg.Assert(arrayType != null, "Caller should verify arrayType != null"); + Dbg.Assert(arrayType is not null, "Caller should verify arrayType is not null"); Dbg.Assert(arrayType.IsArray, "Caller should verify arrayType.IsArray"); // MOF syntax from Appendix A of DSP0004 doesn't allow expressing @@ -647,7 +647,7 @@ internal static PSInvalidCastException GetInvalidCastException( string descriptionOfTargetType) { Dbg.Assert(!string.IsNullOrEmpty(errorId), "Caller should verify !string.IsNullOrEmpty(errorId)"); - Dbg.Assert(sourceValue != null, "Caller should verify sourceValue != null"); + Dbg.Assert(sourceValue is not null, "Caller should verify sourceValue is not null"); Dbg.Assert(!string.IsNullOrEmpty(descriptionOfTargetType), "Caller should verify !string.IsNullOrEmpty(descriptionOfTargetType)"); throw new PSInvalidCastException( @@ -662,7 +662,7 @@ internal static PSInvalidCastException GetInvalidCastException( [Conditional("DEBUG")] internal static void AssertIntrinsicCimValue(object value) { - Dbg.Assert(value != null, "Caller should verify value != null"); + Dbg.Assert(value is not null, "Caller should verify value is not null"); Type type = value.GetType(); AssertIntrinsicCimType(type); Dbg.Assert(!typeof(PSReference).IsAssignableFrom(type) && typeof(PSReference[]) != type, @@ -672,7 +672,7 @@ internal static void AssertIntrinsicCimValue(object value) [Conditional("DEBUG")] internal static void AssertIntrinsicCimType(Type type) { - Dbg.Assert(type != null, "Caller should verify type != null"); + Dbg.Assert(type is not null, "Caller should verify type is not null"); Dbg.Assert( LanguagePrimitives.IsCimIntrinsicScalarType(type) || (type.IsArray && LanguagePrimitives.IsCimIntrinsicScalarType(type.GetElementType())) || 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..c5935612dcf 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimJobContext.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimJobContext.cs @@ -40,7 +40,7 @@ public string ClassNameOrNullIfResourceUriIsUsed { get { - if (this.CmdletInvocationContext.CmdletDefinitionContext.ResourceUri != null) + if (this.CmdletInvocationContext.CmdletDefinitionContext.ResourceUri is not null) { return null; } 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..9b2406e2002 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimOperationOptionsHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimOperationOptionsHelper.cs @@ -83,7 +83,7 @@ internal static void AssociateCimInstanceWithCustomOptions(CimInstance cimInstan internal static CimCustomOptionsDictionary MergeOptions(CimCustomOptionsDictionary optionsFromCommandLine, CimInstance instanceRelatedToThisOperation) { CimCustomOptionsDictionary instanceRelatedOptions; - if (s_cimInstanceToCustomOptions.TryGetValue(instanceRelatedToThisOperation, out instanceRelatedOptions) && instanceRelatedOptions != null) + if (s_cimInstanceToCustomOptions.TryGetValue(instanceRelatedToThisOperation, out instanceRelatedOptions) && instanceRelatedOptions is not null) { IEnumerable> instanceRelatedOptionsSnapshot = instanceRelatedOptions.GetSnapshot(); IEnumerable> optionsFromCommandLineSnapshot = optionsFromCommandLine.GetSnapshot(); @@ -99,7 +99,7 @@ internal static CimCustomOptionsDictionary MergeOptions(CimCustomOptionsDictiona internal static CimCustomOptionsDictionary MergeOptions(CimCustomOptionsDictionary optionsFromCommandLine, IEnumerable instancesRelatedToThisOperation) { CimCustomOptionsDictionary result = optionsFromCommandLine; - if (instancesRelatedToThisOperation != null) + if (instancesRelatedToThisOperation is not null) { foreach (CimInstance instanceRelatedToThisOperation in instancesRelatedToThisOperation) { @@ -126,7 +126,7 @@ internal static void SetCustomOptions( IEnumerable> customOptions, CimSensitiveValueConverter cimSensitiveValueConverter) { - if (customOptions != null) + if (customOptions is not null) { foreach (KeyValuePair queryOption in customOptions) { @@ -141,7 +141,7 @@ internal static void SetCustomOption( object optionValue, CimSensitiveValueConverter cimSensitiveValueConverter) { - Dbg.Assert(!string.IsNullOrWhiteSpace(optionName), "Caller should verify optionName != null"); + Dbg.Assert(!string.IsNullOrWhiteSpace(optionName), "Caller should verify optionName is not null"); if (optionValue is null) { diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs index 1180714267b..a6c32cd80dd 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs @@ -345,7 +345,7 @@ internal StartableJob GetQueryJob(CimJobContext jobContext) internal bool IsMatchingResult(CimInstance result) { - Dbg.Assert(result != null, "Caller should verify result != null"); + Dbg.Assert(result is not null, "Caller should verify result is not null"); return this.ClientSideQuery.IsResultMatchingClientSideQuery(result); } @@ -358,7 +358,7 @@ internal bool IsMatchingResult(CimInstance result) CimSession ISessionBoundQueryBuilder.GetTargetSession() { - if (_associatedObject != null) + if (_associatedObject is not null) { return CimCmdletAdapter.GetSessionOfOriginFromCimInstance(_associatedObject); } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimWrapper.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimWrapper.cs index 6270175bc15..93aed5cfbb1 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimWrapper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimWrapper.cs @@ -218,7 +218,7 @@ internal override StartableJob CreateInstanceMethodInvocationJob(CimSession sess CimJobContext jobContext = this.CreateJobContext(session, objectInstance); - Dbg.Assert(objectInstance != null, "Caller should verify objectInstance != null"); + Dbg.Assert(objectInstance is not null, "Caller should verify objectInstance is not null"); StartableJob result; if (methodInvocationInfo.MethodName.Equals(CimCmdletAdapter.DeleteInstance_MethodName, StringComparison.OrdinalIgnoreCase)) @@ -255,11 +255,11 @@ private bool IsSupportedSession(CimSession cimSession, TerminatingErrorTracker t bool whatIfSwitchSpecified = this.CmdletInvocationInfo.BoundParameters.ContainsKey("WhatIf"); if (confirmSwitchSpecified || whatIfSwitchSpecified) { - if (cimSession.ComputerName != null && (!cimSession.ComputerName.Equals("localhost", StringComparison.OrdinalIgnoreCase))) + if (cimSession.ComputerName is not null && (!cimSession.ComputerName.Equals("localhost", StringComparison.OrdinalIgnoreCase))) { PSPropertyInfo protocolProperty = PSObject.AsPSObject(cimSession).Properties["Protocol"]; - if ((protocolProperty != null) && - (protocolProperty.Value != null) && + if ((protocolProperty is not null) && + (protocolProperty.Value is not null) && (protocolProperty.Value.ToString().Equals("DCOM", StringComparison.OrdinalIgnoreCase))) { bool sessionWasAlreadyTerminated; @@ -351,7 +351,7 @@ internal static void AssociateSessionOfOriginWithInstance(CimInstance cimInstanc internal static CimSession GetSessionOfOriginFromCimInstance(CimInstance instance) { CimSession result = null; - if (instance != null) + if (instance is not null) { s_cimInstanceToSessionOfOrigin.TryGetValue(instance, out result); } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs index 60c534512a3..374cebd3bba 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs @@ -37,7 +37,7 @@ public NotFoundError(string propertyName, object propertyValue, bool wildcardsEn if (wildcardsEnabled) { var propertyValueAsString = propertyValue as string; - if ((propertyValueAsString != null) && (WildcardPattern.ContainsWildcardCharacters(propertyValueAsString))) + if ((propertyValueAsString is not null) && (WildcardPattern.ContainsWildcardCharacters(propertyValueAsString))) { this.ErrorMessageGenerator = (queryDescription, className) => GetErrorMessageForNotFound_ForWildcard(this.PropertyName, this.PropertyValue, className); @@ -467,7 +467,7 @@ protected override BehaviorOnNoMatch GetDefaultBehaviorWhenNoMatchesFound(object else { string expectedPropertyValueAsString = cimTypedExpectedPropertyValue as string; - if (expectedPropertyValueAsString != null && WildcardPattern.ContainsWildcardCharacters(expectedPropertyValueAsString)) + if (expectedPropertyValueAsString is not null && WildcardPattern.ContainsWildcardCharacters(expectedPropertyValueAsString)) { return BehaviorOnNoMatch.SilentlyContinue; } @@ -505,7 +505,7 @@ private static bool NonWildcardEqual(string propertyName, object actualPropertyV } var expectedPropertyValueAsString = expectedPropertyValue as string; - if (expectedPropertyValueAsString != null) + if (expectedPropertyValueAsString is not null) { var actualPropertyValueAsString = (string)actualPropertyValue; return actualPropertyValueAsString.Equals(expectedPropertyValueAsString, StringComparison.OrdinalIgnoreCase); @@ -667,7 +667,7 @@ internal IEnumerable GenerateNotFoundErrors() } CimInstanceFilterBase filter = _filters.SingleOrDefault(); - if (filter != null) + if (filter is not null) { return filter.GetNotFoundErrors_IfThisIsTheOnlyFilter(); } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/AddContentCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/AddContentCommand.cs index af8efbd6885..583ce1a56e3 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/AddContentCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/AddContentCommand.cs @@ -33,7 +33,7 @@ internal override void SeekContentPosition(List contentHolders) { foreach (ContentHolder holder in contentHolders) { - if (holder.Writer != null) + if (holder.Writer is not null) { try { diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/CIMHelper.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/CIMHelper.cs index 559af13127b..1d51ad2ebc0 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/CIMHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/CIMHelper.cs @@ -141,7 +141,7 @@ internal static string WqlQueryAll(string from) { var instances = session.QueryInstances(nameSpace, CIMHelper.WqlQueryAll(wmiClassName)); - if (instances != null) + if (instances is not null) { var type = typeof(T); var binding = BindingFlags.Public | BindingFlags.Instance; @@ -202,7 +202,7 @@ internal static void SetObjectDataMember(object obj, BindingFlags binding, CimPr var pi = type.GetProperty(cimProperty.Name, binding); - if (pi != null && pi.CanWrite) + if (pi is not null && pi.CanWrite) { pi.SetValue(obj, cimProperty.Value, null); } @@ -210,7 +210,7 @@ internal static void SetObjectDataMember(object obj, BindingFlags binding, CimPr { var fi = type.GetField(cimProperty.Name, binding); - if (fi != null && !fi.IsInitOnly) + if (fi is not null && !fi.IsInitOnly) { fi.SetValue(obj, cimProperty.Value); } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearContentCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearContentCommand.cs index 61726686f28..bd2451d52d9 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearContentCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearContentCommand.cs @@ -91,7 +91,7 @@ protected override bool ProviderSupportsShouldProcess /// internal override object GetDynamicParameters(CmdletProviderContext context) { - if (Path != null && Path.Length > 0) + if (Path is not null && Path.Length > 0) { // Go ahead an let any exceptions terminate the pipeline. return InvokeProvider.Content.ClearContentDynamicParameters(Path[0], context); diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearPropertyCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearPropertyCommand.cs index 75ee9a639e3..f31c212262b 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearPropertyCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearPropertyCommand.cs @@ -89,7 +89,7 @@ internal override object GetDynamicParameters(CmdletProviderContext context) Collection propertyCollection = new Collection(); propertyCollection.Add(_property); - if (Path != null && Path.Length > 0) + if (Path is not null && Path.Length > 0) { // Go ahead and let any exception terminate the pipeline. diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearRecycleBinCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearRecycleBinCommand.cs index 4b2ab1095f2..844bfa41e14 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearRecycleBinCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearRecycleBinCommand.cs @@ -71,7 +71,7 @@ protected override void ProcessRecord() { // There are two scenarios: // 1) The user provides a list of drives. - if (_drivesList != null) + if (_drivesList is not null) { foreach (var drive in _drivesList) { @@ -109,7 +109,7 @@ protected override void ProcessRecord() private bool ValidDrivePath(string drivePath) { DriveInfo actualDrive = null; - if (_availableDrives != null) + if (_availableDrives is not null) { foreach (DriveInfo drive in _availableDrives) { diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Clipboard.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Clipboard.cs index 38a1b5c48a6..f0d03e7cd8a 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Clipboard.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Clipboard.cs @@ -378,7 +378,7 @@ private static void ExecuteOnStaThread(Func action) thread.Start(); thread.Join(); - if (exception != null) + if (exception is not null) { throw exception; } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/CombinePathCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/CombinePathCommand.cs index bd97d485cd1..8f071ba1675 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/CombinePathCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/CombinePathCommand.cs @@ -62,13 +62,13 @@ public class JoinPathCommand : CoreCommandWithCredentialsBase protected override void ProcessRecord() { Dbg.Diagnostics.Assert( - Path != null, + Path is not null, "Since Path is a mandatory parameter, paths should never be null"); string combinedChildPath = ChildPath; // join the ChildPath elements - if (AdditionalChildPath != null) + if (AdditionalChildPath is not null) { foreach (string childPath in AdditionalChildPath) { @@ -167,7 +167,7 @@ protected override void ProcessRecord() { try { - if (resolvedPaths[index] != null) + if (resolvedPaths[index] is not null) { WriteObject(resolvedPaths[index].Path); } @@ -208,7 +208,7 @@ protected override void ProcessRecord() } else { - if (joinedPath != null) + if (joinedPath is not null) { WriteObject(joinedPath); } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs index 0d0bf2f17d9..9f20ace0366 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs @@ -389,14 +389,14 @@ public void Dispose(bool disposing) { if (disposing) { - if (_timer != null) + if (_timer is not null) { _timer.Dispose(); } _waitHandler.Dispose(); _cancel.Dispose(); - if (_powershell != null) + if (_powershell is not null) { _powershell.Dispose(); } @@ -423,7 +423,7 @@ private void ValidateComputerNames() string targetComputerName = ComputerWMIHelper.ValidateComputerName(name, _shortLocalMachineName, _fullLocalMachineName, ref error); if (targetComputerName is null) { - if (error != null) + if (error is not null) { WriteError(error); } @@ -511,7 +511,7 @@ private void OnTimedEvent(object s) _cancel.Cancel(); _waitHandler.Set(); - if (_powershell != null) + if (_powershell is not null) { _powershell.Stop(); _powershell.Dispose(); @@ -749,7 +749,7 @@ internal static List TestPowerShell(List computerNames, List ComputerWMIHelper.NetBIOSNameMaxLength) + if (newName is not null && newName.Length > ComputerWMIHelper.NetBIOSNameMaxLength) { string truncatedName = newName.Substring(0, ComputerWMIHelper.NetBIOSNameMaxLength); string query = StringUtil.Format(ComputerResources.TruncateNetBIOSName, truncatedName); @@ -1472,7 +1472,7 @@ private void DoRenameComputerWsman(string computer, string computerName, string // If the target computer is not in a domain, just use null for the UserName and Password string dUserName = null; string dPassword = null; - if (((bool)cimInstance.CimInstanceProperties["PartOfDomain"].Value) && (DomainCredential != null)) + if (((bool)cimInstance.CimInstanceProperties["PartOfDomain"].Value) && (DomainCredential is not null)) { dUserName = DomainCredential.UserName; dPassword = Utils.GetStringFromSecureString(DomainCredential.Password); @@ -1916,10 +1916,10 @@ internal static string GetMachineNames(string[] computerNames) { string separator = ","; RegistryKey regKey = Registry.CurrentUser.OpenSubKey(@"Control Panel\International"); - if (regKey != null) + if (regKey is not null) { object sListValue = regKey.GetValue("sList"); - if (sListValue != null) + if (sListValue is not null) { separator = sListValue.ToString(); } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs index da9c0cc4d00..efa0cf697b1 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs @@ -128,27 +128,27 @@ public override SwitchParameter Force internal void WriteContentObject(object content, long readCount, PathInfo pathInfo, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - content != null, + content is not null, "The caller should verify the content."); Dbg.Diagnostics.Assert( - pathInfo != null, + pathInfo is not null, "The caller should verify the pathInfo."); Dbg.Diagnostics.Assert( - context != null, + context is not null, "The caller should verify the context."); PSObject result = PSObject.AsPSObject(content); Dbg.Diagnostics.Assert( - result != null, + result is not null, "A PSObject should always be constructed."); // Use the cached notes if the cache exists and the path is still the same PSNoteProperty note; - if (_currentContentItem != null && + if (_currentContentItem is not null && ((_currentContentItem.PathInfo == pathInfo) || string.Equals( pathInfo.Path, @@ -176,7 +176,7 @@ internal void WriteContentObject(object content, long readCount, PathInfo pathIn string parentPath = null; - if (pathInfo.Drive != null) + if (pathInfo.Drive is not null) { parentPath = SessionState.Path.ParseParent(pathInfo.Path, pathInfo.Drive.Root, context); } @@ -205,7 +205,7 @@ internal void WriteContentObject(object content, long readCount, PathInfo pathIn // PSDriveInfo - if (pathInfo.Drive != null) + if (pathInfo.Drive is not null) { PSDriveInfo drive = pathInfo.Drive; note = new PSNoteProperty("PSDrive", drive); @@ -315,7 +315,7 @@ public PSObject AttachNotes(PSObject content) // PSDriveInfo - if (PathInfo.Drive != null) + if (PathInfo.Drive is not null) { note = new PSNoteProperty("PSDrive", Drive); content.Properties.Add(note, true); @@ -374,7 +374,7 @@ internal void CloseContent(List contentHolders, bool disposing) { try { - if (holder.Writer != null) + if (holder.Writer is not null) { holder.Writer.Close(); } @@ -411,7 +411,7 @@ internal void CloseContent(List contentHolders, bool disposing) try { - if (holder.Reader != null) + if (holder.Reader is not null) { holder.Reader.Close(); } @@ -533,9 +533,9 @@ internal List GetContentReaders( continue; } - if (readers != null && readers.Count > 0) + if (readers is not null && readers.Count > 0) { - if (readers.Count == 1 && readers[0] != null) + if (readers.Count == 1 && readers[0] is not null) { ContentHolder holder = new ContentHolder(pathInfo, readers[0], null); diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ControlPanelItemCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ControlPanelItemCommand.cs index fffb36d2979..fdb3b3d3236 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ControlPanelItemCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ControlPanelItemCommand.cs @@ -230,7 +230,7 @@ private static bool CompareVerbActionOpen(string verbActionName) ? canonicalName.Substring(0, canonicalName.IndexOf('\0')) : null; - if (canonicalName != null && canonicalName.Equals(RegionCanonicalName, StringComparison.OrdinalIgnoreCase)) + if (canonicalName is not null && canonicalName.Equals(RegionCanonicalName, StringComparison.OrdinalIgnoreCase)) { // The 'Region' control panel item always has '&Open' (english or other locale) as the first verb name s_verbActionOpenName = item.Verbs().Item(0).Name; @@ -238,7 +238,7 @@ private static bool CompareVerbActionOpen(string verbActionName) } } - Dbg.Assert(s_verbActionOpenName != null, "The 'Region' control panel item is available on all SKUs and it always " + Dbg.Assert(s_verbActionOpenName is not null, "The 'Region' control panel item is available on all SKUs and it always " + "has '&Open' as the first verb item, so VerbActionOpenName should never be null at this point"); } @@ -257,7 +257,7 @@ private bool IsServerCoreOrHeadLessServer() using (RegistryKey installation = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion")) { - Dbg.Assert(installation != null, "the CurrentVersion subkey should exist"); + Dbg.Assert(installation is not null, "the CurrentVersion subkey should exist"); string installationType = (string)installation.GetValue("InstallationType", string.Empty); @@ -271,7 +271,7 @@ private bool IsServerCoreOrHeadLessServer() { ps.AddScript(TestHeadlessServerScript); Collection psObjectCollection = ps.Invoke(Array.Empty()); - Dbg.Assert(psObjectCollection != null && psObjectCollection.Count == 1, "invoke should never return null, there should be only one return item"); + Dbg.Assert(psObjectCollection is not null && psObjectCollection.Count == 1, "invoke should never return null, there should be only one return item"); if (LanguagePrimitives.IsTrue(PSObject.Base(psObjectCollection[0]))) { result = true; @@ -451,7 +451,7 @@ internal List GetControlPanelItemByCanonicalName(List internal override object GetDynamicParameters(CmdletProviderContext context) { - if (Path != null && Path.Length > 0) + if (Path is not null && Path.Length > 0) { return InvokeProvider.Property.CopyPropertyDynamicParameters( Path[0], diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Eventlog.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Eventlog.cs index 45c484744fa..bac2c9fa1b4 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Eventlog.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Eventlog.cs @@ -422,7 +422,7 @@ private void Process(EventLog log) throw; } - if ((entry != null) && + if ((entry is not null) && ((lastindex == Int32.MinValue || lastindex - entry.Index == 1))) { @@ -462,7 +462,7 @@ private void Process(EventLog log) private bool FiltersMatch(EventLogEntry entry) { - if (_indexes != null) + if (_indexes is not null) { if (!((IList)_indexes).Contains(entry.Index)) { @@ -470,7 +470,7 @@ private bool FiltersMatch(EventLogEntry entry) } } - if (_instanceIds != null) + if (_instanceIds is not null) { if (!((IList)_instanceIds).Contains(entry.InstanceId)) { @@ -478,7 +478,7 @@ private bool FiltersMatch(EventLogEntry entry) } } - if (_entryTypes != null) + if (_entryTypes is not null) { bool entrymatch = false; foreach (string type in _entryTypes) @@ -493,7 +493,7 @@ private bool FiltersMatch(EventLogEntry entry) if (!entrymatch) return entrymatch; } - if (_sources != null) + if (_sources is not null) { bool sourcematch = false; foreach (string source in _sources) @@ -514,7 +514,7 @@ private bool FiltersMatch(EventLogEntry entry) if (!sourcematch) return sourcematch; } - if (_message != null) + if (_message is not null) { if (WildcardPattern.ContainsWildcardCharacters(_message)) { @@ -528,13 +528,13 @@ private bool FiltersMatch(EventLogEntry entry) } } - if (_username != null) + if (_username is not null) { bool usernamematch = false; foreach (string user in _username) { _isThrowError = false; - if (entry.UserName != null) + if (entry.UserName is not null) { WildcardPattern wildcardpattern = WildcardPattern.Get(user, WildcardOptions.IgnoreCase); if (wildcardpattern.IsMatch(entry.UserName)) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetChildrenCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetChildrenCommand.cs index b6ff487fcdb..ab66d468265 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetChildrenCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetChildrenCommand.cs @@ -218,7 +218,7 @@ internal override object GetDynamicParameters(CmdletProviderContext context) object result = null; string path = string.Empty; - if (_paths != null && _paths.Length > 0) + if (_paths is not null && _paths.Length > 0) { path = _paths[0]; } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs index d7cb6dbd3f6..d9d95772c77 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs @@ -129,7 +129,7 @@ protected override void BeginProcessing() { // if the Property parameter was given, determine the requested // property names - if (Property != null && Property.Length > 0) + if (Property is not null && Property.Length > 0) { try { @@ -149,7 +149,7 @@ protected override void ProcessRecord() { // if the user provided property names but no matching properties // were found, return an empty custom object - if (_namedProperties != null && _namedProperties.Count == 0) + if (_namedProperties is not null && _namedProperties.Count == 0) { WriteObject(new PSObject()); return; @@ -167,11 +167,11 @@ protected override void ProcessRecord() osInfo.os = session.GetFirst(CIMHelper.ClassNames.OperatingSystem); osInfo.pageFileUsage = session.GetAll(CIMHelper.ClassNames.PageFileUsage); - if (osInfo.os != null) + if (osInfo.os is not null) { osInfo.halVersion = GetHalVersion(session, osInfo.os.SystemDirectory); - if (osInfo.os.LastBootUpTime != null) + if (osInfo.os.LastBootUpTime is not null) osInfo.upTime = now - osInfo.os.LastBootUpTime.Value; } @@ -202,7 +202,7 @@ protected override void ProcessRecord() var infoOutput = CreateFullOutputObject(systemInfo, osInfo, miscInfo); - if (_namedProperties != null) + if (_namedProperties is not null) { // var output = CreateCustomOutputObject(namedProperties, systemInfo, osInfo, miscInfo); var output = CreateCustomOutputObject(infoOutput, _namedProperties); @@ -251,7 +251,7 @@ private static string GetHalVersion(CimSession session, string systemDirectory) var query = string.Format("SELECT * FROM CIM_DataFile Where Name='{0}'", halPath); var instance = session.QueryFirstInstance(query); - if (instance != null) + if (instance is not null) halVersion = instance.CimInstanceProperties["Version"].Value.ToString(); } catch (Exception) @@ -285,13 +285,13 @@ private static NetworkAdapter[] GetNetworkAdapters(CimSession session) var list = new List(); - if (adapters != null && configs != null) + if (adapters is not null && configs is not null) { var configDict = new Dictionary(); foreach (var config in configs) { - if (config.Index != null) + if (config.Index is not null) configDict[config.Index.Value] = config; } @@ -301,8 +301,8 @@ private static NetworkAdapter[] GetNetworkAdapters(CimSession session) { // Only include adapters that have a non-null connection status // and a non-null index - if (adapter.NetConnectionStatus != null - && adapter.Index != null) + if (adapter.NetConnectionStatus is not null + && adapter.Index is not null) { if (configDict.ContainsKey(adapter.Index.Value)) { @@ -344,7 +344,7 @@ private static Processor[] GetProcessors(CimSession session) { var processors = session.GetAll(CIMHelper.ClassNames.Processor); - if (processors != null) + if (processors is not null) { var list = new List(); @@ -429,10 +429,10 @@ private static DeviceGuardInfo GetDeviceGuard(CimSession session) var wmiGuard = session.GetFirst(CIMHelper.DeviceGuardNamespace, CIMHelper.ClassNames.DeviceGuard); - if (wmiGuard != null) + if (wmiGuard is not null) { var smartStatus = EnumConverter.Convert((int?)wmiGuard.VirtualizationBasedSecurityStatus ?? 0); - if (smartStatus != null) + if (smartStatus is not null) { status = (DeviceGuardSmartStatus)smartStatus; } @@ -454,13 +454,13 @@ private static DeviceGuardInfo GetDeviceGuard(CimSession session) /// private static bool? GetBooleanProperty(CimInstance instance, string propertyName) { - if (instance != null) + if (instance is not null) { try { var property = instance.CimInstanceProperties[propertyName]; - if (property != null && property.Value != null) + if (property is not null && property.Value is not null) return (bool)property.Value; } catch (Exception) @@ -492,7 +492,7 @@ private static HyperVInfo GetHyperVisorInfo(CimSession session) using (instance = session.QueryFirstInstance(CIMHelper.WqlQueryAll(CIMHelper.ClassNames.ComputerSystem))) { - if (instance != null) + if (instance is not null) { info.Present = GetBooleanProperty(instance, "HypervisorPresent"); ok = true; @@ -501,12 +501,12 @@ private static HyperVInfo GetHyperVisorInfo(CimSession session) // don't bother checking requirements if the HyperV in present // when the HyperV is present, the requirements values are misleading - if (ok && info.Present != null && info.Present.Value) + if (ok && info.Present is not null && info.Present.Value) return info; using (instance = session.QueryFirstInstance(CIMHelper.WqlQueryAll(CIMHelper.ClassNames.OperatingSystem))) { - if (instance != null) + if (instance is not null) { info.DataExecutionPreventionAvailable = GetBooleanProperty(instance, "DataExecutionPrevention_Available"); ok = true; @@ -515,7 +515,7 @@ private static HyperVInfo GetHyperVisorInfo(CimSession session) using (instance = session.QueryFirstInstance(CIMHelper.WqlQueryAll(CIMHelper.ClassNames.Processor))) { - if (instance != null) + if (instance is not null) { info.SecondLevelAddressTranslation = GetBooleanProperty(instance, "SecondLevelAddressTranslationExtensions"); info.VirtualizationFirmwareEnabled = GetBooleanProperty(instance, "VirtualizationFirmwareEnabled"); @@ -569,7 +569,7 @@ private static MiscInfoGroup GetOtherInfo(CimSession session) // get time zone // we'll use .Net's TimeZoneInfo for now. systeminfo uses Caption from Win32_TimeZone var tzi = TimeZoneInfo.Local; - if (tzi != null) + if (tzi is not null) rv.timeZone = tzi.DisplayName; rv.logonServer = RegistryInfo.GetLogonServer(); @@ -672,7 +672,7 @@ private static ComputerInfo CreateFullOutputObject(SystemInfoGroup systemInfo, O var output = new ComputerInfo(); var regCurVer = osInfo.regCurVer; - if (regCurVer != null) + if (regCurVer is not null) { output.WindowsBuildLabEx = regCurVer.BuildLabEx; output.WindowsCurrentVersion = regCurVer.CurrentVersion; @@ -689,7 +689,7 @@ private static ComputerInfo CreateFullOutputObject(SystemInfoGroup systemInfo, O } var os = osInfo.os; - if (os != null) + if (os is not null) { output.OsName = os.Caption; output.OsBootDevice = os.BootDevice; @@ -715,7 +715,7 @@ private static ComputerInfo CreateFullOutputObject(SystemInfoGroup systemInfo, O output.OsFreeSpaceInPagingFiles = os.FreeSpaceInPagingFiles; output.OsTotalVirtualMemorySize = os.TotalVirtualMemorySize; output.OsFreeVirtualMemory = os.FreeVirtualMemory; - if (os.TotalVirtualMemorySize != null && os.FreeVirtualMemory != null) + if (os.TotalVirtualMemorySize is not null && os.FreeVirtualMemory is not null) output.OsInUseVirtualMemory = os.TotalVirtualMemorySize - os.FreeVirtualMemory; output.OsInstallDate = os.InstallDate; output.OsLastBootUpTime = os.LastBootUpTime; @@ -758,7 +758,7 @@ private static ComputerInfo CreateFullOutputObject(SystemInfoGroup systemInfo, O output.OsHotFixes = osInfo.hotFixes; var pageFileUsage = osInfo.pageFileUsage; - if (pageFileUsage != null) + if (pageFileUsage is not null) { output.OsPagingFiles = new string[pageFileUsage.Length]; @@ -768,7 +768,7 @@ private static ComputerInfo CreateFullOutputObject(SystemInfoGroup systemInfo, O } var bios = systemInfo.bios; - if (bios != null) + if (bios is not null) { output.BiosCharacteristics = bios.BiosCharacteristics; output.BiosBuildNumber = bios.BuildNumber; @@ -801,12 +801,12 @@ private static ComputerInfo CreateFullOutputObject(SystemInfoGroup systemInfo, O output.BiosTargetOperatingSystem = bios.TargetOperatingSystem; output.BiosVersion = bios.Version; - if (otherInfo != null) + if (otherInfo is not null) output.BiosFirmwareType = otherInfo.firmwareType; } var computer = systemInfo.computer; - if (computer != null) + if (computer is not null) { output.CsAdminPasswordStatus = EnumConverter.Convert(computer.AdminPasswordStatus); output.CsAutomaticManagedPagefile = computer.AutomaticManagedPagefile; @@ -869,13 +869,13 @@ private static ComputerInfo CreateFullOutputObject(SystemInfoGroup systemInfo, O output.CsWakeUpType = EnumConverter.Convert(computer.WakeUpType); output.CsWorkgroup = computer.Workgroup; - if (otherInfo != null) + if (otherInfo is not null) { output.CsPhysicallyInstalledMemory = otherInfo.physicallyInstalledMemory; } } - if (otherInfo != null) + if (otherInfo is not null) { output.TimeZone = otherInfo.timeZone; output.LogonServer = otherInfo.logonServer; @@ -892,7 +892,7 @@ private static ComputerInfo CreateFullOutputObject(SystemInfoGroup systemInfo, O output.KeyboardLayout = Conversion.GetLocaleName(layout); } - if (otherInfo.hyperV != null) + if (otherInfo.hyperV is not null) { output.HyperVisorPresent = otherInfo.hyperV.Present; output.HyperVRequirementDataExecutionPreventionAvailable = otherInfo.hyperV.DataExecutionPreventionAvailable; @@ -904,12 +904,12 @@ private static ComputerInfo CreateFullOutputObject(SystemInfoGroup systemInfo, O output.OsServerLevel = otherInfo.serverLevel; var deviceGuardInfo = otherInfo.deviceGuard; - if (deviceGuardInfo != null) + if (deviceGuardInfo is not null) { output.DeviceGuardSmartStatus = deviceGuardInfo.status; var deviceGuard = deviceGuardInfo.deviceGuard; - if (deviceGuard != null) + if (deviceGuard is not null) { output.DeviceGuardRequiredSecurityProperties = deviceGuard.RequiredSecurityProperties; output.DeviceGuardAvailableSecurityProperties = deviceGuard.AvailableSecurityProperties; @@ -942,7 +942,7 @@ private static PSObject CreateCustomOutputObject(ComputerInfo info, List { var rv = new PSObject(); - if (info != null && namedProperties != null && namedProperties.Count > 0) + if (info is not null && namedProperties is not null && namedProperties.Count > 0) { // Walk the list of named properties, find a matching property in the // info object, and create a new property on the results object @@ -953,7 +953,7 @@ private static PSObject CreateCustomOutputObject(ComputerInfo info, List { var propInfo = type.GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance); - if (propInfo != null) + if (propInfo is not null) { object value = propInfo.GetValue(info); rv.Properties.Add(new PSNoteProperty(propertyName, value)); @@ -1049,7 +1049,7 @@ private static List CollectPropertyNames(string[] requestedProperties) var propertyName = availableProperties.Find(pred); // add the properly-cased name, if found, to the list - if (propertyName != null && !rv.Contains(propertyName)) + if (propertyName is not null && !rv.Contains(propertyName)) rv.Add(propertyName); } } @@ -1117,7 +1117,7 @@ internal static string GetLocaleName(string locale) { CultureInfo culture = null; - if (locale != null) + if (locale is not null) { try { @@ -1239,7 +1239,7 @@ public static Dictionary GetServerLevels() using (var key = Registry.LocalMachine.OpenSubKey(keyPath)) { - if (key != null) + if (key is not null) { foreach (var name in key.GetValueNames()) { @@ -1262,7 +1262,7 @@ public static string GetLogonServer() using (var key = Registry.CurrentUser.OpenSubKey(keyPath)) { - if (key != null) + if (key is not null) return (string)key.GetValue(valueName, null); } @@ -1273,7 +1273,7 @@ public static RegWinNtCurrentVersion GetWinNtCurrentVersion() { using (var key = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows NT\CurrentVersion")) { - if (key != null) + if (key is not null) { object temp = key.GetValue("InstallDate"); @@ -1321,7 +1321,7 @@ internal abstract class WmiClassBase /// protected static string GetLanguageName(uint? lcid) { - if (lcid != null && lcid >= 0) + if (lcid is not null && lcid >= 0) { try { @@ -1468,7 +1468,7 @@ internal class WmiComputerSystem public PowerManagementCapabilities[] GetPowerManagementCapabilities() { - if (PowerManagementCapabilities != null) + if (PowerManagementCapabilities is not null) { var list = new List(); @@ -1476,7 +1476,7 @@ public PowerManagementCapabilities[] GetPowerManagementCapabilities() { var val = EnumConverter.Convert(cap); - if (val != null) + if (val is not null) list.Add(val.Value); } @@ -1505,14 +1505,14 @@ public DeviceGuard AsOutputType var guard = new DeviceGuard(); var status = EnumConverter.Convert((int?)VirtualizationBasedSecurityStatus); - if (status != null && status != DeviceGuardSmartStatus.Off) + if (status is not null && status != DeviceGuardSmartStatus.Off) { var listHardware = new List(); for (int i = 0; i < RequiredSecurityProperties.Length; i++) { var temp = EnumConverter.Convert((int?)RequiredSecurityProperties[i]); - if (temp != null) + if (temp is not null) listHardware.Add(temp.Value); } @@ -1523,7 +1523,7 @@ public DeviceGuard AsOutputType { var temp = EnumConverter.Convert((int?)AvailableSecurityProperties[i]); - if (temp != null) + if (temp is not null) listHardware.Add(temp.Value); } @@ -1534,7 +1534,7 @@ public DeviceGuard AsOutputType { var temp = EnumConverter.Convert((int?)SecurityServicesConfigured[i]); - if (temp != null) + if (temp is not null) listSoftware.Add(temp.Value); } @@ -1545,7 +1545,7 @@ public DeviceGuard AsOutputType { var temp = EnumConverter.Convert((int?)SecurityServicesRunning[i]); - if (temp != null) + if (temp is not null) listSoftware.Add(temp.Value); } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetContentCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetContentCommand.cs index 86f252fb8fc..3da704f48de 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetContentCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetContentCommand.cs @@ -85,7 +85,7 @@ public int Tail /// internal override object GetDynamicParameters(CmdletProviderContext context) { - if (Path != null && Path.Length > 0) + if (Path is not null && Path.Length > 0) { return InvokeProvider.Content.GetContentReaderDynamicParameters(Path[0], context); } @@ -139,7 +139,7 @@ protected override void ProcessRecord() long countRead = 0; Dbg.Diagnostics.Assert( - holder.Reader != null, + holder.Reader is not null, "All holders should have a reader assigned"); if (_tailSpecified && !(holder.Reader is FileSystemContentReaderWriter)) @@ -239,7 +239,7 @@ protected override void ProcessRecord() break; } - if (results != null && results.Count > 0) + if (results is not null && results.Count > 0) { countRead += results.Count; if (ReadCount == 1) @@ -253,7 +253,7 @@ protected override void ProcessRecord() WriteContentObject(results, countRead, holder.PathInfo, currentContext); } } - } while (results != null && results.Count > 0 && ((TotalCount < 0) || countRead < TotalCount)); + } while (results is not null && results.Count > 0 && ((TotalCount < 0) || countRead < TotalCount)); } } } @@ -280,7 +280,7 @@ protected override void ProcessRecord() private bool ScanForwardsForTail(ContentHolder holder, CmdletProviderContext currentContext) { var fsReader = holder.Reader as FileSystemContentReaderWriter; - Dbg.Diagnostics.Assert(fsReader != null, "Tail is only supported for FileSystemContentReaderWriter"); + Dbg.Diagnostics.Assert(fsReader is not null, "Tail is only supported for FileSystemContentReaderWriter"); var tailResultQueue = new Queue(); IList results = null; ErrorRecord error = null; @@ -319,7 +319,7 @@ private bool ScanForwardsForTail(ContentHolder holder, CmdletProviderContext cur break; } - if (results != null && results.Count > 0) + if (results is not null && results.Count > 0) { foreach (object entry in results) { @@ -328,7 +328,7 @@ private bool ScanForwardsForTail(ContentHolder holder, CmdletProviderContext cur tailResultQueue.Enqueue(entry); } } - } while (results != null && results.Count > 0); + } while (results is not null && results.Count > 0); if (tailResultQueue.Count > 0) { @@ -368,7 +368,7 @@ private bool ScanForwardsForTail(ContentHolder holder, CmdletProviderContext cur } } - if (error != null) + if (error is not null) { WriteError(error); return false; @@ -390,7 +390,7 @@ private bool ScanForwardsForTail(ContentHolder holder, CmdletProviderContext cur private bool SeekPositionForTail(IContentReader reader) { var fsReader = reader as FileSystemContentReaderWriter; - Dbg.Diagnostics.Assert(fsReader != null, "Tail is only supported for FileSystemContentReaderWriter"); + Dbg.Diagnostics.Assert(fsReader is not null, "Tail is only supported for FileSystemContentReaderWriter"); try { diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetPropertyCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetPropertyCommand.cs index 826bfb5d406..70c62059427 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetPropertyCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetPropertyCommand.cs @@ -87,7 +87,7 @@ public string[] Name /// internal override object GetDynamicParameters(CmdletProviderContext context) { - if (Path != null && Path.Length > 0) + if (Path is not null && Path.Length > 0) { return InvokeProvider.Property.GetPropertyDynamicParameters( Path[0], @@ -244,7 +244,7 @@ public string[] Name /// internal override object GetDynamicParameters(CmdletProviderContext context) { - if (Path != null && Path.Length > 0) + if (Path is not null && Path.Length > 0) { return InvokeProvider.Property.GetPropertyDynamicParameters( Path[0], @@ -288,17 +288,17 @@ protected override void ProcessRecord() SessionStateUtilities.ConvertArrayToCollection(_property), base.SuppressWildcardExpansion); - if (itemProperties != null) + if (itemProperties is not null) { foreach (PSObject currentItem in itemProperties) { - if (this.Name != null) + if (this.Name is not null) { foreach (string currentPropertyName in this.Name) { - if (currentItem.Properties != null && - currentItem.Properties[currentPropertyName] != null && - currentItem.Properties[currentPropertyName].Value != null) + if (currentItem.Properties is not null && + currentItem.Properties[currentPropertyName] is not null && + currentItem.Properties[currentPropertyName].Value is not null) { CmdletProviderContext.WriteObject(currentItem.Properties[currentPropertyName].Value); } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetWMIObjectCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetWMIObjectCommand.cs index f460b2c4957..fdefa8f0af1 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetWMIObjectCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetWMIObjectCommand.cs @@ -424,7 +424,7 @@ private string GetClassNameFromQuery(string query) System.Management.Automation.Diagnostics.Assert(query.Contains("from"), "Only get called when ErrorCode is InvalidClass, which means the query string contains 'from' and the class name"); - if (Class != null) + if (Class is not null) { return Class; } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Hotfix.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Hotfix.cs index c0404fa133c..00db7ae6de6 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Hotfix.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Hotfix.cs @@ -90,7 +90,7 @@ protected override void ProcessRecord() StringBuilder queryString = new StringBuilder(); ManagementScope scope = new ManagementScope(ComputerWMIHelper.GetScopeString(computer, ComputerWMIHelper.WMI_Path_CIM), _connectionOptions); scope.Connect(); - if (Id != null) + if (Id is not null) { queryString.Append("Select * from Win32_QuickFixEngineering where ("); for (int i = 0; i <= Id.Length - 1; i++) @@ -115,7 +115,7 @@ protected override void ProcessRecord() _searchProcess = new ManagementObjectSearcher(scope, new ObjectQuery(queryString.ToString())); foreach (ManagementObject obj in _searchProcess.Get()) { - if (Description != null) + if (Description is not null) { if (!FilterMatch(obj)) { @@ -157,7 +157,7 @@ protected override void ProcessRecord() WriteError(new ErrorRecord(ex, "GetHotFixNoEntriesFound", ErrorCategory.ObjectNotFound, null)); } - if (_searchProcess != null) + if (_searchProcess is not null) { this.Dispose(); } @@ -169,7 +169,7 @@ protected override void ProcessRecord() /// protected override void StopProcessing() { - if (_searchProcess != null) + if (_searchProcess is not null) { _searchProcess.Dispose(); } @@ -227,7 +227,7 @@ public void Dispose(bool disposing) { if (disposing) { - if (_searchProcess != null) + if (_searchProcess is not null) { _searchProcess.Dispose(); } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/InvokeWMIMethodCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/InvokeWMIMethodCommand.cs index df0c5775ca1..ddba6ae6512 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/InvokeWMIMethodCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/InvokeWMIMethodCommand.cs @@ -100,14 +100,14 @@ protected override void ProcessRecord() return; } - if (_inputObject != null) + if (_inputObject is not null) { object result = null; ManagementBaseObject inputParameters = null; try { inputParameters = _inputObject.GetMethodParameters(_methodName); - if (_argumentList != null) + if (_argumentList is not null) { int inParamCount = _argumentList.Length; foreach (PropertyData property in inputParameters.Properties) @@ -141,7 +141,7 @@ protected override void ProcessRecord() WriteError(errorRecord); } - if (result != null) + if (result is not null) { WriteObject(result); } @@ -154,7 +154,7 @@ protected override void ProcessRecord() ManagementPath mPath = null; object result = null; ManagementObject mObject = null; - if (_path != null) + if (_path is not null) { mPath = new ManagementPath(_path); if (string.IsNullOrEmpty(mPath.NamespacePath)) @@ -193,7 +193,7 @@ protected override void ProcessRecord() result = null; try { - if (_path != null) + if (_path is not null) { mPath.Server = name; if (mPath.IsClass) @@ -219,7 +219,7 @@ protected override void ProcessRecord() } ManagementBaseObject inputParameters = mObject.GetMethodParameters(_methodName); - if (_argumentList != null) + if (_argumentList is not null) { int inParamCount = _argumentList.Length; foreach (PropertyData property in inputParameters.Properties) @@ -262,7 +262,7 @@ protected override void ProcessRecord() WriteError(errorRecord); } - if (result != null) + if (result is not null) { WriteObject(result); } @@ -302,7 +302,7 @@ private static object MakeBaseObjectArray(object argument) int index = 0; foreach (object argElement in listArgument) { - copiedArgument[index++] = argElement != null ? PSObject.Base(argElement) : null; + copiedArgument[index++] = argElement is not null ? PSObject.Base(argElement) : null; } return copiedArgument; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/MovePropertyCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/MovePropertyCommand.cs index eb4f9f8dc7d..8f054af8802 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/MovePropertyCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/MovePropertyCommand.cs @@ -87,12 +87,12 @@ public string[] Name internal override object GetDynamicParameters(CmdletProviderContext context) { string propertyName = string.Empty; - if (Name != null && Name.Length > 0) + if (Name is not null && Name.Length > 0) { propertyName = Name[0]; } - if (Path != null && Path.Length > 0) + if (Path is not null && Path.Length > 0) { return InvokeProvider.Property.MovePropertyDynamicParameters(Path[0], propertyName, Destination, propertyName, context); } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs index 1edb5c5f239..55a2168656e 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs @@ -107,7 +107,7 @@ protected bool DoesProviderSupportShouldProcess(string[] paths) // may be getting piped in. bool result = true; - if (paths != null && paths.Length >= 0) + if (paths is not null && paths.Length >= 0) { foreach (string path in paths) { @@ -435,7 +435,7 @@ protected override void ProcessRecord() case LocationParameterSet: PathInfo result = null; - if (PSDrive != null && PSDrive.Length > 0) + if (PSDrive is not null && PSDrive.Length > 0) { foreach (string drive in PSDrive) { @@ -506,7 +506,7 @@ protected override void ProcessRecord() } // If the drive wasn't specified but the provider was else if ((PSDrive is null || PSDrive.Length == 0) && - (PSProvider != null && PSProvider.Length > 0)) + (PSProvider is not null && PSProvider.Length > 0)) { foreach (string providerName in PSProvider) { @@ -581,7 +581,7 @@ protected override void ProcessRecord() break; case StackParameterSet: - if (_stackNames != null) + if (_stackNames is not null) { foreach (string stackName in _stackNames) { @@ -792,7 +792,7 @@ protected override void ProcessRecord() break; } - if (_passThrough && result != null) + if (_passThrough && result is not null) { WriteObject(result); } @@ -900,7 +900,7 @@ protected override void ProcessRecord() // working directory stack SessionState.Path.PushCurrentLocation(_stackName); - if (Path != null) + if (Path is not null) { try { @@ -1216,7 +1216,7 @@ protected override void ProcessRecord() } // Check to see if the provider exists - if (provider != null) + if (provider is not null) { // Get the confirmation strings @@ -1452,7 +1452,7 @@ internal List GetMatchingDrives( } else { - if (nameMatcher != null && nameMatcher.IsMatch(drive.Name)) + if (nameMatcher is not null && nameMatcher.IsMatch(drive.Name)) addDrive = true; } @@ -1937,7 +1937,7 @@ public override SwitchParameter Force /// internal override object GetDynamicParameters(CmdletProviderContext context) { - if (Path != null && Path.Length > 0) + if (Path is not null && Path.Length > 0) { return InvokeProvider.Item.GetItemDynamicParameters(Path[0], context); } @@ -2078,7 +2078,7 @@ public override SwitchParameter Force /// internal override object GetDynamicParameters(CmdletProviderContext context) { - if (Path != null && Path.Length > 0) + if (Path is not null && Path.Length > 0) { // Path is only globbed if Name is specified. if (string.IsNullOrEmpty(Name)) @@ -2275,7 +2275,7 @@ public override string[] Exclude /// internal override object GetDynamicParameters(CmdletProviderContext context) { - if (Path != null && Path.Length > 0) + if (Path is not null && Path.Length > 0) { return InvokeProvider.Item.SetItemDynamicParameters(Path[0], Value, context); } @@ -2470,7 +2470,7 @@ public override SwitchParameter Force /// internal override object GetDynamicParameters(CmdletProviderContext context) { - if (Path != null && Path.Length > 0) + if (Path is not null && Path.Length > 0) { return InvokeProvider.Item.RemoveItemDynamicParameters(Path[0], Recurse, context); } @@ -2701,7 +2701,7 @@ protected override void ProcessRecord() try { System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(providerPath); - if (di != null && (di.Attributes & System.IO.FileAttributes.ReparsePoint) != 0) + if (di is not null && (di.Attributes & System.IO.FileAttributes.ReparsePoint) != 0) { shouldRecurse = false; treatAsFile = true; @@ -2906,7 +2906,7 @@ public SwitchParameter PassThru /// internal override object GetDynamicParameters(CmdletProviderContext context) { - if (Path != null && Path.Length > 0) + if (Path is not null && Path.Length > 0) { return InvokeProvider.Item.MoveItemDynamicParameters(Path[0], Destination, context); } @@ -3658,7 +3658,7 @@ public SwitchParameter PassThru /// internal override object GetDynamicParameters(CmdletProviderContext context) { - if (Path != null && Path.Length > 0) + if (Path is not null && Path.Length > 0) { return InvokeProvider.Item.CopyItemDynamicParameters(Path[0], Destination, Recurse, context); } @@ -3864,7 +3864,7 @@ public override string[] Exclude /// internal override object GetDynamicParameters(CmdletProviderContext context) { - if (Path != null && Path.Length > 0) + if (Path is not null && Path.Length > 0) { return InvokeProvider.Item.ClearItemDynamicParameters(Path[0], context); } @@ -4034,7 +4034,7 @@ public override string[] Exclude /// internal override object GetDynamicParameters(CmdletProviderContext context) { - if (Path != null && Path.Length > 0) + if (Path is not null && Path.Length > 0) { return InvokeProvider.Item.InvokeItemDynamicParameters(Path[0], context); } @@ -4170,7 +4170,7 @@ protected override void ProcessRecord() { PSSnapinQualifiedName pssnapinQualifiedProvider = PSSnapinQualifiedName.GetInstance(requestedProvider); - if (pssnapinQualifiedProvider != null && WildcardPattern.ContainsWildcardCharacters(pssnapinQualifiedProvider.ShortName)) + if (pssnapinQualifiedProvider is not null && WildcardPattern.ContainsWildcardCharacters(pssnapinQualifiedProvider.ShortName)) { // The user entered a glob string so use the WildcardPattern to // compare the glob string to the provider names that exist @@ -4184,7 +4184,7 @@ protected override void ProcessRecord() foreach (ProviderInfo enumeratedProvider in SessionState.Provider.GetAll()) { Dbg.Diagnostics.Assert( - enumeratedProvider != null, + enumeratedProvider is not null, "SessionState.Providers should return only ProviderInfo objects"); if (enumeratedProvider.IsMatch(matcher, pssnapinQualifiedProvider)) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/NewPropertyCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/NewPropertyCommand.cs index e3982d49034..bf02dd7e8aa 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/NewPropertyCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/NewPropertyCommand.cs @@ -113,7 +113,7 @@ public override SwitchParameter Force /// internal override object GetDynamicParameters(CmdletProviderContext context) { - if (Path != null && Path.Length > 0) + if (Path is not null && Path.Length > 0) { return InvokeProvider.Property.NewPropertyDynamicParameters(Path[0], Name, PropertyType, Value, context); } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ParsePathCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ParsePathCommand.cs index a1dd7895fc1..b80e05477e4 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ParsePathCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ParsePathCommand.cs @@ -422,7 +422,7 @@ protected override void ProcessRecord() break; } - if (result != null) + if (result is not null) { WriteObject(result); } @@ -442,7 +442,7 @@ protected override void ProcessRecord() private string RemoveQualifier(string path) { Dbg.Diagnostics.Assert( - path != null, + path is not null, "Path should be verified by the caller"); string result = path; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/PingPathCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/PingPathCommand.cs index caf9b407252..e177fb26c9f 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/PingPathCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/PingPathCommand.cs @@ -137,7 +137,7 @@ internal override object GetDynamicParameters(CmdletProviderContext context) if (this.PathType == TestPathType.Any && !IsValid) { - if (Path != null && Path.Length > 0 && Path[0] != null) + if (Path is not null && Path.Length > 0 && Path[0] is not null) { result = InvokeProvider.Item.ItemExistsDynamicParameters(Path[0], context); } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs index 888c6026c76..fc41fc5e3d4 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs @@ -665,7 +665,7 @@ protected override void ProcessRecord() try { ProcessModule mainModule = PsUtils.GetMainModule(process); - if (mainModule != null) + if (mainModule is not null) { WriteObject(mainModule.FileVersionInfo, true); } @@ -926,7 +926,7 @@ public void Dispose() { if (_disposed == false) { - if (_waitHandle != null) + if (_waitHandle is not null) { _waitHandle.Dispose(); _waitHandle = null; @@ -944,7 +944,7 @@ private void myProcess_Exited(object sender, System.EventArgs e) { if (0 == System.Threading.Interlocked.Decrement(ref _numberOfProcessesToWaitFor)) { - if (_waitHandle != null) + if (_waitHandle is not null) { _waitHandle.Set(); } @@ -1048,7 +1048,7 @@ protected override void EndProcessing() /// protected override void StopProcessing() { - if (_waitHandle != null) + if (_waitHandle is not null) { _waitHandle.Set(); } @@ -1412,7 +1412,7 @@ private void StopProcess(Process process) exception = e; } - if (exception != null) + if (exception is not null) { if (!TryHasExited(process)) { @@ -1874,12 +1874,12 @@ protected override void BeginProcessing() #endif } - if (ArgumentList != null) + if (ArgumentList is not null) { startInfo.Arguments = string.Join(' ', ArgumentList); } - if (WorkingDirectory != null) + if (WorkingDirectory is not null) { // WorkingDirectory -> Not Exist -> Throw Error WorkingDirectory = ResolveFilePath(WorkingDirectory); @@ -1922,7 +1922,7 @@ protected override void BeginProcessing() #if !UNIX startInfo.LoadUserProfile = _loaduserprofile; #endif - if (_credential != null) + if (_credential is not null) { NetworkCredential nwcredential = _credential.GetNetworkCredential(); startInfo.UserName = nwcredential.UserName; @@ -1939,7 +1939,7 @@ protected override void BeginProcessing() } // RedirectionInput File Check -> Not Exist -> Throw Error - if (_redirectstandardinput != null) + if (_redirectstandardinput is not null) { _redirectstandardinput = ResolveFilePath(_redirectstandardinput); if (!File.Exists(_redirectstandardinput)) @@ -1952,7 +1952,7 @@ protected override void BeginProcessing() } // RedirectionInput == RedirectionOutput -> Throw Error - if (_redirectstandardinput != null && _redirectstandardoutput != null) + if (_redirectstandardinput is not null && _redirectstandardoutput is not null) { _redirectstandardinput = ResolveFilePath(_redirectstandardinput); _redirectstandardoutput = ResolveFilePath(_redirectstandardoutput); @@ -1966,7 +1966,7 @@ protected override void BeginProcessing() } // RedirectionInput == RedirectionError -> Throw Error - if (_redirectstandardinput != null && _redirectstandarderror != null) + if (_redirectstandardinput is not null && _redirectstandarderror is not null) { _redirectstandardinput = ResolveFilePath(_redirectstandardinput); _redirectstandarderror = ResolveFilePath(_redirectstandarderror); @@ -1980,7 +1980,7 @@ protected override void BeginProcessing() } // RedirectionOutput == RedirectionError -> Throw Error - if (_redirectstandardoutput != null && _redirectstandarderror != null) + if (_redirectstandardoutput is not null && _redirectstandarderror is not null) { _redirectstandarderror = ResolveFilePath(_redirectstandarderror); _redirectstandardoutput = ResolveFilePath(_redirectstandardoutput); @@ -1995,7 +1995,7 @@ protected override void BeginProcessing() } else if (ParameterSetName.Equals("UseShellExecute")) { - if (Verb != null) { startInfo.Verb = Verb; } + if (Verb is not null) { startInfo.Verb = Verb; } startInfo.WindowStyle = _windowstyle; } @@ -2007,7 +2007,7 @@ protected override void BeginProcessing() if (PassThru.IsPresent) { - if (process != null) + if (process is not null) { WriteObject(process); } @@ -2021,7 +2021,7 @@ protected override void BeginProcessing() if (Wait.IsPresent) { - if (process != null) + if (process is not null) { if (!process.HasExited) { @@ -2060,7 +2060,7 @@ protected override void BeginProcessing() /// protected override void StopProcessing() { - if (_waithandle != null) + if (_waithandle is not null) { _waithandle.Set(); } @@ -2081,7 +2081,7 @@ public void Dispose() private void Dispose(bool isDisposing) { - if (_waithandle != null) + if (_waithandle is not null) { _waithandle.Dispose(); _waithandle = null; @@ -2097,7 +2097,7 @@ private void Dispose(bool isDisposing) /// private void myProcess_Exited(object sender, System.EventArgs e) { - if (_waithandle != null) + if (_waithandle is not null) { _waithandle.Set(); } @@ -2200,12 +2200,12 @@ private void StreamClosing() { Thread.Sleep(1000); - if (_outputWriter != null) + if (_outputWriter is not null) { _outputWriter.Dispose(); } - if (_errorWriter != null) + if (_errorWriter is not null) { _errorWriter.Dispose(); } @@ -2213,7 +2213,7 @@ private void StreamClosing() private void SetupInputOutputRedirection(Process p) { - if (_redirectstandardinput != null) + if (_redirectstandardinput is not null) { p.StartInfo.RedirectStandardInput = true; _redirectstandardinput = ResolveFilePath(_redirectstandardinput); @@ -2223,7 +2223,7 @@ private void SetupInputOutputRedirection(Process p) p.StartInfo.RedirectStandardInput = false; } - if (_redirectstandardoutput != null) + if (_redirectstandardoutput is not null) { p.StartInfo.RedirectStandardOutput = true; _redirectstandardoutput = ResolveFilePath(_redirectstandardoutput); @@ -2238,7 +2238,7 @@ private void SetupInputOutputRedirection(Process p) _outputWriter = null; } - if (_redirectstandarderror != null) + if (_redirectstandarderror is not null) { p.StartInfo.RedirectStandardError = true; _redirectstandarderror = ResolveFilePath(_redirectstandarderror); @@ -2351,7 +2351,7 @@ private static byte[] ConvertEnvVarsToByteArray(StringDictionary sd) private void SetStartupInfo(ProcessStartInfo startinfo, ref ProcessNativeMethods.STARTUPINFO lpStartupInfo, ref int creationFlags) { // RedirectionStandardInput - if (_redirectstandardinput != null) + if (_redirectstandardinput is not null) { startinfo.RedirectStandardInput = true; _redirectstandardinput = ResolveFilePath(_redirectstandardinput); @@ -2363,7 +2363,7 @@ private void SetStartupInfo(ProcessStartInfo startinfo, ref ProcessNativeMethods } // RedirectionStandardOutput - if (_redirectstandardoutput != null) + if (_redirectstandardoutput is not null) { startinfo.RedirectStandardOutput = true; _redirectstandardoutput = ResolveFilePath(_redirectstandardoutput); @@ -2375,7 +2375,7 @@ private void SetStartupInfo(ProcessStartInfo startinfo, ref ProcessNativeMethods } // RedirectionStandardError - if (_redirectstandarderror != null) + if (_redirectstandarderror is not null) { startinfo.RedirectStandardError = true; _redirectstandarderror = ResolveFilePath(_redirectstandarderror); @@ -2456,7 +2456,7 @@ private Process StartWithCreateProcess(ProcessStartInfo startinfo) if (!UseNewEnvironment) { var environmentVars = startinfo.EnvironmentVariables; - if (environmentVars != null) + if (environmentVars is not null) { // All Windows Operating Systems that we support are Windows NT systems, so we use Unicode for environment. creationFlags |= 0x400; @@ -2468,7 +2468,7 @@ private Process StartWithCreateProcess(ProcessStartInfo startinfo) bool flag; - if (_credential != null) + if (_credential is not null) { // Run process as another user. ProcessNativeMethods.LogonFlags logonFlags = 0; @@ -2847,19 +2847,19 @@ public void Dispose(bool disposing) { if (disposing) { - if ((this.hStdInput != null) && !this.hStdInput.IsInvalid) + if ((this.hStdInput is not null) && !this.hStdInput.IsInvalid) { this.hStdInput.Dispose(); this.hStdInput = null; } - if ((this.hStdOutput != null) && !this.hStdOutput.IsInvalid) + if ((this.hStdOutput is not null) && !this.hStdOutput.IsInvalid) { this.hStdOutput.Dispose(); this.hStdOutput = null; } - if ((this.hStdError != null) && !this.hStdError.IsInvalid) + if ((this.hStdError is not null) && !this.hStdError.IsInvalid) { this.hStdError.Dispose(); this.hStdError = null; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/RegisterWMIEventCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/RegisterWMIEventCommand.cs index 0a4d9c6cb34..acb792cfc5c 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/RegisterWMIEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/RegisterWMIEventCommand.cs @@ -103,7 +103,7 @@ private string GetScopeString(string computer, string namespaceParameter) protected override object GetSourceObject() { string wmiQuery = this.Query; - if (this.Class != null) + if (this.Class is not null) { // Validate class format for (int i = 0; i < this.Class.Length; i++) @@ -131,7 +131,7 @@ protected override object GetSourceObject() } ConnectionOptions conOptions = new ConnectionOptions(); - if (this.Credential != null) + if (this.Credential is not null) { System.Net.NetworkCredential cred = this.Credential.GetNetworkCredential(); if (string.IsNullOrEmpty(cred.Domain)) @@ -176,7 +176,7 @@ protected override void EndProcessing() // Register for the "Unsubscribed" event so that we can stop the // event watcher. PSEventSubscriber newSubscriber = NewSubscriber; - if (newSubscriber != null) + if (newSubscriber is not null) { newSubscriber.Unsubscribed += new PSEventUnsubscribedEventHandler(newSubscriber_Unsubscribed); } @@ -185,7 +185,7 @@ protected override void EndProcessing() private void newSubscriber_Unsubscribed(object sender, PSEventUnsubscribedEventArgs e) { ManagementEventWatcher watcher = sender as ManagementEventWatcher; - if (watcher != null) + if (watcher is not null) { watcher.Stop(); } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/RemovePropertyCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/RemovePropertyCommand.cs index 1f02a4fc6d1..93e6f43697a 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/RemovePropertyCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/RemovePropertyCommand.cs @@ -102,12 +102,12 @@ public override SwitchParameter Force internal override object GetDynamicParameters(CmdletProviderContext context) { string propertyName = null; - if (Name != null && Name.Length > 0) + if (Name is not null && Name.Length > 0) { propertyName = Name[0]; } - if (Path != null && Path.Length > 0) + if (Path is not null && Path.Length > 0) { return InvokeProvider.Property.RemovePropertyDynamicParameters(Path[0], propertyName, context); } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/RemoveWMIObjectCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/RemoveWMIObjectCommand.cs index cce50ea1563..b693e1366fc 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/RemoveWMIObjectCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/RemoveWMIObjectCommand.cs @@ -66,7 +66,7 @@ protected override void ProcessRecord() return; } - if (_inputObject != null) + if (_inputObject is not null) { try { @@ -95,7 +95,7 @@ protected override void ProcessRecord() ConnectionOptions options = GetConnectionOption(); ManagementPath mPath = null; ManagementObject mObject = null; - if (_path != null) + if (_path is not null) { mPath = new ManagementPath(_path); if (string.IsNullOrEmpty(mPath.NamespacePath)) @@ -133,7 +133,7 @@ protected override void ProcessRecord() { try { - if (_path != null) + if (_path is not null) { mPath.Server = name; if (mPath.IsClass) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/RenamePropertyCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/RenamePropertyCommand.cs index 3bed667fb0f..85feeea7ceb 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/RenamePropertyCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/RenamePropertyCommand.cs @@ -81,7 +81,7 @@ public string LiteralPath /// internal override object GetDynamicParameters(CmdletProviderContext context) { - if (Path != null) + if (Path is not null) { return InvokeProvider.Property.RenamePropertyDynamicParameters(Path, Name, NewName, context); } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ResolvePathCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ResolvePathCommand.cs index 8fa26142c5b..7e8ba47ba7a 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ResolvePathCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ResolvePathCommand.cs @@ -110,7 +110,7 @@ protected override void ProcessRecord() // When result path and base path is on different PSDrive // (../)*path should not go beyond the root of base path if (currentPath.Drive != SessionState.Path.CurrentLocation.Drive && - SessionState.Path.CurrentLocation.Drive != null && + SessionState.Path.CurrentLocation.Drive is not null && !currentPath.ProviderPath.StartsWith( SessionState.Path.CurrentLocation.Drive.Root, StringComparison.OrdinalIgnoreCase)) { diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs index 31fe60f93da..e5edb5ede4a 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs @@ -411,7 +411,7 @@ private List MatchingServicesByServiceName() else { ServiceController service = GetOneService(pattern); - if (service != null) + if (service is not null) { found = true; IncludeExcludeAdd(matchingServices, service, true); @@ -517,9 +517,9 @@ private void IncludeExcludeAdd( ServiceController service, bool checkDuplicates) { - if (include != null && !Matches(service, include)) + if (include is not null && !Matches(service, include)) return; - if (exclude != null && Matches(service, exclude)) + if (exclude is not null && Matches(service, exclude)) return; if (checkDuplicates) { @@ -921,7 +921,7 @@ internal bool DoStartService(ServiceController serviceController) } } - if (exception != null) + if (exception is not null) { // This service refused to accept the start command, // so write a non-terminating error. @@ -985,7 +985,7 @@ internal List DoStopService(ServiceController serviceControll if (!force) { - if ((dependentServices != null) + if ((dependentServices is not null) && (dependentServices.Length > 0)) { // Check if all dependent services are stopped @@ -1005,7 +1005,7 @@ internal List DoStopService(ServiceController serviceControll } } - if (dependentServices != null) + if (dependentServices is not null) { foreach (ServiceController service in dependentServices) { @@ -1039,7 +1039,7 @@ internal List DoStopService(ServiceController serviceControll } } - if (exception != null) + if (exception is not null) { // This service refused to accept the stop command, // so write a non-terminating error. @@ -1128,7 +1128,7 @@ internal bool DoPauseService(ServiceController serviceController) catch (InvalidOperationException e) { Win32Exception eInner = e.InnerException as Win32Exception; - if (eInner != null + if (eInner is not null && NativeMethods.ERROR_SERVICE_NOT_ACTIVE == eInner.NativeErrorCode) { serviceNotRunning = true; @@ -1137,7 +1137,7 @@ internal bool DoPauseService(ServiceController serviceController) exception = e; } - if (exception != null) + if (exception is not null) { // This service refused to accept the pause command, // so write a non-terminating error. @@ -1209,7 +1209,7 @@ internal bool DoResumeService(ServiceController serviceController) catch (InvalidOperationException e) { Win32Exception eInner = e.InnerException as Win32Exception; - if (eInner != null + if (eInner is not null && NativeMethods.ERROR_SERVICE_NOT_ACTIVE == eInner.NativeErrorCode) { serviceNotRunning = true; @@ -1218,7 +1218,7 @@ internal bool DoResumeService(ServiceController serviceController) exception = e; } - if (exception != null) + if (exception is not null) { // This service refused to accept the continue command, // so write a non-terminating error. @@ -1684,7 +1684,7 @@ protected override void ProcessRecord() try { - if (InputObject != null) + if (InputObject is not null) { service = InputObject; Name = service.ServiceName; @@ -1771,7 +1771,7 @@ protected override void ProcessRecord() } // Modify startup type or display name or credential if (!string.IsNullOrEmpty(DisplayName) - || ServiceStartupType.InvalidValue != StartupType || Credential != null) + || ServiceStartupType.InvalidValue != StartupType || Credential is not null) { DWORD dwStartType = NativeMethods.SERVICE_NO_CHANGE; if (!NativeMethods.TryGetNativeStartupType(StartupType, out dwStartType)) @@ -1784,7 +1784,7 @@ protected override void ProcessRecord() } string username = null; - if (Credential != null) + if (Credential is not null) { username = Credential.UserName; password = Marshal.SecureStringToCoTaskMemUnicode(Credential.Password); @@ -1888,7 +1888,7 @@ protected override void ProcessRecord() // Check for the dependent services as set-service dont have force parameter ServiceController[] dependentServices = service.DependentServices; - if ((!Force) && (dependentServices != null) && (dependentServices.Length > 0)) + if ((!Force) && (dependentServices is not null) && (dependentServices.Length > 0)) { WriteNonTerminatingError(service, null, "ServiceHasDependentServicesNoForce", ServiceResources.ServiceHasDependentServicesNoForce, ErrorCategory.InvalidOperation); return; @@ -2159,7 +2159,7 @@ protected override void BeginProcessing() } // set up the double-null-terminated lpDependencies parameter IntPtr lpDependencies = IntPtr.Zero; - if (DependsOn != null) + if (DependsOn is not null) { int numchars = 1; // final null foreach (string dependedOn in DependsOn) @@ -2189,7 +2189,7 @@ protected override void BeginProcessing() // set up the Credential parameter string username = null; - if (Credential != null) + if (Credential is not null) { username = Credential.UserName; password = Marshal.SecureStringToCoTaskMemUnicode(Credential.Password); @@ -2382,7 +2382,7 @@ protected override void ProcessRecord() bool objServiceShouldBeDisposed = false; try { - if (InputObject != null) + if (InputObject is not null) { service = InputObject; Name = service.ServiceName; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs index 29019bee06f..70391a3dd53 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs @@ -50,7 +50,7 @@ protected override void BeginProcessing() /// protected override void ProcessRecord() { - if (Value != null) + if (Value is not null) { _contentList.AddRange(Value); } @@ -90,13 +90,13 @@ private void SetClipboardContent(List contentList, bool append) content.AppendLine(Clipboard.GetText()); } - if (contentList != null) + if (contentList is not null) { content.Append(string.Join(Environment.NewLine, contentList.ToArray(), 0, contentList.Count)); } string verboseString = null; - if (contentList != null) + if (contentList is not null) { verboseString = contentList[0]; if (verboseString.Length >= 20) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetPropertyCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetPropertyCommand.cs index 9e2018342ba..c45660a0954 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetPropertyCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetPropertyCommand.cs @@ -134,7 +134,7 @@ internal override object GetDynamicParameters(CmdletProviderContext context) break; } - if (Path != null && Path.Length > 0) + if (Path is not null && Path.Length > 0) { return InvokeProvider.Property.SetPropertyDynamicParameters(Path[0], mshObject, context); } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetWMIInstanceCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetWMIInstanceCommand.cs index 4b2deac8bef..3efa976bf4d 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetWMIInstanceCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetWMIInstanceCommand.cs @@ -81,7 +81,7 @@ protected override void ProcessRecord() return; } - if (InputObject != null) + if (InputObject is not null) { object result = null; ManagementObject mObj = null; @@ -90,7 +90,7 @@ protected override void ProcessRecord() PutOptions pOptions = new PutOptions(); mObj = SetWmiInstanceGetPipelineObject(); pOptions.Type = _putType; - if (mObj != null) + if (mObj is not null) { if (!ShouldProcess(mObj.Path.Path.ToString())) { @@ -126,7 +126,7 @@ protected override void ProcessRecord() // If Class is specified only CreateOnly flag is supported mPath = this.SetWmiInstanceBuildManagementPath(); // If server name is specified loop through it. - if (mPath != null) + if (mPath is not null) { if (!(mPath.Server == "." && serverNameSpecified)) { @@ -146,7 +146,7 @@ protected override void ProcessRecord() mObject = this.SetWmiInstanceGetObject(mPath, name); PutOptions pOptions = new PutOptions(); pOptions.Type = _putType; - if (mObject != null) + if (mObject is not null) { if (!ShouldProcess(mObject.Path.Path.ToString())) { @@ -174,7 +174,7 @@ protected override void ProcessRecord() WriteError(errorRecord); } - if (result != null) + if (result is not null) { WriteObject(result); } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/TestConnectionCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/TestConnectionCommand.cs index c21d73e25b4..4d8cfb03d27 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/TestConnectionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/TestConnectionCommand.cs @@ -796,7 +796,7 @@ private IPHostEntry GetCancellableHostEntry(string targetNameOrAddress) // Creates and fills a send buffer. This follows the ping.exe and CoreFX model. private byte[] GetSendBuffer(int bufferSize) { - if (bufferSize == DefaultSendBufferSize && s_DefaultSendBuffer != null) + if (bufferSize == DefaultSendBufferSize && s_DefaultSendBuffer is not null) { return s_DefaultSendBuffer; } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/TimeZoneCommands.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/TimeZoneCommands.cs index 106c9038981..0021fd47324 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/TimeZoneCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/TimeZoneCommands.cs @@ -76,7 +76,7 @@ protected override void ProcessRecord() } else // ParameterSetName == "Name" { - if (Name != null) + if (Name is not null) { // lookup each time zone name (or wildcard pattern) foreach (string tzname in Name) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/UseTransactionCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/UseTransactionCommand.cs index 056cf60265b..0471f51bc8a 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/UseTransactionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/UseTransactionCommand.cs @@ -64,7 +64,7 @@ protected override void EndProcessing() // exceedingly obtuse. We clarify things here. bool isTimeoutException = false; Exception tempException = e; - while (tempException != null) + while (tempException is not null) { if (tempException is System.TimeoutException) { diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/WMIHelper.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/WMIHelper.cs index eed6efff76a..845d8206816 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/WMIHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/WMIHelper.cs @@ -200,7 +200,7 @@ private void ConnectSetWmi() SetWmiInstance setObject = (SetWmiInstance)_wmiObject; _state = WmiState.Running; RaiseWmiOperationState(null, WmiState.Running); - if (setObject.InputObject != null) + if (setObject.InputObject is not null) { ManagementObject mObj = null; try @@ -244,7 +244,7 @@ private void ConnectSetWmi() mObj = (ManagementObject)setObject.InputObject.Clone(); } - if (setObject.Arguments != null) + if (setObject.Arguments is not null) { IDictionaryEnumerator en = setObject.Arguments.GetEnumerator(); while (en.MoveNext()) @@ -254,7 +254,7 @@ private void ConnectSetWmi() } pOptions.Type = setObject.PutType; - if (mObj != null) + if (mObj is not null) { mObj.Put(_results, pOptions); } @@ -289,7 +289,7 @@ private void ConnectSetWmi() { ManagementPath mPath = null; // If Class is specified only CreateOnly flag is supported - if (setObject.Class != null) + if (setObject.Class is not null) { if (setObject.flagSpecified && setObject.PutType != PutType.CreateOnly) { @@ -360,7 +360,7 @@ private void ConnectSetWmi() } } // If server name is specified loop through it. - if (mPath != null) + if (mPath is not null) { if (!(mPath.Server == "." && setObject.serverNameSpecified)) { @@ -372,7 +372,7 @@ private void ConnectSetWmi() ManagementObject mObject = null; try { - if (setObject.Path != null) + if (setObject.Path is not null) { mPath.Server = _computerName; ManagementScope mScope = new ManagementScope(mPath, options); @@ -437,7 +437,7 @@ private void ConnectSetWmi() mObject = mClass.CreateInstance(); } - if (setObject.Arguments != null) + if (setObject.Arguments is not null) { IDictionaryEnumerator en = setObject.Arguments.GetEnumerator(); while (en.MoveNext()) @@ -448,7 +448,7 @@ private void ConnectSetWmi() PutOptions pOptions = new PutOptions(); pOptions.Type = setObject.PutType; - if (mObject != null) + if (mObject is not null) { mObject.Put(_results, pOptions); } @@ -490,13 +490,13 @@ private void ConnectInvokeWmi() _state = WmiState.Running; RaiseWmiOperationState(null, WmiState.Running); - if (invokeObject.InputObject != null) + if (invokeObject.InputObject is not null) { ManagementBaseObject inputParameters = null; try { inputParameters = invokeObject.InputObject.GetMethodParameters(invokeObject.Name); - if (invokeObject.ArgumentList != null) + if (invokeObject.ArgumentList is not null) { int inParamCount = invokeObject.ArgumentList.Length; foreach (PropertyData property in inputParameters.Properties) @@ -536,7 +536,7 @@ private void ConnectInvokeWmi() ConnectionOptions options = invokeObject.GetConnectionOption(); ManagementPath mPath = null; ManagementObject mObject = null; - if (invokeObject.Path != null) + if (invokeObject.Path is not null) { mPath = new ManagementPath(invokeObject.Path); if (string.IsNullOrEmpty(mPath.NamespacePath)) @@ -588,7 +588,7 @@ private void ConnectInvokeWmi() } } - if (invokeObject.Path != null) + if (invokeObject.Path is not null) { mPath.Server = _computerName; if (mPath.IsClass) @@ -614,7 +614,7 @@ private void ConnectInvokeWmi() } ManagementBaseObject inputParameters = mObject.GetMethodParameters(invokeObject.Name); - if (invokeObject.ArgumentList != null) + if (invokeObject.ArgumentList is not null) { int inParamCount = invokeObject.ArgumentList.Length; foreach (PropertyData property in inputParameters.Properties) @@ -629,7 +629,7 @@ private void ConnectInvokeWmi() if (needToEnablePrivilege) { ManagementBaseObject result = mObject.InvokeMethod(invokeObject.Name, inputParameters, null); - Dbg.Diagnostics.Assert(result != null, "result cannot be null if the Join method is invoked"); + Dbg.Diagnostics.Assert(result is not null, "result cannot be null if the Join method is invoked"); int returnCode = Convert.ToInt32(result["ReturnValue"], CultureInfo.CurrentCulture); if (returnCode != 0) { @@ -716,7 +716,7 @@ private void ConnectRemoveWmi() RemoveWmiObject removeObject = (RemoveWmiObject)_wmiObject; _state = WmiState.Running; RaiseWmiOperationState(null, WmiState.Running); - if (removeObject.InputObject != null) + if (removeObject.InputObject is not null) { try { @@ -748,7 +748,7 @@ private void ConnectRemoveWmi() ConnectionOptions options = removeObject.GetConnectionOption(); ManagementPath mPath = null; ManagementObject mObject = null; - if (removeObject.Path != null) + if (removeObject.Path is not null) { mPath = new ManagementPath(removeObject.Path); if (string.IsNullOrEmpty(mPath.NamespacePath)) @@ -781,7 +781,7 @@ private void ConnectRemoveWmi() try { - if (removeObject.Path != null) + if (removeObject.Path is not null) { mPath.Server = _computerName; if (mPath.IsClass) @@ -1198,7 +1198,7 @@ internal ConnectionOptions GetConnectionOption() options.Authority = this.Authority; options.EnablePrivileges = this.EnableAllPrivileges; options.Impersonation = this.Impersonation; - if (this.Credential != null) + if (this.Credential is not null) { if (!(this.Credential.UserName == null && this.Credential.Password == null)) // Empty credential, use implicit credential { @@ -1217,9 +1217,9 @@ internal ManagementObject SetWmiInstanceGetObject(ManagementPath mPath, string s ConnectionOptions options = GetConnectionOption(); ManagementObject mObject = null; var setObject = this as SetWmiInstance; - if (setObject != null) + if (setObject is not null) { - if (setObject.Path != null) + if (setObject.Path is not null) { mPath.Server = serverName; ManagementScope mScope = new ManagementScope(mPath, options); @@ -1275,7 +1275,7 @@ internal ManagementObject SetWmiInstanceGetObject(ManagementPath mPath, string s mObject = mClass.CreateInstance(); } - if (setObject.Arguments != null) + if (setObject.Arguments is not null) { IDictionaryEnumerator en = setObject.Arguments.GetEnumerator(); while (en.MoveNext()) @@ -1294,10 +1294,10 @@ internal ManagementPath SetWmiInstanceBuildManagementPath() { ManagementPath mPath = null; var wmiInstance = this as SetWmiInstance; - if (wmiInstance != null) + if (wmiInstance is not null) { // If Class is specified only CreateOnly flag is supported - if (wmiInstance.Class != null) + if (wmiInstance.Class is not null) { if (wmiInstance.flagSpecified && wmiInstance.PutType != PutType.CreateOnly) { @@ -1385,10 +1385,10 @@ internal ManagementObject SetWmiInstanceGetPipelineObject() // Should only be called from Set-WMIInstance cmdlet ManagementObject mObj = null; var wmiInstance = this as SetWmiInstance; - if (wmiInstance != null) + if (wmiInstance is not null) { // Extra check - if (wmiInstance.InputObject != null) + if (wmiInstance.InputObject is not null) { if (wmiInstance.InputObject.GetType() == typeof(ManagementClass)) { @@ -1429,7 +1429,7 @@ internal ManagementObject SetWmiInstanceGetPipelineObject() mObj = (ManagementObject)wmiInstance.InputObject.Clone(); } - if (wmiInstance.Arguments != null) + if (wmiInstance.Arguments is not null) { IDictionaryEnumerator en = wmiInstance.Arguments.GetEnumerator(); while (en.MoveNext()) @@ -1449,7 +1449,7 @@ internal ManagementObject SetWmiInstanceGetPipelineObject() internal void RunAsJob(string cmdletName) { PSWmiJob wmiJob = new PSWmiJob(this, ComputerName, this.ThrottleLimit, Job.GetCommandTextFromInvocationInfo(this.MyInvocation)); - if (_context != null) + if (_context is not null) { ((System.Management.Automation.Runspaces.LocalRunspace)_context.CurrentRunspace).JobRepository.Add(wmiJob); } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/WebServiceProxy.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/WebServiceProxy.cs index 547b121c571..b835b0d71c1 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/WebServiceProxy.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/WebServiceProxy.cs @@ -231,7 +231,7 @@ protected override void BeginProcessing() if (pr.Name.Equals("Credentials", StringComparison.OrdinalIgnoreCase)) { - if (Credential != null) + if (Credential is not null) { NetworkCredential cred = Credential.GetNetworkCredential(); pr.SetValue(instance, cred as object, null); @@ -338,7 +338,7 @@ private Assembly GenerateWebServiceProxyAssembly(string NameSpace, string ClassN catch (WebException ex) { ErrorRecord er = new ErrorRecord(ex, "WebException", ErrorCategory.ObjectNotFound, _uri); - if (ex.InnerException != null) + if (ex.InnerException is not null) er.ErrorDetails = new ErrorDetails(ex.InnerException.Message); WriteError(er); return null; @@ -475,11 +475,11 @@ private object InstantiateWebServiceProxy(Assembly assembly) break; } - if (proxyType != null) break; + if (proxyType is not null) break; } System.Management.Automation.Diagnostics.Assert( - proxyType != null, + proxyType is not null, "Proxy class should always get generated unless there were some errors earlier (in that case we shouldn't get here)"); return assembly.CreateInstance(proxyType.ToString()); diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/WriteContentCommandBase.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/WriteContentCommandBase.cs index 6045773b236..a4a1205a288 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/WriteContentCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/WriteContentCommandBase.cs @@ -78,7 +78,7 @@ public object[] Value /// protected override void BeginProcessing() { - if (Path != null && Path.Length > 0) + if (Path is not null && Path.Length > 0) { _pipingPaths = false; } @@ -106,7 +106,7 @@ protected override void ProcessRecord() { // Make sure to clean up the content writers that are already there - if (contentStreams != null && contentStreams.Count > 0) + if (contentStreams is not null && contentStreams.Count > 0) { CloseContent(contentStreams, false); _contentWritersOpen = false; @@ -135,7 +135,7 @@ protected override void ProcessRecord() { foreach (ContentHolder holder in contentStreams) { - if (holder.Writer != null) + if (holder.Writer is not null) { IList result = null; try @@ -167,7 +167,7 @@ protected override void ProcessRecord() continue; } - if (result != null && result.Count > 0 && PassThru) + if (result is not null && result.Count > 0 && PassThru) { WriteContentObject(result, result.Count, holder.PathInfo, currentContext); } @@ -236,7 +236,7 @@ internal virtual void BeforeOpenStreams(string[] paths) /// internal override object GetDynamicParameters(CmdletProviderContext context) { - if (Path != null && Path.Length > 0) + if (Path is not null && Path.Length > 0) { return InvokeProvider.Content.GetContentWriterDynamicParameters(Path[0], context); } @@ -308,9 +308,9 @@ internal List GetContentWriters( continue; } - if (writers != null && writers.Count > 0) + if (writers is not null && writers.Count > 0) { - if (writers.Count == 1 && writers[0] != null) + if (writers.Count == 1 && writers[0] is not null) { ContentHolder holder = new ContentHolder(pathInfo, null, writers[0]); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs index b81799eb6bc..d17c321c481 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs @@ -225,7 +225,7 @@ private void EnsureValue1HasBeenSpecified() fdc.Add(new FieldDescription("Value")); string prompt = StringUtil.Format(AddMember.Value1Prompt, _memberType); Dictionary result = this.Host.UI.Prompt(prompt, null, fdc); - if (result != null) + if (result is not null) { _value1 = result["Value"].BaseObject; } @@ -349,7 +349,7 @@ private PSMemberInfo GetScriptProperty() /// protected override void ProcessRecord() { - if (_typeName != null && string.IsNullOrWhiteSpace(_typeName)) + if (_typeName is not null && string.IsNullOrWhiteSpace(_typeName)) { ThrowTerminatingError(NewError("TypeNameShouldNotBeEmpty", "TypeNameShouldNotBeEmpty", _typeName)); } @@ -437,7 +437,7 @@ protected override void ProcessRecord() if (!AddMemberToTarget(member)) return; - if (_typeName != null) + if (_typeName is not null) { UpdateTypeNames(); } @@ -456,7 +456,7 @@ protected override void ProcessRecord() private bool AddMemberToTarget(PSMemberInfo member) { PSMemberInfo previousMember = _inputObject.Members[member.Name]; - if (previousMember != null) + if (previousMember is not null) { if (!_force) { @@ -508,7 +508,7 @@ private void ProcessNotePropertyMultiMemberSet() result = true; } - if (result && _typeName != null) + if (result && _typeName is not null) { UpdateTypeNames(); } @@ -559,7 +559,7 @@ protected override void Validate(object arguments, EngineIntrinsics engineIntrin { string notePropertyName = arguments as string; PSMemberTypes memberType; - if (notePropertyName != null && LanguagePrimitives.TryConvertTo(notePropertyName, out memberType)) + if (notePropertyName is not null && LanguagePrimitives.TryConvertTo(notePropertyName, out memberType)) { switch (memberType) { @@ -588,7 +588,7 @@ internal sealed class NotePropertyTransformationAttribute : ArgumentTransformati public override object Transform(EngineIntrinsics engineIntrinsics, object inputData) { object target = PSObject.Base(inputData); - if (target != null && target.GetType().IsNumeric()) + if (target is not null && target.GetType().IsNumeric()) { var result = LanguagePrimitives.ConvertTo(target); return result; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs index 008344e7366..9d34f92e026 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs @@ -106,7 +106,7 @@ public string[] MemberDefinition { _sourceCode = string.Empty; - if (value != null) + if (value is not null) { _sourceCode = string.Join("\n", value); } @@ -296,7 +296,7 @@ public string[] ReferencedAssemblies set { - if (value != null) { _referencedAssemblies = value; } + if (value is not null) { _referencedAssemblies = value; } } } @@ -321,7 +321,7 @@ public string OutputAssembly { _outputAssembly = value; - if (_outputAssembly != null) + if (_outputAssembly is not null) { _outputAssembly = _outputAssembly.Trim(); @@ -792,7 +792,7 @@ private string ResolveAssemblyName(string assembly, bool isForReferenceAssembly) if (!assembly.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) { Assembly result = LoadAssemblyHelper(assembly); - if (result != null) + if (result is not null) { return result.Location; } @@ -963,7 +963,7 @@ private void SourceCodeProcessing() CompilationOptions compilationOptions = null; EmitOptions emitOptions = null; - if (CompilerOptions != null) + if (CompilerOptions is not null) { var arguments = ParseCompilerOption(CompilerOptions); 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..ecd0ebe1317 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Compare-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Compare-Object.cs @@ -153,7 +153,7 @@ private readonly List _differenceEntryBacklog /// private void Process(OrderByPropertyEntry differenceEntry) { - Diagnostics.Assert(_referenceEntries != null, "null referenceEntries"); + Diagnostics.Assert(_referenceEntries is not null, "null referenceEntries"); // Retrieve the next reference object (referenceEntry) if any OrderByPropertyEntry referenceEntry = null; @@ -167,7 +167,7 @@ private void Process(OrderByPropertyEntry differenceEntry) // Return // 2005/07/19 Switched order of referenceEntry and differenceEntry // so that we cast differenceEntry to the type of referenceEntry. - if (referenceEntry != null && differenceEntry != null && + if (referenceEntry is not null && differenceEntry is not null && 0 == _comparer.Compare(referenceEntry, differenceEntry)) { EmitMatch(referenceEntry); @@ -180,7 +180,7 @@ private void Process(OrderByPropertyEntry differenceEntry) // Clear differenceEntry OrderByPropertyEntry matchingEntry = MatchAndRemove(differenceEntry, _referenceEntryBacklog); - if (matchingEntry != null) + if (matchingEntry is not null) { EmitMatch(matchingEntry); differenceEntry = null; @@ -192,7 +192,7 @@ private void Process(OrderByPropertyEntry differenceEntry) // Clear referenceEntry matchingEntry = MatchAndRemove(referenceEntry, _differenceEntryBacklog); - if (matchingEntry != null) + if (matchingEntry is not null) { EmitMatch(referenceEntry); referenceEntry = null; @@ -206,7 +206,7 @@ private void Process(OrderByPropertyEntry differenceEntry) // Emit oldest entry in differenceEntryBacklog as unmatched // Remove oldest entry from differenceEntryBacklog // Add differenceEntry to differenceEntryBacklog - if (differenceEntry != null) + if (differenceEntry is not null) { if (0 < SyncWindow) { @@ -232,7 +232,7 @@ private void Process(OrderByPropertyEntry differenceEntry) // Emit oldest entry in referenceEntryBacklog as unmatched // Remove oldest entry from referenceEntryBacklog // Add referenceEntry to referenceEntryBacklog - if (referenceEntry != null) + if (referenceEntry is not null) { if (0 < SyncWindow) { @@ -253,15 +253,15 @@ private void Process(OrderByPropertyEntry differenceEntry) private void InitComparer() { - if (_comparer != null) + if (_comparer is not null) return; List referenceObjectList = new List(ReferenceObject); _orderByProperty = new OrderByProperty( this, referenceObjectList, Property, true, _cultureInfo, CaseSensitive); - Diagnostics.Assert(_orderByProperty.Comparer != null, "no comparer"); + Diagnostics.Assert(_orderByProperty.Comparer is not null, "no comparer"); Diagnostics.Assert( - _orderByProperty.OrderMatrix != null && + _orderByProperty.OrderMatrix is not null && _orderByProperty.OrderMatrix.Count == ReferenceObject.Length, "no OrderMatrix"); if (_orderByProperty.Comparer is null || _orderByProperty.OrderMatrix is null || _orderByProperty.OrderMatrix.Count == 0) @@ -279,11 +279,11 @@ private OrderByPropertyEntry MatchAndRemove( { if (match is null || list is null) return null; - Diagnostics.Assert(_comparer != null, "null comparer"); + Diagnostics.Assert(_comparer is not null, "null comparer"); for (int i = 0; i < list.Count; i++) { OrderByPropertyEntry listEntry = list[i]; - Diagnostics.Assert(listEntry != null, "null listEntry " + i); + Diagnostics.Assert(listEntry is not null, "null listEntry " + i); if (0 == _comparer.Compare(match, listEntry)) { list.RemoveAt(i); @@ -315,7 +315,7 @@ private void EmitReferenceOnly(OrderByPropertyEntry entry) private void Emit(OrderByPropertyEntry entry, string sideIndicator) { - Diagnostics.Assert(entry != null, "null entry"); + Diagnostics.Assert(entry is not null, "null entry"); PSObject mshobj; if (PassThru) @@ -334,7 +334,7 @@ private void Emit(OrderByPropertyEntry entry, string sideIndicator) else { List mshParameterList = _orderByProperty.MshParameterList; - Diagnostics.Assert(mshParameterList != null, "null mshParameterList"); + Diagnostics.Assert(mshParameterList is not null, "null mshParameterList"); Diagnostics.Assert(mshParameterList.Count == Property.Length, "mshParameterList.Count " + mshParameterList.Count); for (int i = 0; i < Property.Length; i++) @@ -342,11 +342,11 @@ private void Emit(OrderByPropertyEntry entry, string sideIndicator) // 2005/07/05 This is the closest we can come to // the string typed by the user MshParameter mshParameter = mshParameterList[i]; - Diagnostics.Assert(mshParameter != null, "null mshParameter"); + Diagnostics.Assert(mshParameter is not null, "null mshParameter"); Hashtable hash = mshParameter.hash; - Diagnostics.Assert(hash != null, "null hash"); + Diagnostics.Assert(hash is not null, "null hash"); object prop = hash[FormatParameterDefinitionKeys.ExpressionEntryKey]; - Diagnostics.Assert(prop != null, "null prop"); + Diagnostics.Assert(prop is not null, "null prop"); string propName = prop.ToString(); PSNoteProperty propertyNote = new PSNoteProperty( propName, @@ -428,7 +428,7 @@ protected override void EndProcessing() { // Clear remaining reference objects if there are more // reference objects than difference objects - if (_referenceEntries != null) + if (_referenceEntries is not null) { while (_referenceObjectIndex < _referenceEntries.Count) { 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..aa65d4c948d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-SddlString.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-SddlString.cs @@ -63,7 +63,7 @@ private List GetApplicableAccessRights(int accessMask, AccessRightTypeNa List foundAccessRightNames = new List(); HashSet foundAccessRightValues = new HashSet(); - if (typeName != null) + if (typeName is not null) { typesToExamine.Add(GetRealAccessRightType(typeName.Value)); } 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..09147b0439f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertTo-Html.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertTo-Html.cs @@ -369,13 +369,13 @@ private void InitializeResolvedNameMshParameters() // Accept the width both as a string and as an int. string width; int? widthNum = p.GetEntry(ConvertHTMLParameterDefinitionKeys.WidthEntryKey) as int?; - width = widthNum != null ? widthNum.Value.ToString() : p.GetEntry(ConvertHTMLParameterDefinitionKeys.WidthEntryKey) as string; + width = widthNum is not null ? widthNum.Value.ToString() : p.GetEntry(ConvertHTMLParameterDefinitionKeys.WidthEntryKey) as string; PSPropertyExpression ex = p.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as PSPropertyExpression; List resolvedNames = ex.ResolveNames(_inputObject); foreach (PSPropertyExpression resolvedName in resolvedNames) { Hashtable ht = CreateAuxPropertyHT(label, alignment, width); - if (resolvedName.Script != null) + if (resolvedName.Script is not null) { // The argument is a calculated property whose value is calculated by a script block. ht.Add(FormatParameterDefinitionKeys.ExpressionEntryKey, resolvedName.Script); @@ -397,17 +397,17 @@ private static Hashtable CreateAuxPropertyHT( string width) { Hashtable ht = new Hashtable(); - if (label != null) + if (label is not null) { ht.Add(ConvertHTMLParameterDefinitionKeys.LabelEntryKey, label); } - if (alignment != null) + if (alignment is not null) { ht.Add(ConvertHTMLParameterDefinitionKeys.AlignmentEntryKey, alignment); } - if (width != null) + if (width is not null) { ht.Add(ConvertHTMLParameterDefinitionKeys.WidthEntryKey, width); } @@ -508,7 +508,7 @@ protected override void BeginProcessing() WarningRecord record = new WarningRecord(Message); InvocationInfo invocationInfo = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo; - if (invocationInfo != null) + if (invocationInfo is not null) { record.SetInvocationInfo(invocationInfo); } @@ -530,13 +530,13 @@ protected override void BeginProcessing() } WriteObject(""); - if (_body != null) + if (_body is not null) { WriteObject(_body, true); } } - if (_preContent != null) + if (_preContent is not null) { WriteObject(_preContent, true); } @@ -558,7 +558,7 @@ private void WriteColumns(List mshParams) { COLTag.Append(" mshParams) } string alignment = p.GetEntry(ConvertHTMLParameterDefinitionKeys.AlignmentEntryKey) as string; - if (alignment != null) + if (alignment is not null) { COLTag.Append(" align = \""); COLTag.Append(alignment); @@ -613,7 +613,7 @@ private void WritePropertyName(StringBuilder Listtag, MshParameter p) { // for writing the property name string label = p.GetEntry(ConvertHTMLParameterDefinitionKeys.LabelEntryKey) as string; - if (label != null) + if (label is not null) { Listtag.Append(label); } @@ -636,7 +636,7 @@ private void WritePropertyValue(StringBuilder Listtag, MshParameter p) foreach (PSPropertyExpressionResult result in resultList) { // create comma sep list for multiple results - if (result.Result != null) + if (result.Result is not null) { string htmlEncodedResult = WebUtility.HtmlEncode(SafeToString(result.Result)); Listtag.Append(htmlEncodedResult); @@ -744,7 +744,7 @@ protected override void EndProcessing() { // if fragment,end with table WriteObject(""); - if (_postContent != null) + if (_postContent is not null) WriteObject(_postContent, true); // if not fragment end with body and html also diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs index ffb42452db2..096576bbca0 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs @@ -283,7 +283,7 @@ protected override void ProcessRecord() { // figure out the column names (and lock-in their order) _propertyNames = ExportCsvHelper.BuildPropertyNames(InputObject, _propertyNames); - if (_isActuallyAppending && _preexistingPropertyNames != null) + if (_isActuallyAppending && _preexistingPropertyNames is not null) { this.ReconcilePreexistingPropertyNames(); } @@ -400,9 +400,9 @@ private void CreateFileStream() private void CleanUp() { - if (_fs != null) + if (_fs is not null) { - if (_sw != null) + if (_sw is not null) { _sw.Flush(); _sw.Dispose(); @@ -413,11 +413,11 @@ private void CleanUp() _fs = null; // reset the read-only attribute - if (_readOnlyFileInfo != null) + if (_readOnlyFileInfo is not null) _readOnlyFileInfo.Attributes |= FileAttributes.ReadOnly; } - if (_helper != null) + if (_helper is not null) { _helper.Dispose(); } @@ -624,7 +624,7 @@ protected override void ProcessRecord() this.ThrowTerminatingError(errorRecord); } - if (_paths != null) + if (_paths is not null) { foreach (string path in _paths) { @@ -823,12 +823,12 @@ protected override void ProcessRecord() this.ThrowTerminatingError(errorRecord); } - if ((Header is null) && (helper.Header != null)) + if ((Header is null) && (helper.Header is not null)) { Header = helper.Header.ToArray(); } - if ((_typeName is null) && (helper.TypeName != null)) + if ((_typeName is null) && (helper.TypeName is not null)) { _typeName = helper.TypeName; } @@ -878,7 +878,7 @@ internal ExportCsvHelper(char delimiter, BaseCsvWritingCommand.QuoteKind quoteKi /// internal static IList BuildPropertyNames(PSObject source, IList propertyNames) { - if (propertyNames != null) + if (propertyNames is not null) { throw new InvalidOperationException(CsvCommandStrings.BuildPropertyNamesMethodShouldBeCalledOnlyOncePerCmdletInstance); } @@ -923,7 +923,7 @@ internal string ConvertPropertyNamesCSV(IList propertyNames) _outputString.Append(_delimiter); } - if (_quoteFields != null) + if (_quoteFields is not null) { if (_quoteFields.TryGetValue(propertyName, out _)) { @@ -994,7 +994,7 @@ internal string ConvertPSObjectToCSV(PSObject mshObject, IList propertyN { var value = GetToStringValueForProperty(property); - if (_quoteFields != null) + if (_quoteFields is not null) { if (_quoteFields.TryGetValue(propertyName, out _)) { @@ -1013,7 +1013,7 @@ internal string ConvertPSObjectToCSV(PSObject mshObject, IList propertyN AppendStringWithEscapeAlways(_outputString, value); break; case BaseCsvWritingCommand.QuoteKind.AsNeeded: - if (value != null && value.Contains(_delimiter)) + if (value is not null && value.Contains(_delimiter)) { AppendStringWithEscapeAlways(_outputString, value); } @@ -1053,7 +1053,7 @@ internal static string GetToStringValueForProperty(PSPropertyInfo property) try { object temp = property.Value; - if (temp != null) + if (temp is not null) { value = temp.ToString(); } @@ -1312,7 +1312,7 @@ internal void ReadHeader() } } - if (Header != null && Header.Count > 0) + if (Header is not null && Header.Count > 0) { ValidatePropertyNames(Header); } @@ -1351,7 +1351,7 @@ internal void Import(ref bool alreadyWriteOutWarning) /// private static void ValidatePropertyNames(IList names) { - if (names != null) + if (names is not null) { if (names.Count == 0) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs index 91ec09a8034..579998ac394 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs @@ -171,7 +171,7 @@ internal void DoneAsStream() internal void Stop() { CustomInternalSerializer serializer = _serializer; - if (serializer != null) + if (serializer is not null) { serializer.Stop(); } @@ -222,7 +222,7 @@ internal class /// internal CustomInternalSerializer(XmlWriter writer, bool notypeinformation, bool isfirstcallforObject) { - Dbg.Assert(writer != null, "caller should validate the parameter"); + Dbg.Assert(writer is not null, "caller should validate the parameter"); _writer = writer; _notypeinformation = notypeinformation; @@ -315,11 +315,11 @@ internal void WriteOneObject(object source, string property, int depth) /// private bool HandlePrimitiveKnownType(object source, string property) { - Dbg.Assert(source != null, "caller should validate the parameter"); + Dbg.Assert(source is not null, "caller should validate the parameter"); // Check if source is of primitive known type TypeSerializationInfo pktInfo = KnownTypes.GetTypeSerializationInfo(source.GetType()); - if (pktInfo != null) + if (pktInfo is not null) { WriteOnePrimitiveKnownType(_writer, property, source, pktInfo); return true; @@ -339,16 +339,16 @@ private bool HandlePrimitiveKnownType(object source, string property) /// private bool HandlePrimitiveKnownTypePSObject(object source, string property, int depth) { - Dbg.Assert(source != null, "caller should validate the parameter"); + Dbg.Assert(source is not null, "caller should validate the parameter"); bool sourceHandled = false; PSObject moSource = source as PSObject; - if (moSource != null && !moSource.ImmediateBaseObjectIsEmpty) + if (moSource is not null && !moSource.ImmediateBaseObjectIsEmpty) { // Check if baseObject is primitive known type object baseObject = moSource.ImmediateBaseObject; TypeSerializationInfo pktInfo = KnownTypes.GetTypeSerializationInfo(baseObject.GetType()); - if (pktInfo != null) + if (pktInfo is not null) { WriteOnePrimitiveKnownType(_writer, property, baseObject, pktInfo); sourceHandled = true; @@ -360,7 +360,7 @@ private bool HandlePrimitiveKnownTypePSObject(object source, string property, in private bool HandleKnownContainerTypes(object source, string property, int depth) { - Dbg.Assert(source != null, "caller should validate the parameter"); + Dbg.Assert(source is not null, "caller should validate the parameter"); ContainerType ct = ContainerType.None; PSObject mshSource = source as PSObject; @@ -368,13 +368,13 @@ private bool HandleKnownContainerTypes(object source, string property, int depth IDictionary dictionary = null; // If passed in object is PSObject with no baseobject, return false. - if (mshSource != null && mshSource.ImmediateBaseObjectIsEmpty) + if (mshSource is not null && mshSource.ImmediateBaseObjectIsEmpty) { return false; } // Check if source (or baseobject in mshSource) is known container type - GetKnownContainerTypeInfo(mshSource != null ? mshSource.ImmediateBaseObject : source, out ct, + GetKnownContainerTypeInfo(mshSource is not null ? mshSource.ImmediateBaseObject : source, out ct, out dictionary, out enumerable); if (ct == ContainerType.None) @@ -412,7 +412,7 @@ private bool HandleKnownContainerTypes(object source, string property, int depth // We serialize properties of enumerable and on deserialization mark the object // as Deserialized. So if object is marked deserialized, we should write properties. // Note: we do not serialize the properties of IEnumerable if depth is zero. - if (depth != 0 && (ct == ContainerType.Enumerable || (mshSource != null && mshSource.IsDeserialized))) + if (depth != 0 && (ct == ContainerType.Enumerable || (mshSource is not null && mshSource.IsDeserialized))) { // Note:Depth is the depth for serialization of baseObject. // Depth for serialization of each property is one less. @@ -420,11 +420,11 @@ private bool HandleKnownContainerTypes(object source, string property, int depth } // If source is PSObject, serialize notes - if (mshSource != null) + if (mshSource is not null) { // Serialize instanceMembers PSMemberInfoCollection instanceMembers = mshSource.InstanceMembers; - if (instanceMembers != null) + if (instanceMembers is not null) { WriteMemberInfoCollection(instanceMembers, depth, true); } @@ -445,14 +445,14 @@ private bool HandleKnownContainerTypes(object source, string property, int depth private void GetKnownContainerTypeInfo( object source, out ContainerType ct, out IDictionary dictionary, out IEnumerable enumerable) { - Dbg.Assert(source != null, "caller should validate the parameter"); + Dbg.Assert(source is not null, "caller should validate the parameter"); ct = ContainerType.None; dictionary = null; enumerable = null; dictionary = source as IDictionary; - if (dictionary != null) + if (dictionary is not null) { ct = ContainerType.Dictionary; return; @@ -462,19 +462,19 @@ private void GetKnownContainerTypeInfo( { ct = ContainerType.Stack; enumerable = LanguagePrimitives.GetEnumerable(source); - Dbg.Assert(enumerable != null, "Stack is enumerable"); + Dbg.Assert(enumerable is not null, "Stack is enumerable"); } else if (source is Queue) { ct = ContainerType.Queue; enumerable = LanguagePrimitives.GetEnumerable(source); - Dbg.Assert(enumerable != null, "Queue is enumerable"); + Dbg.Assert(enumerable is not null, "Queue is enumerable"); } else if (source is IList) { ct = ContainerType.List; enumerable = LanguagePrimitives.GetEnumerable(source); - Dbg.Assert(enumerable != null, "IList is enumerable"); + Dbg.Assert(enumerable is not null, "IList is enumerable"); } else { @@ -485,19 +485,19 @@ private void GetKnownContainerTypeInfo( { ct = ContainerType.Stack; enumerable = LanguagePrimitives.GetEnumerable(source); - Dbg.Assert(enumerable != null, "Stack is enumerable"); + Dbg.Assert(enumerable is not null, "Stack is enumerable"); } else if (DerivesFromGenericType(gt, typeof(Queue<>))) { ct = ContainerType.Queue; enumerable = LanguagePrimitives.GetEnumerable(source); - Dbg.Assert(enumerable != null, "Queue is enumerable"); + Dbg.Assert(enumerable is not null, "Queue is enumerable"); } else if (DerivesFromGenericType(gt, typeof(List<>))) { ct = ContainerType.List; enumerable = LanguagePrimitives.GetEnumerable(source); - Dbg.Assert(enumerable != null, "Queue is enumerable"); + Dbg.Assert(enumerable is not null, "Queue is enumerable"); } } } @@ -506,7 +506,7 @@ private void GetKnownContainerTypeInfo( if (ct == ContainerType.None) { enumerable = LanguagePrimitives.GetEnumerable(source); - if (enumerable != null) + if (enumerable is not null) { ct = ContainerType.Enumerable; } @@ -521,9 +521,9 @@ private void GetKnownContainerTypeInfo( /// private static bool DerivesFromGenericType(Type derived, Type baseType) { - Dbg.Assert(derived != null, "caller should validate the parameter"); - Dbg.Assert(baseType != null, "caller should validate the parameter"); - while (derived != null) + Dbg.Assert(derived is not null, "caller should validate the parameter"); + Dbg.Assert(baseType is not null, "caller should validate the parameter"); + while (derived is not null) { if (derived.GetTypeInfo().IsGenericType) derived = derived.GetGenericTypeDefinition(); @@ -565,20 +565,20 @@ private void WritePrimitiveTypePSObjectWithNotes( string property, int depth) { - Dbg.Assert(source != null, "caller should validate the parameter"); + Dbg.Assert(source is not null, "caller should validate the parameter"); // Write start of PSObject. Since baseobject is primitive known // type, we do not need TypeName information. - WriteStartOfPSObject(source, property, source.ToStringFromDeserialization != null); + WriteStartOfPSObject(source, property, source.ToStringFromDeserialization is not null); - if (pktInfo != null) + if (pktInfo is not null) { WriteOnePrimitiveKnownType(_writer, null, primitive, pktInfo); } // Serialize instanceMembers PSMemberInfoCollection instanceMembers = source.InstanceMembers; - if (instanceMembers != null) + if (instanceMembers is not null) { WriteMemberInfoCollection(instanceMembers, depth, true); } @@ -588,7 +588,7 @@ private void WritePrimitiveTypePSObjectWithNotes( private void HandleComplexTypePSObject(PSObject source, string property, int depth) { - Dbg.Assert(source != null, "caller should validate the parameter"); + Dbg.Assert(source is not null, "caller should validate the parameter"); WriteStartOfPSObject(source, property, true); @@ -643,9 +643,9 @@ private void WriteStartOfPSObject( string property, bool writeTNH) { - Dbg.Assert(mshObject != null, "caller should validate the parameter"); + Dbg.Assert(mshObject is not null, "caller should validate the parameter"); - if (property != null) + if (property is not null) { WriteStartElement(_writer, CustomSerializationStrings.Properties); WriteAttribute(_writer, CustomSerializationStrings.NameAttribute, property); @@ -678,7 +678,7 @@ private void WriteStartOfPSObject( /// private bool PSObjectHasNotes(PSObject source) { - if (source.InstanceMembers != null && source.InstanceMembers.Count > 0) + if (source.InstanceMembers is not null && source.InstanceMembers.Count > 0) { return true; } @@ -701,7 +701,7 @@ private bool PSObjectHasNotes(PSObject source) private void WriteMemberInfoCollection( PSMemberInfoCollection me, int depth, bool writeEnclosingMemberSetElementTag) { - Dbg.Assert(me != null, "caller should validate the parameter"); + Dbg.Assert(me is not null, "caller should validate the parameter"); foreach (PSMemberInfo info in me) { @@ -734,7 +734,7 @@ private void WriteMemberInfoCollection( /// private void WritePSObjectProperties(PSObject source, int depth) { - Dbg.Assert(source != null, "caller should validate the information"); + Dbg.Assert(source is not null, "caller should validate the information"); depth = GetDepthOfSerialization(source, depth); @@ -747,7 +747,7 @@ private void WritePSObjectProperties(PSObject source, int depth) foreach (string propertyName in source.GetSpecificPropertiesToSerialize(null)) { PSPropertyInfo property = source.Properties[propertyName]; - if (property != null) + if (property is not null) { specificProperties.Add(property); } @@ -759,7 +759,7 @@ private void WritePSObjectProperties(PSObject source, int depth) foreach (PSPropertyInfo prop in source.Properties) { - Dbg.Assert(prop != null, "propertyCollection should only have member of type PSProperty"); + Dbg.Assert(prop is not null, "propertyCollection should only have member of type PSProperty"); object value = AutomationNull.Value; // PSObject throws GetValueException if it cannot // get value for a property. @@ -799,7 +799,7 @@ private void WritePSObjectProperties(PSObject source, int depth) private void SerializeProperties( PSMemberInfoInternalCollection propertyCollection, string name, int depth) { - Dbg.Assert(propertyCollection != null, "caller should validate the parameter"); + Dbg.Assert(propertyCollection is not null, "caller should validate the parameter"); if (propertyCollection.Count == 0) return; @@ -807,7 +807,7 @@ private void SerializeProperties( { PSPropertyInfo prop = info as PSPropertyInfo; - Dbg.Assert(prop != null, "propertyCollection should only have member of type PSProperty"); + Dbg.Assert(prop is not null, "propertyCollection should only have member of type PSProperty"); object value = AutomationNull.Value; // PSObject throws GetValueException if it cannot @@ -840,7 +840,7 @@ private void SerializeProperties( /// private void WriteEnumerable(IEnumerable enumerable, int depth) { - Dbg.Assert(enumerable != null, "caller should validate the parameter"); + Dbg.Assert(enumerable is not null, "caller should validate the parameter"); IEnumerator enumerator = null; try @@ -855,7 +855,7 @@ private void WriteEnumerable(IEnumerable enumerable, int depth) // AD has incorrect implementation of IEnumerable where they returned null // for GetEnumerator instead of empty enumerator - if (enumerator != null) + if (enumerator is not null) { while (true) { @@ -897,7 +897,7 @@ private void WriteDictionary(IDictionary dictionary, int depth) { } - if (dictionaryEnum != null) + if (dictionaryEnum is not null) { while (dictionaryEnum.MoveNext()) { @@ -915,15 +915,15 @@ private void WriteDictionary(IDictionary dictionary, int depth) private void HandlePSObjectAsString(PSObject source, string property, int depth) { - Dbg.Assert(source != null, "caller should validate the information"); + Dbg.Assert(source is not null, "caller should validate the information"); bool hasNotes = PSObjectHasNotes(source); string value = GetStringFromPSObject(source); - if (value != null) + if (value is not null) { TypeSerializationInfo pktInfo = KnownTypes.GetTypeSerializationInfo(value.GetType()); - Dbg.Assert(pktInfo != null, "TypeSerializationInfo should be present for string"); + Dbg.Assert(pktInfo is not null, "TypeSerializationInfo should be present for string"); if (hasNotes) { WritePrimitiveTypePSObjectWithNotes(source, value, pktInfo, property, depth); @@ -958,15 +958,15 @@ private void HandlePSObjectAsString(PSObject source, string property, int depth) /// private string GetStringFromPSObject(PSObject source) { - Dbg.Assert(source != null, "caller should have validated the information"); + Dbg.Assert(source is not null, "caller should have validated the information"); // check if we have a well known string serialization source PSPropertyInfo serializationProperty = source.GetStringSerializationSource(null); string result = null; - if (serializationProperty != null) + if (serializationProperty is not null) { object val = serializationProperty.Value; - if (val != null) + if (val is not null) { try { @@ -1036,7 +1036,7 @@ private static int GetDepthOfSerialization(PSObject source, int depth) /// private void WriteNull(string property) { - if (property != null) + if (property is not null) { WriteStartElement(_writer, CustomSerializationStrings.Properties); WriteAttribute(_writer, CustomSerializationStrings.NameAttribute, property); @@ -1072,7 +1072,7 @@ private void WritePropertyWithNullValue( private void WriteObjectString( XmlWriter writer, string property, object source, TypeSerializationInfo entry) { - if (property != null) + if (property is not null) { WriteStartElement(writer, CustomSerializationStrings.Properties); WriteAttribute(writer, CustomSerializationStrings.NameAttribute, property); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs index 6ed5b66c8a1..4748d855f52 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs @@ -230,14 +230,14 @@ protected override void StopProcessing() // Cancel runspace debugging. System.Management.Automation.Debugger debugger = _debugger; - if ((debugger != null) && (_runspace != null)) + if ((debugger is not null) && (_runspace is not null)) { debugger.StopDebugRunspace(_runspace); } // Unblock the data collection. PSDataCollection debugCollection = _debugBlockingCollection; - if (debugCollection != null) + if (debugCollection is not null) { debugCollection.Complete(); } @@ -315,11 +315,11 @@ private void WaitAndReceiveRunspaceOutput() private void HostWriteLine(string line) { - if ((this.Host != null) && (this.Host.UI != null)) + if ((this.Host is not null) && (this.Host.UI is not null)) { try { - if (this.Host.UI.RawUI != null) + if (this.Host.UI.RawUI is not null) { this.Host.UI.WriteLine(ConsoleColor.Yellow, this.Host.UI.RawUI.BackgroundColor, line); } @@ -335,23 +335,23 @@ private void HostWriteLine(string line) private void AddDataEventHandlers() { // Create new collection objects. - if (_debugBlockingCollection != null) { _debugBlockingCollection.Dispose(); } + if (_debugBlockingCollection is not null) { _debugBlockingCollection.Dispose(); } - if (_debugAccumulateCollection != null) { _debugAccumulateCollection.Dispose(); } + if (_debugAccumulateCollection is not null) { _debugAccumulateCollection.Dispose(); } _debugBlockingCollection = new PSDataCollection(); _debugBlockingCollection.BlockingEnumerator = true; _debugAccumulateCollection = new PSDataCollection(); _runningPowerShell = _runspace.GetCurrentBasePowerShell(); - if (_runningPowerShell != null) + if (_runningPowerShell is not null) { - if (_runningPowerShell.OutputBuffer != null) + if (_runningPowerShell.OutputBuffer is not null) { _runningPowerShell.OutputBuffer.DataAdding += HandlePowerShellOutputBufferDataAdding; } - if (_runningPowerShell.ErrorBuffer != null) + if (_runningPowerShell.ErrorBuffer is not null) { _runningPowerShell.ErrorBuffer.DataAdding += HandlePowerShellErrorBufferDataAdding; } @@ -359,14 +359,14 @@ private void AddDataEventHandlers() else { _runningPipeline = _runspace.GetCurrentlyRunningPipeline(); - if (_runningPipeline != null) + if (_runningPipeline is not null) { - if (_runningPipeline.Output != null) + if (_runningPipeline.Output is not null) { _runningPipeline.Output.DataReady += HandlePipelineOutputDataReady; } - if (_runningPipeline.Error != null) + if (_runningPipeline.Error is not null) { _runningPipeline.Error.DataReady += HandlePipelineErrorDataReady; } @@ -376,28 +376,28 @@ private void AddDataEventHandlers() private void RemoveDataEventHandlers() { - if (_runningPowerShell != null) + if (_runningPowerShell is not null) { - if (_runningPowerShell.OutputBuffer != null) + if (_runningPowerShell.OutputBuffer is not null) { _runningPowerShell.OutputBuffer.DataAdding -= HandlePowerShellOutputBufferDataAdding; } - if (_runningPowerShell.ErrorBuffer != null) + if (_runningPowerShell.ErrorBuffer is not null) { _runningPowerShell.ErrorBuffer.DataAdding -= HandlePowerShellErrorBufferDataAdding; } _runningPowerShell = null; } - else if (_runningPipeline != null) + else if (_runningPipeline is not null) { - if (_runningPipeline.Output != null) + if (_runningPipeline.Output is not null) { _runningPipeline.Output.DataReady -= HandlePipelineOutputDataReady; } - if (_runningPipeline.Error != null) + if (_runningPipeline.Error is not null) { _runningPipeline.Error.DataReady -= HandlePipelineErrorDataReady; } @@ -410,10 +410,10 @@ private void HandleRunspaceAvailabilityChanged(object sender, RunspaceAvailabili { // Ignore nested commands. LocalRunspace localRunspace = sender as LocalRunspace; - if (localRunspace != null) + if (localRunspace is not null) { var basePowerShell = localRunspace.GetCurrentBasePowerShell(); - if ((basePowerShell != null) && (basePowerShell.IsNested)) + if ((basePowerShell is not null) && (basePowerShell.IsNested)) { return; } @@ -441,7 +441,7 @@ private void HandleDebuggerNestedDebuggingCancelledEvent(object sender, EventArg private void HandlePipelineOutputDataReady(object sender, EventArgs e) { PipelineReader reader = sender as PipelineReader; - if (reader != null && reader.IsOpen) + if (reader is not null && reader.IsOpen) { WritePipelineCollection(reader.NonBlockingRead(), PSStreamObjectType.Output); } @@ -450,7 +450,7 @@ private void HandlePipelineOutputDataReady(object sender, EventArgs e) private void HandlePipelineErrorDataReady(object sender, EventArgs e) { PipelineReader reader = sender as PipelineReader; - if (reader != null && reader.IsOpen) + if (reader is not null && reader.IsOpen) { WritePipelineCollection(reader.NonBlockingRead(), PSStreamObjectType.Error); } @@ -460,7 +460,7 @@ private void WritePipelineCollection(Collection collection, PSStreamObject { foreach (var item in collection) { - if (item != null) + if (item is not null) { AddToDebugBlockingCollection(new PSStreamObject(psStreamType, item)); } @@ -469,7 +469,7 @@ private void WritePipelineCollection(Collection collection, PSStreamObject private void HandlePowerShellOutputBufferDataAdding(object sender, DataAddingEventArgs e) { - if (e.ItemAdded != null) + if (e.ItemAdded is not null) { HandlePowerShellPStreamItem(new PSStreamObject(PSStreamObjectType.Output, e.ItemAdded)); } @@ -477,7 +477,7 @@ private void HandlePowerShellOutputBufferDataAdding(object sender, DataAddingEve private void HandlePowerShellErrorBufferDataAdding(object sender, DataAddingEventArgs e) { - if (e.ItemAdded != null) + if (e.ItemAdded is not null) { HandlePowerShellPStreamItem(new PSStreamObject(PSStreamObjectType.Error, e.ItemAdded)); } @@ -494,7 +494,7 @@ private void HandlePowerShellPStreamItem(PSStreamObject streamItem) } // Handle new item. - if ((_debugBlockingCollection != null) && (_debugBlockingCollection.IsOpen)) + if ((_debugBlockingCollection is not null) && (_debugBlockingCollection.IsOpen)) { AddToDebugBlockingCollection(streamItem); } @@ -510,7 +510,7 @@ private void AddToDebugBlockingCollection(PSStreamObject streamItem) { if (!_debugBlockingCollection.IsOpen) { return; } - if (streamItem != null) + if (streamItem is not null) { try { @@ -538,7 +538,7 @@ private void EnableHostDebugger(Runspace runspace, bool enabled) if (_debugger is ServerRemoteDebugger) { LocalRunspace localRunspace = runspace as LocalRunspace; - if ((localRunspace != null) && (localRunspace.ExecutionContext != null) && (localRunspace.ExecutionContext.EngineHostInterface != null)) + if ((localRunspace is not null) && (localRunspace.ExecutionContext is not null) && (localRunspace.ExecutionContext.EngineHostInterface is not null)) { try { @@ -552,7 +552,7 @@ private void EnableHostDebugger(Runspace runspace, bool enabled) private void SetLocalMode(System.Management.Automation.Debugger debugger, bool localMode) { ServerRemoteDebugger remoteDebugger = debugger as ServerRemoteDebugger; - if (remoteDebugger != null) + if (remoteDebugger is not null) { remoteDebugger.LocalDebugMode = localMode; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/EnableDisableRunspaceDebugCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/EnableDisableRunspaceDebugCommand.cs index 3a33974abeb..8621dd8bcef 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/EnableDisableRunspaceDebugCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/EnableDisableRunspaceDebugCommand.cs @@ -285,7 +285,7 @@ protected System.Management.Automation.Debugger GetDebuggerFromRunspace(Runspace protected void SetDebugPreferenceHelper(string processName, string[] appDomainName, bool enable, string fullyQualifiedErrorId) { List appDomainNames = null; - if (appDomainName != null) + if (appDomainName is not null) { foreach (string currentAppDomainName in appDomainName) { @@ -498,7 +498,7 @@ protected override void ProcessRecord() foreach (var runspace in results) { System.Management.Automation.Debugger debugger = GetDebuggerFromRunspace(runspace); - if (debugger != null) + if (debugger is not null) { WriteObject( new PSRunspaceDebug((debugger.UnhandledBreakpointMode == UnhandledBreakpointProcessingMode.Wait), @@ -533,7 +533,7 @@ protected override void EndProcessing() { Runspace currentRunspace = this.Context.CurrentRunspace; - if (currentRunspace != null && currentRunspace.Debugger != null) + if (currentRunspace is not null && currentRunspace.Debugger is not null) { WriteVerbose(string.Format(CultureInfo.InvariantCulture, Debugger.DebugBreakMessage, MyInvocation.ScriptLineNumber, MyInvocation.ScriptName)); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs index 6b362465c8b..bd424471b22 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs @@ -271,7 +271,7 @@ protected override void EndProcessing() writer = OpenFile(out readOnlyFileInfo); } - if (writer != null) + if (writer is not null) WriteHeader(writer); // Now write out the aliases @@ -288,7 +288,7 @@ protected override void EndProcessing() line = GetAliasLine(alias, "set-alias -Name:\"{0}\" -Value:\"{1}\" -Description:\"{2}\" -Option:\"{3}\""); } - if (writer != null) + if (writer is not null) writer.WriteLine(line); if (PassThru) @@ -299,10 +299,10 @@ protected override void EndProcessing() } finally { - if (writer != null) + if (writer is not null) writer.Dispose(); // reset the read-only attribute - if (readOnlyFileInfo != null) + if (readOnlyFileInfo is not null) readOnlyFileInfo.Attributes |= FileAttributes.ReadOnly; } } @@ -344,7 +344,7 @@ private void WriteHeader(StreamWriter writer) // Now write the description if there is one - if (Description != null) + if (Description is not null) { // First we need to break up the description on newlines and add a // # for each line. 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..e87766e9002 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 @@ -33,7 +33,7 @@ internal string DisplayName() internal Type GetValueType(PSObject liveObject, out object columnValue) { columnValue = GetValue(liveObject); - if (columnValue != null && columnValue is IComparable) + if (columnValue is not null && columnValue is IComparable) { return columnValue.GetType(); } 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..6363a1108ba 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 @@ -30,7 +30,7 @@ internal override object GetValue(PSObject liveObject) // Only first element is used. PSPropertyExpressionResult result = resList[0]; - if (result.Exception != null) + if (result.Exception is not null) { return null; } 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..ece2724a513 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 @@ -34,14 +34,14 @@ internal override object GetValue(PSObject liveObject) // The live object has the liveObjectPropertyName property. object liveObjectValue = propertyInfo.Value; ICollection collectionValue = liveObjectValue as ICollection; - if (collectionValue != null) + if (collectionValue is not null) { liveObjectValue = _parentCmdlet.ConvertToString(PSObjectHelper.AsPSObject(propertyInfo.Value)); } else { PSObject psObjectValue = liveObjectValue as PSObject; - if (psObjectValue != null) + if (psObjectValue is not null) { // Since PSObject implements IComparable there is a need to verify if its BaseObject actually implements IComparable. if (psObjectValue.BaseObject is IComparable) 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..8ed0a8e502a 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 @@ -115,7 +115,7 @@ protected override void BeginProcessing() _expressionFactory = new PSPropertyExpressionFactory(); // If the value of the Title parameter is valid, use it as a window's title. - if (this.Title != null) + if (this.Title is not null) { _windowProxy = new OutWindowProxy(this.Title, OutputMode, this); } @@ -150,7 +150,7 @@ protected override void EndProcessing() // Output selected items to pipeline. List selectedItems = _windowProxy.GetSelectedItems(); - if (this.OutputMode != OutputModeOption.None && selectedItems != null) + if (this.OutputMode != OutputModeOption.None && selectedItems is not null) { foreach (PSObject selectedItem in selectedItems) { @@ -181,7 +181,7 @@ protected override void ProcessRecord() } IDictionary dictionary = InputObject.BaseObject as IDictionary; - if (dictionary != null) + if (dictionary is not null) { // Dictionaries should be enumerated through because the pipeline does not enumerate through them. foreach (DictionaryEntry entry in dictionary) @@ -217,7 +217,7 @@ internal string ConvertToString(PSObject liveObject) _expressionFactory, InnerFormatShapeCommand.FormatEnumerationLimit(), formatErrorObject); - if (formatErrorObject.exception != null) + if (formatErrorObject.exception is not null) { // There was a formatting error that should be sent to the console. this.WriteError( @@ -247,7 +247,7 @@ private void ProcessObject(PSObject input) { LocalPipeline pipeline = (LocalPipeline)this.Context.CurrentRunspace.GetCurrentlyRunningPipeline(); - if (pipeline != null && !pipeline.IsStopping) + if (pipeline is not null && !pipeline.IsStopping) { // Stop the pipeline cleanly. pipeline.StopAsync(); @@ -287,7 +287,7 @@ baseObject is FormatInfoData || // Some thread synchronization needed. Exception exception = _windowProxy.GetLastException(); - if (exception != null) + if (exception is not null) { ErrorRecord error = new ErrorRecord( exception, @@ -362,7 +362,7 @@ internal NonscalarTypeHeader(OutGridViewCommand parentCmd, PSObject input) : bas // Request a view definition from the type database. ViewDefinition viewDefinition = DisplayDataQuery.GetViewByShapeAndType(parentCmd._expressionFactory, parentCmd._typeInfoDataBase, FormatShape.Table, input.TypeNames, null); - if (viewDefinition != null) + if (viewDefinition is not null) { // Create a header using a view definition provided by the types database. parentCmd._windowProxy.AddColumnsAndItem(input, tableView, (TableControlBody)viewDefinition.mainControl); @@ -476,7 +476,7 @@ private void Dispose(bool isDisposing) { if (isDisposing) { - if (_windowProxy != null) + if (_windowProxy is not null) { _windowProxy.Dispose(); _windowProxy = null; 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..45fd39b95d8 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 @@ -81,7 +81,7 @@ internal void AddColumns(string[] propertyNames, string[] displayNames, Type[] t { // Verify if this is an error loading the System.Core dll. FileNotFoundException fileNotFoundEx = ex.InnerException as FileNotFoundException; - if (fileNotFoundEx != null && fileNotFoundEx.FileName.Contains("System.Core")) + if (fileNotFoundEx is not null && fileNotFoundEx.FileName.Contains("System.Core")) { _parentCmdlet.ThrowTerminatingError( new ErrorRecord(new InvalidOperationException( @@ -232,7 +232,7 @@ internal void ShowWindow() internal void BlockUntillClosed() { - if (_closedEvent != null) + if (_closedEvent is not null) { _closedEvent.WaitOne(); } @@ -246,7 +246,7 @@ private void Dispose(bool isDisposing) { if (isDisposing) { - if (_closedEvent != null) + if (_closedEvent is not null) { _closedEvent.Dispose(); _closedEvent = null; 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..d1479181dae 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 @@ -41,7 +41,7 @@ internal HeaderInfo GenerateHeaderInfo(PSObject input, TableControlBody tableBod // as strings and it is used to detect this situation and use the actual field value. bool fileSystemObject = typeof(FileSystemInfo).IsInstanceOfType(input.BaseObject); - if (tableBody != null) // If the tableBody is null, the TableControlBody info was not put into the database. + if (tableBody is not null) // If the tableBody is null, the TableControlBody info was not put into the database. { // Generate HeaderInfo from the type information database. List activeRowItemDefinitionList = GetActiveTableRowDefinition(tableBody, input); @@ -56,7 +56,7 @@ internal HeaderInfo GenerateHeaderInfo(PSObject input, TableControlBody tableBod if (col < tableBody.header.columnHeaderDefinitionList.Count) colHeader = tableBody.header.columnHeaderDefinitionList[col]; - if (colHeader != null && colHeader.label != null) + if (colHeader is not null && colHeader.label is not null) { displayName = _typeInfoDatabase.displayResourceManagerCache.GetTextTokenString(colHeader.label); } @@ -67,10 +67,10 @@ internal HeaderInfo GenerateHeaderInfo(PSObject input, TableControlBody tableBod token = rowItem.formatTokenList[0]; } - if (token != null) + if (token is not null) { FieldPropertyToken fpt = token as FieldPropertyToken; - if (fpt != null) + if (fpt is not null) { if (displayName is null) { @@ -102,7 +102,7 @@ internal HeaderInfo GenerateHeaderInfo(PSObject input, TableControlBody tableBod else { TextToken tt = token as TextToken; - if (tt != null) + if (tt is not null) { displayName = _typeInfoDatabase.displayResourceManagerCache.GetTextTokenString(tt); columnInfo = new OriginalColumnInfo(tt.text, displayName, tt.text, parentCmdlet); @@ -110,7 +110,7 @@ internal HeaderInfo GenerateHeaderInfo(PSObject input, TableControlBody tableBod } } - if (columnInfo != null) + if (columnInfo is not null) { headerInfo.AddColumn(columnInfo); } @@ -163,7 +163,7 @@ internal HeaderInfo GenerateHeaderInfo(PSObject input, OutGridViewCommand parent MshResolvedExpressionParameterAssociation association = activeAssociationList[k]; // set the label of the column - if (association.OriginatingParameter != null) + if (association.OriginatingParameter is not null) { object key = association.OriginatingParameter.GetEntry(FormatParameterDefinitionKeys.LabelEntryKey); if (key != AutomationNull.Value) @@ -241,7 +241,7 @@ private List GetActiveTableRowDefinition(TableControlBod if (matchingRowDefinition is null) { Collection typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames); - if (typesWithoutPrefix != null) + if (typesWithoutPrefix is not null) { match = new TypeMatch(_expressionFactory, _typeInfoDatabase, typesWithoutPrefix); 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..f3dbedf9dca 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 @@ -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 is null && remotingClientInfo is not null) { clientVersion = PSObject.Base((PSObject.Base(remotingClientInfo.ApplicationArguments["PSVersionTable"]) as PSPrimitiveDictionary)?["PSVersion"]) as Version; } @@ -113,9 +113,9 @@ 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 is not null && clientVersion is null) // To be safe: Remoting client version could unexpectedly not be determined. || - (clientVersion != null + (clientVersion is not null && (clientVersion.Major < 5 || @@ -141,21 +141,21 @@ protected override void ProcessRecord() PSControl control; var tableControlBody = definition.mainControl as TableControlBody; - if (tableControlBody != null) + if (tableControlBody is not null) { control = new TableControl(tableControlBody, definition); } else { var listControlBody = definition.mainControl as ListControlBody; - if (listControlBody != null) + if (listControlBody is not null) { control = new ListControl(listControlBody, definition); } else { var wideControlBody = definition.mainControl as WideControlBody; - if (wideControlBody != null) + if (wideControlBody is not null) { control = new WideControl(wideControlBody, definition); if (writeOldWay) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs index a0225c8ea6a..575b8fdd958 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs @@ -349,7 +349,7 @@ private void ProcessInputObjects(PSObject inputObject) FlushInputBuffer(); } - if (inputBytes != null) + if (inputBytes is not null) { _inputBuffer.AddRange(inputBytes); } @@ -401,7 +401,7 @@ private byte[] ConvertToBytes(object inputObject) { if (_groupInput) { - if (_lastInputType != null && baseType != _lastInputType) + if (_lastInputType is not null && baseType != _lastInputType) { _groupInput = false; FlushInputBuffer(); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-object/Format-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-object/Format-Object.cs index 813bfad23c0..e685c4fcec3 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-object/Format-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-object/Format-Object.cs @@ -59,7 +59,7 @@ internal override FormattingCommandLineParameters GetCommandLineParameters() { FormattingCommandLineParameters parameters = new FormattingCommandLineParameters(); - if (_props != null) + if (_props is not null) { ParameterProcessor processor = new ParameterProcessor(new FormatObjectParameterDefinition()); TerminatingErrorContext invocationContext = new TerminatingErrorContext(this); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-wide/Format-Wide.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-wide/Format-Wide.cs index 5927244d896..f85c492023e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-wide/Format-Wide.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-wide/Format-Wide.cs @@ -85,7 +85,7 @@ internal override FormattingCommandLineParameters GetCommandLineParameters() { FormattingCommandLineParameters parameters = new FormattingCommandLineParameters(); - if (_prop != null) + if (_prop is not null) { ParameterProcessor processor = new ParameterProcessor(new FormatWideParameterDefinition()); TerminatingErrorContext invocationContext = new TerminatingErrorContext(this); 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..77a4733a945 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 @@ -127,7 +127,7 @@ public SwitchParameter NoClobber [Parameter] public int Width { - get { return (_width != null) ? _width.Value : 0; } + get { return (_width is not null) ? _width.Value : 0; } set { _width = value; } } @@ -208,7 +208,7 @@ private LineOutput InstantiateLineOutputInterface() // compute the # of columns available int computedWidth = int.MaxValue; - if (_width != null) + if (_width is not null) { // use the value from the command line computedWidth = _width.Value; @@ -279,14 +279,14 @@ protected override void InternalDispose() private void CleanUp() { - if (_fs != null) + if (_fs is not null) { _fs.Dispose(); _fs = null; } // reset the read-only attribute - if (_readOnlyFileInfo != null) + if (_readOnlyFileInfo is not null) { _readOnlyFileInfo.Attributes |= FileAttributes.ReadOnly; _readOnlyFileInfo = null; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs index 5616a7fa436..28b683a58d9 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs @@ -139,7 +139,7 @@ private void DoPrint() finally { // make sure we do not leak the font - if (_printFont != null) + if (_printFont is not null) { _printFont.Dispose(); _printFont = null; @@ -155,7 +155,7 @@ private void DoPrint() /// GDI+ graphics object needed for verification. private void CreateFont(Graphics g) { - if (_printFont != null) + if (_printFont is not null) return; // create the font diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-string/Out-String.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-string/Out-String.cs index 5dcb3c4f588..a70a2d5f111 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-string/Out-String.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-string/Out-String.cs @@ -40,7 +40,7 @@ public SwitchParameter Stream [Parameter] public int Width { - get { return (_width != null) ? _width.Value : 0; } + get { return (_width is not null) ? _width.Value : 0; } set { _width = value; } } @@ -98,7 +98,7 @@ private LineOutput InstantiateLineOutputInterface() // compute the # of columns available int computedWidth = int.MaxValue; - if (_width != null) + if (_width is not null) { // use the value from the command line computedWidth = _width.Value; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-Error.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-Error.cs index 7c2fdbe0c14..ff6b8ef68c4 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-Error.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-Error.cs @@ -46,7 +46,7 @@ protected override void ProcessRecord() var errorRecords = new List(); var index = 0; - if (InputObject != null) + if (InputObject is not null) { if (InputObject.BaseObject is Exception || InputObject.BaseObject is ErrorRecord) { 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..a215ef311d4 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSBreakpoint.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSBreakpoint.cs @@ -190,7 +190,7 @@ protected override void ProcessRecord() } // Filter by script - if (Script != null) + if (Script is not null) { breakpoints = Filter( breakpoints, diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetDateCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetDateCommand.cs index 4516568cc34..e5ce64e364b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetDateCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetDateCommand.cs @@ -308,12 +308,12 @@ protected override void ProcessRecord() dateToUse = dateToUse.ToUniversalTime(); } - if (UFormat != null) + if (UFormat is not null) { // format according to UFormat string WriteObject(UFormatDateString(dateToUse)); } - else if (Format != null) + else if (Format is not null) { // format according to Format string diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventCommand.cs index faf16d384f7..8cb023addd5 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventCommand.cs @@ -32,7 +32,7 @@ public string SourceIdentifier { _sourceIdentifier = value; - if (value != null) + if (value is not null) { _matchPattern = WildcardPattern.Get(value, WildcardOptions.IgnoreCase); } @@ -83,7 +83,7 @@ protected override void EndProcessing() foreach (PSEventArgs eventArg in eventArgsCollection) { // If they specified a event identifier and we don't match, continue - if ((_sourceIdentifier != null) && + if ((_sourceIdentifier is not null) && (!_matchPattern.IsMatch(eventArg.SourceIdentifier))) { continue; @@ -104,7 +104,7 @@ protected override void EndProcessing() // and no globbing was done. if (!foundMatch) { - bool lookingForSource = (_sourceIdentifier != null) && + bool lookingForSource = (_sourceIdentifier is not null) && (!WildcardPattern.ContainsWildcardCharacters(_sourceIdentifier)); bool lookingForId = (_eventId >= 0); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventSubscriberCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventSubscriberCommand.cs index cde73b2914d..e1ce5ef2150 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventSubscriberCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventSubscriberCommand.cs @@ -32,7 +32,7 @@ public string SourceIdentifier { _sourceIdentifier = value; - if (value != null) + if (value is not null) { _matchPattern = WildcardPattern.Get(value, WildcardOptions.IgnoreCase); } @@ -71,7 +71,7 @@ protected override void ProcessRecord() foreach (PSEventSubscriber subscriber in subscribers) { // If they specified a event identifier and we don't match, continue - if ((_sourceIdentifier != null) && + if ((_sourceIdentifier is not null) && (!_matchPattern.IsMatch(subscriber.SourceIdentifier))) { continue; @@ -98,7 +98,7 @@ protected override void ProcessRecord() // and no globbing was done. if (!foundMatch) { - bool lookingForSource = (_sourceIdentifier != null) && + bool lookingForSource = (_sourceIdentifier is not null) && (!WildcardPattern.ContainsWildcardCharacters(_sourceIdentifier)); bool lookingForId = (SubscriptionId >= 0); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHash.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHash.cs index 65e55a86ab1..21e80f45b0b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHash.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHash.cs @@ -95,7 +95,7 @@ protected override void ProcessRecord() try { Collection newPaths = Context.SessionState.Path.GetResolvedProviderPathFromPSPath(path, out provider); - if (newPaths != null) + if (newPaths is not null) { pathsToProcess.AddRange(newPaths); } @@ -203,7 +203,7 @@ private bool ComputeFileHash(string path, out string hash) openfilestream?.Dispose(); } - return hash != null; + return hash is not null; } /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs index d7492ced51b..f2b8cec5851 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs @@ -232,7 +232,7 @@ protected override void ProcessRecord() if (!Force) { PSMethod memberAsPSMethod = member as PSMethod; - if ((memberAsPSMethod != null) && (memberAsPSMethod.IsSpecial)) + if ((memberAsPSMethod is not null) && (memberAsPSMethod.IsSpecial)) { continue; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs index cad052a58e2..49fb83a1436 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs @@ -59,7 +59,7 @@ private MyParameterSet EffectiveParameterSet } else if (ParameterSetName.Equals(GetRandomCommand.RandomNumberParameterSet, StringComparison.OrdinalIgnoreCase)) { - if ((Maximum != null) && (Maximum.GetType().IsArray)) + if ((Maximum is not null) && (Maximum.GetType().IsArray)) { InputObject = (object[])Maximum; _effectiveParameterSet = MyParameterSet.RandomListItem; @@ -406,8 +406,8 @@ protected override void BeginProcessing() if (IsInt(maxOperand) && IsInt(minOperand)) { - int minValue = minOperand != null ? (int)minOperand : 0; - int maxValue = maxOperand != null ? (int)maxOperand : int.MaxValue; + int minValue = minOperand is not null ? (int)minOperand : 0; + int maxValue = maxOperand is not null ? (int)maxOperand : int.MaxValue; if (minValue >= maxValue) { @@ -425,8 +425,8 @@ protected override void BeginProcessing() } else if ((IsInt64(maxOperand) || IsInt(maxOperand)) && (IsInt64(minOperand) || IsInt(minOperand))) { - Int64 minValue = minOperand != null ? ((minOperand is Int64) ? (Int64)minOperand : (int)minOperand) : 0; - Int64 maxValue = maxOperand != null ? ((maxOperand is Int64) ? (Int64)maxOperand : (int)maxOperand) : Int64.MaxValue; + Int64 minValue = minOperand is not null ? ((minOperand is Int64) ? (Int64)minOperand : (int)minOperand) : 0; + Int64 maxValue = maxOperand is not null ? ((maxOperand is Int64) ? (Int64)maxOperand : (int)maxOperand) : Int64.MaxValue; if (minValue >= maxValue) { @@ -686,7 +686,7 @@ public int Next(int minValue, int maxValue) /// The array to be filled. internal void NextBytes(byte[] buffer) { - if (_cryptographicGenerator != null) + if (_cryptographicGenerator is not null) { _cryptographicGenerator.GetBytes(buffer); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetVerbCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetVerbCommand.cs index 766b38116c0..4f650f6c3fb 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetVerbCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetVerbCommand.cs @@ -51,7 +51,7 @@ protected override void ProcessRecord() foreach (Type type in verbTypes) { string groupName = type.Name.Substring(5); - if (this.Group != null) + if (this.Group is not null) { if (!SessionStateUtilities.CollectionContainsValue(this.Group, groupName, StringComparer.OrdinalIgnoreCase)) { @@ -63,7 +63,7 @@ protected override void ProcessRecord() { if (field.IsLiteral) { - if (this.Verb != null) + if (this.Verb is not null) { if (!SessionStateUtilities.MatchesAnyWildcardPattern(field.Name, matchingVerbs, false)) { 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..14510634a6d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Group-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Group-Object.cs @@ -41,7 +41,7 @@ internal static object ArrayToTuple(IList inputObjects) /// Tuple object. private static object ArrayToTuple(IList inputObjects, int startIndex) { - Diagnostics.Assert(inputObjects != null, "inputObjects is null"); + Diagnostics.Assert(inputObjects is not null, "inputObjects is null"); Diagnostics.Assert(inputObjects.Count > 0, "inputObjects is empty"); switch (inputObjects.Count - startIndex) @@ -145,7 +145,7 @@ private static string BuildName(List propValues) foreach (ObjectCommandPropertyValue propValue in propValues) { var propValuePropertyValue = propValue?.PropertyValue; - if (propValuePropertyValue != null) + if (propValuePropertyValue is not null) { if (propValuePropertyValue is ICollection propertyValueItems) { @@ -278,7 +278,7 @@ private static void DoGrouping( OrderByPropertyComparer orderByPropertyComparer) { var currentObjectOrderValues = currentObjectEntry.orderValues; - if (currentObjectOrderValues != null && currentObjectOrderValues.Count > 0) + if (currentObjectOrderValues is not null && currentObjectOrderValues.Count > 0) { object currentTupleObject = PSTuple.ArrayToTuple(currentObjectOrderValues); @@ -332,7 +332,7 @@ private static void DoOrderedGrouping( OrderByPropertyComparer orderByPropertyComparer) { var currentObjectOrderValues = currentObjectEntry.orderValues; - if (currentObjectOrderValues != null && currentObjectOrderValues.Count > 0) + if (currentObjectOrderValues is not null && currentObjectOrderValues.Count > 0) { object currentTupleObject = PSTuple.ArrayToTuple(currentObjectOrderValues); @@ -387,7 +387,7 @@ private void WriteNonTerminatingError(Exception exception, string resourceIdAndE /// protected override void ProcessRecord() { - if (InputObject != null && InputObject != AutomationNull.Value) + if (InputObject is not null && InputObject != AutomationNull.Value) { OrderByPropertyEntry currentEntry; @@ -407,7 +407,7 @@ protected override void ProcessRecord() ThrowTerminatingError(er); } - if (AsHashTable && !AsString && (Property != null && (Property.Length > 1 || _orderByProperty.MshParameterList.Count > 1))) + if (AsHashTable && !AsString && (Property is not null && (Property.Length > 1 || _orderByProperty.MshParameterList.Count > 1))) { ArgumentException ex = new ArgumentException(UtilityCommonStrings.GroupObjectSingleProperty); ErrorRecord er = new ErrorRecord(ex, "ArgumentException", ErrorCategory.InvalidArgument, Property); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs index 8cf01d456cb..14375897947 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs @@ -226,7 +226,7 @@ private PSModuleInfo CreateModule(string manifestFile) { ScriptBlock script = this.Context.Engine.ParseScriptBlock(importModuleScript, false); Collection results = script.Invoke(manifestFile, this.Session, this.Prefix, _disableNameChecking); - Dbg.Assert(results != null, "Import-Module should always succeed"); + Dbg.Assert(results is not null, "Import-Module should always succeed"); Dbg.Assert(results.Count == 1, "Import-Module should always succeed"); Dbg.Assert(results[0].BaseObject is PSModuleInfo, "Import-Module should always succeed"); return (PSModuleInfo)(results[0].BaseObject); @@ -303,7 +303,7 @@ protected override void BeginProcessing() } } - Dbg.Assert(manifestFile != null, "A psd1 file should always be generated"); + Dbg.Assert(manifestFile is not null, "A psd1 file should always be generated"); PSModuleInfo moduleInfo = this.CreateModule(manifestFile); this.RegisterModuleCleanUp(moduleInfo); @@ -456,7 +456,7 @@ public ModuleSpecification[] FullyQualifiedModule set { - if (value != null) + if (value is not null) { _moduleSpecifications = value; } @@ -716,7 +716,7 @@ private ErrorRecord GetErrorFromRemoteCommand(string commandName, RuntimeExcepti // handle recognized types of exceptions first // RemoteException remoteException = runtimeException as RemoteException; - if ((remoteException != null) && (remoteException.SerializedRemoteException != null)) + if ((remoteException is not null) && (remoteException.SerializedRemoteException is not null)) { if (Deserializer.IsInstanceOfType(remoteException.SerializedRemoteException, typeof(CommandNotFoundException))) { @@ -911,7 +911,7 @@ private List CommandSkipListFromServer ImplicitRemotingCommandsToSkipKey)) { _commandSkipListFromServer = new List(); - if (serverDeclaredListOfCommandsToSkip != null) + if (serverDeclaredListOfCommandsToSkip is not null) { _commandSkipListFromServer.AddRange(serverDeclaredListOfCommandsToSkip); } @@ -948,7 +948,7 @@ private bool IsCommandSkippedByServerDeclaration(string commandName) { if (commandToSkip.Equals(commandName, StringComparison.OrdinalIgnoreCase)) { - if (this.CommandName != null) + if (this.CommandName is not null) { foreach (string commandNameParameter in this.CommandName) { @@ -1016,11 +1016,11 @@ private T GetPropertyValue(string commandName, PSObject pso, string propertyN private List RehydrateList(string commandName, PSObject deserializedObject, string propertyName, Func itemRehydrator) { - Dbg.Assert(deserializedObject != null, "deserializedObject parameter != null"); + Dbg.Assert(deserializedObject is not null, "deserializedObject parameter is not null"); List result = null; PSPropertyInfo deserializedListProperty = deserializedObject.Properties[propertyName]; - if (deserializedListProperty != null) + if (deserializedListProperty is not null) { result = RehydrateList(commandName, deserializedListProperty.Value, itemRehydrator); } @@ -1038,7 +1038,7 @@ private List RehydrateList(string commandName, object deserializedList, Fu List result = null; ArrayList list = ConvertTo(commandName, deserializedList, true); - if (list != null) + if (list is not null) { result = new List(); foreach (object o in list) @@ -1054,8 +1054,8 @@ private List RehydrateList(string commandName, object deserializedList, Fu private Dictionary RehydrateDictionary(string commandName, PSObject deserializedObject, string propertyName, Func valueRehydrator) { - Dbg.Assert(deserializedObject != null, "deserializedObject parameter != null"); - Dbg.Assert(!string.IsNullOrEmpty(propertyName), "propertyName parameter != null"); + Dbg.Assert(deserializedObject is not null, "deserializedObject parameter is not null"); + Dbg.Assert(!string.IsNullOrEmpty(propertyName), "propertyName parameter is not null"); if (valueRehydrator is null) { @@ -1064,10 +1064,10 @@ private Dictionary RehydrateDictionary(string commandName, PSObject Dictionary result = new Dictionary(); PSPropertyInfo deserializedDictionaryProperty = deserializedObject.Properties[propertyName]; - if (deserializedDictionaryProperty != null) + if (deserializedDictionaryProperty is not null) { Hashtable deserializedDictionary = ConvertTo(commandName, deserializedDictionaryProperty.Value, true); - if (deserializedDictionary != null) + if (deserializedDictionary is not null) { foreach (DictionaryEntry deserializedItem in deserializedDictionary) { @@ -1150,7 +1150,7 @@ private static bool IsSafeTypeConstraint(Type type) { return true; } - else if (KnownTypes.GetTypeSerializationInfo(type) != null) + else if (KnownTypes.GetTypeSerializationInfo(type) is not null) { return true; } @@ -1180,7 +1180,7 @@ private bool IsSafeCommandMetadata(CommandMetadata commandMetadata) return false; } - if ((commandMetadata.DefaultParameterSetName != null) && + if ((commandMetadata.DefaultParameterSetName is not null) && !IsSafeNameOrIdentifier(commandMetadata.DefaultParameterSetName)) { this.WriteError(this.GetErrorSkippedUnsafeNameInMetadata( @@ -1193,7 +1193,7 @@ private bool IsSafeCommandMetadata(CommandMetadata commandMetadata) Dbg.Assert(commandMetadata.CommandType is null, "CommandType shouldn't get rehydrated"); Dbg.Assert(commandMetadata.ImplementsDynamicParameters == false, "Proxies shouldn't do dynamic parameters"); - if (commandMetadata.Parameters != null) + if (commandMetadata.Parameters is not null) { foreach (ParameterMetadata parameter in commandMetadata.Parameters.Values) { @@ -1215,7 +1215,7 @@ private bool IsSafeCommandMetadata(CommandMetadata commandMetadata) return false; } - if (parameter.Aliases != null) + if (parameter.Aliases is not null) { foreach (string alias in parameter.Aliases) { @@ -1230,7 +1230,7 @@ private bool IsSafeCommandMetadata(CommandMetadata commandMetadata) } } - if (parameter.ParameterSets != null) + if (parameter.ParameterSets is not null) { foreach (KeyValuePair setPair in parameter.ParameterSets) { @@ -1390,9 +1390,9 @@ private void AddRemoteCommandMetadata( Dictionary alias2resolvedCommandName, PSObject remoteCommandInfo) { - Dbg.Assert(name2commandMetadata != null, "name2commandMetadata parameter != null"); - Dbg.Assert(alias2resolvedCommandName != null, "alias2resolvedCommandName parameter != null"); - Dbg.Assert(remoteCommandInfo != null, "remoteCommandInfo parameter != null"); + Dbg.Assert(name2commandMetadata is not null, "name2commandMetadata parameter is not null"); + Dbg.Assert(alias2resolvedCommandName is not null, "alias2resolvedCommandName parameter is not null"); + Dbg.Assert(remoteCommandInfo is not null, "remoteCommandInfo parameter is not null"); string resolvedCommandName; CommandMetadata commandMetadata = RehydrateCommandMetadata(remoteCommandInfo, out resolvedCommandName); @@ -1401,7 +1401,7 @@ private void AddRemoteCommandMetadata( return; } - if (resolvedCommandName != null && !IsSafeNameOrIdentifier(commandMetadata.Name)) + if (resolvedCommandName is not null && !IsSafeNameOrIdentifier(commandMetadata.Name)) { this.WriteError(this.GetErrorSkippedUnsafeCommandName(resolvedCommandName)); return; @@ -1428,7 +1428,7 @@ private void AddRemoteCommandMetadata( } } - if (resolvedCommandName != null) + if (resolvedCommandName is not null) { alias2resolvedCommandName[commandMetadata.Name] = resolvedCommandName; commandMetadata.Name = resolvedCommandName; @@ -1459,8 +1459,8 @@ private bool IsSafeTypeDefinition(ExtendedTypeDefinition typeDefinition) private void AddRemoteTypeDefinition(IList listOfTypeDefinitions, PSObject remoteTypeDefinition) { - Dbg.Assert(listOfTypeDefinitions != null, "listOfTypeDefinitions parameter != null"); - Dbg.Assert(remoteTypeDefinition != null, "remoteTypeDefinition parameter != null"); + Dbg.Assert(listOfTypeDefinitions is not null, "listOfTypeDefinitions parameter is not null"); + Dbg.Assert(remoteTypeDefinition is not null, "remoteTypeDefinition parameter is not null"); ExtendedTypeDefinition typeDefinition = ConvertTo("Get-FormatData", remoteTypeDefinition); if (!IsSafeTypeDefinition(typeDefinition)) @@ -1567,7 +1567,7 @@ private PowerShell BuildPowerShellForGetFormatData() // For remote PS version 5.1 and greater, we need to include the new -PowerShellVersion parameter RemoteRunspace remoteRunspace = Session.Runspace as RemoteRunspace; - if ((remoteRunspace != null) && (remoteRunspace.ServerVersion != null) && + if ((remoteRunspace is not null) && (remoteRunspace.ServerVersion is not null) && (remoteRunspace.ServerVersion >= new Version(5, 1))) { powerShell.AddParameter("PowerShellVersion", PSVersionInfo.PSVersion); @@ -1654,7 +1654,7 @@ private PowerShell BuildPowerShellForGetCommand() powerShell.AddCommand("Get-Command"); powerShell.AddParameter("CommandType", this.CommandType); - if (this.CommandName != null) + if (this.CommandName is not null) { powerShell.AddParameter("Name", this.CommandName); } @@ -1914,9 +1914,9 @@ internal ImplicitRemotingCodeGenerator( Guid moduleGuid, InvocationInfo invocationInfo) { - Dbg.Assert(remoteRunspaceInfo != null, "Caller should validate remoteRunspaceInfo != null"); - Dbg.Assert(moduleGuid != null, "Caller should validate moduleGuid != null"); - Dbg.Assert(invocationInfo != null, "Caller should validate invocationInfo != null"); + Dbg.Assert(remoteRunspaceInfo is not null, "Caller should validate remoteRunspaceInfo is not null"); + Dbg.Assert(moduleGuid is not null, "Caller should validate moduleGuid is not null"); + Dbg.Assert(invocationInfo is not null, "Caller should validate invocationInfo is not null"); _remoteRunspaceInfo = remoteRunspaceInfo; _moduleGuid = moduleGuid; @@ -1934,19 +1934,19 @@ internal ImplicitRemotingCodeGenerator( private string GetConnectionString() { WSManConnectionInfo connectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as WSManConnectionInfo; - if (connectionInfo != null) + if (connectionInfo is not null) { return connectionInfo.ConnectionUri.ToString(); } VMConnectionInfo vmConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as VMConnectionInfo; - if (vmConnectionInfo != null) + if (vmConnectionInfo is not null) { return vmConnectionInfo.ComputerName; } ContainerConnectionInfo containerConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as ContainerConnectionInfo; - if (containerConnectionInfo != null) + if (containerConnectionInfo is not null) { return containerConnectionInfo.ComputerName; } @@ -2224,9 +2224,9 @@ private PSPrimitiveDictionary GetApplicationArguments() { RemoteRunspace remoteRunspace = _remoteRunspaceInfo.Runspace as RemoteRunspace; - Dbg.Assert(remoteRunspace != null, "PSSessionInfo should refer to a *remote* runspace"); - Dbg.Assert(remoteRunspace.RunspacePool != null, "All remote runspaces are implemented using a runspace pool"); - Dbg.Assert(remoteRunspace.RunspacePool != null, "All remote runspace pools have an internal implementation helper"); + Dbg.Assert(remoteRunspace is not null, "PSSessionInfo should refer to a *remote* runspace"); + Dbg.Assert(remoteRunspace.RunspacePool is not null, "All remote runspaces are implemented using a runspace pool"); + Dbg.Assert(remoteRunspace.RunspacePool is not null, "All remote runspace pools have an internal implementation helper"); return remoteRunspace.RunspacePool.RemoteRunspacePoolInternal.ApplicationArguments; } @@ -2236,7 +2236,7 @@ private string GenerateNewPSSessionOption() StringBuilder result = new StringBuilder("& $script:NewPSSessionOption "); RunspaceConnectionInfo runspaceConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as RunspaceConnectionInfo; - if (runspaceConnectionInfo != null) + if (runspaceConnectionInfo is not null) { result.AppendFormat(null, "-Culture '{0}' ", CodeGeneration.EscapeSingleQuotedStringContent(runspaceConnectionInfo.Culture.ToString())); result.AppendFormat(null, "-UICulture '{0}' ", CodeGeneration.EscapeSingleQuotedStringContent(runspaceConnectionInfo.UICulture.ToString())); @@ -2248,7 +2248,7 @@ private string GenerateNewPSSessionOption() } WSManConnectionInfo wsmanConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as WSManConnectionInfo; - if (wsmanConnectionInfo != null) + if (wsmanConnectionInfo is not null) { if (!wsmanConnectionInfo.UseCompression) { result.Append("-NoCompression "); } @@ -2297,7 +2297,7 @@ private string GenerateNewPSSessionOption() } PSPrimitiveDictionary applicationArguments = GetApplicationArguments(); - if (applicationArguments != null) + if (applicationArguments is not null) { result.Append("-ApplicationArguments $("); result.Append("& $script:ImportCliXml -Path $("); @@ -2508,7 +2508,7 @@ private string GenerateReimportingOfModules() private string GenerateNewRunspaceExpression() { VMConnectionInfo vmConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as VMConnectionInfo; - if (vmConnectionInfo != null) + if (vmConnectionInfo is not null) { string vmConfigurationName = vmConnectionInfo.ConfigurationName; return string.Format( @@ -2521,7 +2521,7 @@ private string GenerateNewRunspaceExpression() else { ContainerConnectionInfo containerConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as ContainerConnectionInfo; - if (containerConnectionInfo != null) + if (containerConnectionInfo is not null) { string containerConfigurationName = containerConnectionInfo.ContainerProc.ConfigurationName; return string.Format( @@ -2567,7 +2567,7 @@ private string GenerateConnectionStringForNewRunspace() if (connectionInfo is null) { VMConnectionInfo vmConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as VMConnectionInfo; - if (vmConnectionInfo != null) + if (vmConnectionInfo is not null) { return string.Format(CultureInfo.InvariantCulture, VMIdParameterTemplate, @@ -2575,7 +2575,7 @@ private string GenerateConnectionStringForNewRunspace() } ContainerConnectionInfo containerConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as ContainerConnectionInfo; - if (containerConnectionInfo != null) + if (containerConnectionInfo is not null) { return string.Format(CultureInfo.InvariantCulture, ContainerIdParameterTemplate, @@ -2631,7 +2631,7 @@ private string GenerateAuthenticationMechanismParameter() { // comment in newrunspacecommand.cs says that -CertificateThumbprint // and AuthenticationMechanism are mutually exclusive - if (_remoteRunspaceInfo.Runspace.ConnectionInfo.CertificateThumbprint != null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo.CertificateThumbprint is not null) { return string.Empty; } @@ -3028,9 +3028,9 @@ internal List GenerateProxyModule( { List result = new List(); - Dbg.Assert(moduleRootDirectory != null, "Caller should validate moduleRootDirectory != null"); + Dbg.Assert(moduleRootDirectory is not null, "Caller should validate moduleRootDirectory is not null"); Dbg.Assert(Directory.Exists(moduleRootDirectory.FullName), "Caller should validate moduleRootDirectory exists"); - Dbg.Assert(encoding != null, "Caller should validate encoding != null"); + Dbg.Assert(encoding is not null, "Caller should validate encoding is not null"); string baseName = Path.Combine(moduleRootDirectory.FullName, fileNamePrefix); FileMode fileMode = force ? FileMode.OpenOrCreate : FileMode.CreateNew; @@ -3115,7 +3115,7 @@ internal List GenerateProxyModule( } PSPrimitiveDictionary applicationArguments = GetApplicationArguments(); - if (applicationArguments != null) + if (applicationArguments is not null) { string applicationArgumentsFile = Path.Combine(moduleRootDirectory.FullName, "ApplicationArguments.xml"); result.Add(applicationArgumentsFile); 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..cf44efe2eab 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Import-LocalizedData.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Import-LocalizedData.cs @@ -184,7 +184,7 @@ protected override void ProcessRecord() Context.LanguageMode = oldLanguageMode; } - if (_bindingVariable != null) + if (_bindingVariable is not null) { VariablePath variablePath = new VariablePath(_bindingVariable); if (variablePath.IsUnscopedVariable) @@ -255,7 +255,7 @@ private string GetFilePath() if (string.IsNullOrEmpty(dir)) { - if (InvocationExtent != null && !string.IsNullOrEmpty(InvocationExtent.File)) + if (InvocationExtent is not null && !string.IsNullOrEmpty(InvocationExtent.File)) { dir = Path.GetDirectoryName(InvocationExtent.File); } @@ -302,7 +302,7 @@ private string GetFilePath() CultureInfo currentCulture = culture; string filePath; string fullFileName = fileName + ".psd1"; - while (currentCulture != null && !string.IsNullOrEmpty(currentCulture.Name)) + while (currentCulture is not null && !string.IsNullOrEmpty(currentCulture.Name)) { filePath = Path.Combine(dir, currentCulture.Name, fullFileName); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportAliasCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportAliasCommand.cs index 83b47dda771..cae6e7d473f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportAliasCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportAliasCommand.cs @@ -134,7 +134,7 @@ protected override void ProcessRecord() existingAlias = SessionState.Internal.GetAliasAtScope(alias.Name, Scope); } - if (existingAlias != null) + if (existingAlias is not null) { // Write an error for aliases that aren't visible... try @@ -217,7 +217,7 @@ protected override void ProcessRecord() // Write the alias to the pipeline if PassThru was specified - if (PassThru && result != null) + if (PassThru && result is not null) { WriteObject(result); } @@ -298,7 +298,7 @@ private Collection GetAliasesFromFile(bool isLiteralPath) Int64 lineNumber = 0; string line = null; - while ((line = reader.ReadLine()) != null) + while ((line = reader.ReadLine()) is not null) { ++lineNumber; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportPowerShellDataFile.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportPowerShellDataFile.cs index 694e82686be..6277c394d0b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportPowerShellDataFile.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportPowerShellDataFile.cs @@ -59,7 +59,7 @@ protected override void ProcessRecord() else { var data = ast.Find(a => a is HashtableAst, false); - if (data != null) + if (data is not null) { WriteObject(data.SafeGetValue()); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/InvokeExpressionCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/InvokeExpressionCommand.cs index d51f20f8704..cd6f0ff5726 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/InvokeExpressionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/InvokeExpressionCommand.cs @@ -31,7 +31,7 @@ public sealed /// protected override void ProcessRecord() { - Diagnostics.Assert(Command != null, "Command is null"); + Diagnostics.Assert(Command is not null, "Command is null"); ScriptBlock myScriptBlock = InvokeCommand.NewScriptBlock(Command); 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..34f3ffe999b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Join-String.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Join-String.cs @@ -107,11 +107,11 @@ protected override void BeginProcessing() /// protected override void ProcessRecord() { - if (InputObject != null) + if (InputObject is not null) { foreach (PSObject inputObject in InputObject) { - if (inputObject != null && inputObject != AutomationNull.Value) + if (inputObject is not null && inputObject != AutomationNull.Value) { var inputValue = Property is null ? inputObject diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MarkdownOptionCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MarkdownOptionCommands.cs index 9182060a6ae..55d308e1a36 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MarkdownOptionCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MarkdownOptionCommands.cs @@ -283,7 +283,7 @@ static PSMarkdownOptionInfoCache() internal static PSMarkdownOptionInfo Get(CommandInfo command) { // If we have the moduleInfo then store are module scope variable - if (command.Module != null) + if (command.Module is not null) { return command.Module.SessionState.PSVariable.GetValue(MarkdownOptionInfoVariableName, new PSMarkdownOptionInfo()) as PSMarkdownOptionInfo; } @@ -305,7 +305,7 @@ internal static PSMarkdownOptionInfo Get(CommandInfo command) internal static PSMarkdownOptionInfo Set(CommandInfo command, PSMarkdownOptionInfo optionInfo) { // If we have the moduleInfo then store are module scope variable - if (command.Module != null) + if (command.Module is not null) { command.Module.SessionState.PSVariable.Set(MarkdownOptionInfoVariableName, optionInfo); return optionInfo; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs index 17147af4c6d..f1ac238f4e3 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs @@ -265,7 +265,7 @@ public string ToString(string directory) /// The string representation of the match object. private string ToString(string directory, string line) { - string displayPath = (directory != null) ? RelativePath(directory) : _path; + string displayPath = (directory is not null) ? RelativePath(directory) : _path; // Just return a single line if the user didn't // enable context-tracking. @@ -378,7 +378,7 @@ internal MatchInfo Clone() // fields that need it. MatchInfo clone = (MatchInfo)this.MemberwiseClone(); - if (clone.Context != null) + if (clone.Context is not null) { clone.Context = (MatchInfoContext)clone.Context.Clone(); } @@ -743,11 +743,11 @@ public void TrackEOF() /// private void UpdateQueue() { - if (_matchInfo != null) + if (_matchInfo is not null) { _emitQueue.Add(_matchInfo); - if (_matchInfo.Context != null) + if (_matchInfo.Context is not null) { _matchInfo.Context.DisplayPreContext = _collectedPreContext.ToArray(); _matchInfo.Context.DisplayPostContext = _collectedPostContext.ToArray(); @@ -896,7 +896,7 @@ private void EmitAllInRange(int startIndex, int endIndex) for (int i = startIndex; i <= endIndex; i++) { MatchInfo match = _collectedContext[i].Match; - if (match != null) + if (match is not null) { int preStart = Math.Max(i - _preContext, 0); int postLength = Math.Min(_postContext, _collectedContext.Count - i - 1); @@ -955,7 +955,7 @@ private void UpdateQueue() /// The length of the postContext range. private void Emit(MatchInfo match, int preStartIndex, int preLength, int postStartIndex, int postLength) { - if (match.Context != null) + if (match.Context is not null) { match.Context.PreContext = CopyContext(preStartIndex, preLength); match.Context.PostContext = CopyContext(postStartIndex, postLength); @@ -1475,7 +1475,7 @@ protected override void ProcessRecord() // We may only have directories when we have resolved wildcards var expandedPathsMaybeDirectory = false; List expandedPaths = null; - if (Path != null) + if (Path is not null) { expandedPaths = ResolveFilePaths(Path, _isLiteralPath); if (expandedPaths is null) @@ -1494,7 +1494,7 @@ protected override void ProcessRecord() } } - if (expandedPaths != null) + if (expandedPaths is not null) { foreach (var filename in expandedPaths) { @@ -1595,7 +1595,7 @@ private bool ProcessFile(string filename) // Read and display lines from the file until the end of // the file is reached. - while ((line = sr.ReadLine()) != null) + while ((line = sr.ReadLine()) is not null) { lineNo++; @@ -1723,7 +1723,7 @@ private bool DoMatch(string operandString, out MatchInfo matchResult) private bool DoMatch(object operand, out MatchInfo matchResult, out string operandString) { MatchInfo matchInfo = operand as MatchInfo; - if (matchInfo != null) + if (matchInfo is not null) { // We're operating in filter mode. Match // against the provided MatchInfo's line. @@ -1874,13 +1874,13 @@ private bool DoMatchWorker(string operandString, MatchInfo matchInfo, out MatchI { // if we were passed a MatchInfo object as the operand, // we're operating in filter mode. - if (matchInfo != null) + if (matchInfo is not null) { // If the original MatchInfo was tracking context, // we need to copy it and disable display context, // since we can't guarantee it will be displayed // correctly when filtered. - if (matchInfo.Context != null) + if (matchInfo.Context is not null) { matchResult = matchInfo.Clone(); matchResult.Context.DisplayPreContext = new string[] { }; @@ -2005,7 +2005,7 @@ public override object Transform(EngineIntrinsics engineIntrinsics, object input object element = argList[i]; mso = element as PSObject; - if (mso != null) + if (mso is not null) { element = mso.BaseObject; } @@ -2019,7 +2019,7 @@ public override object Transform(EngineIntrinsics engineIntrinsics, object input // Handle the singleton case... fileInfo = result as FileInfo; - if (fileInfo != null) + if (fileInfo is not null) { return fileInfo.FullName; } @@ -2040,7 +2040,7 @@ private bool MeetsIncludeExcludeCriteria(string filename) bool ok = false; // see if the file is on the include list... - if (_include != null) + if (_include is not null) { foreach (WildcardPattern patternItem in _include) { @@ -2062,7 +2062,7 @@ private bool MeetsIncludeExcludeCriteria(string filename) } // now see if it's on the exclude list... - if (_exclude != null) + if (_exclude is not null) { foreach (WildcardPattern patternItem in _exclude) { 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..a87c01fa04f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs @@ -625,10 +625,10 @@ private object Compare(object objValue, object statMinOrMaxValue, bool isMin) int factor = isMin ? 1 : -1; double temp; - currentValue = ((objValue != null) && LanguagePrimitives.TryConvertTo(objValue, out temp)) ? temp : currentValue; - statValue = ((statValue != null) && LanguagePrimitives.TryConvertTo(statValue, out temp)) ? temp : statValue; + currentValue = ((objValue is not null) && LanguagePrimitives.TryConvertTo(objValue, out temp)) ? temp : currentValue; + statValue = ((statValue is not null) && LanguagePrimitives.TryConvertTo(statValue, out temp)) ? temp : statValue; - if (currentValue != null && statValue != null && !currentValue.GetType().Equals(statValue.GetType())) + if (currentValue is not null && statValue is not null && !currentValue.GetType().Equals(statValue.GetType())) { currentValue = PSObject.AsPSObject(currentValue).ToString(); statValue = PSObject.AsPSObject(statValue).ToString(); @@ -788,7 +788,7 @@ private void AnalyzeNumber(double numValue, Statistics stat) /// The error ID to write. private void WritePropertyNotFoundError(string propertyName, string errorId) { - Diagnostics.Assert(Property != null, "no property and no InputObject should have been addressed"); + Diagnostics.Assert(Property is not null, "no property and no InputObject should have been addressed"); ErrorRecord errorRecord = new ErrorRecord( PSTraceSource.NewArgumentException("Property"), errorId, @@ -816,7 +816,7 @@ protected override void EndProcessing() foreach (string propertyName in _statistics.Keys) { Statistics stat = _statistics[propertyName]; - if (stat.count == 0 && Property != null) + if (stat.count == 0 && Property is not null) { // Why are there two different ids for this error? string errorId = (IsMeasuringGeneric) ? "GenericMeasurePropertyNotFound" : "TextMeasurePropertyNotFound"; @@ -842,7 +842,7 @@ protected override void EndProcessing() mi = CreateTextMeasureInfo(stat); // Set common properties. - if (Property != null) + if (Property is not null) mi.Property = propertyName; WriteObject(mi); @@ -879,7 +879,7 @@ private MeasureInfo CreateGenericMeasureInfo(Statistics stat, bool shouldUseGene if (_measureMax) { - if (shouldUseGenericMeasureInfo && (stat.max != null)) + if (shouldUseGenericMeasureInfo && (stat.max is not null)) { double temp; LanguagePrimitives.TryConvertTo(stat.max, out temp); @@ -893,7 +893,7 @@ private MeasureInfo CreateGenericMeasureInfo(Statistics stat, bool shouldUseGene if (_measureMin) { - if (shouldUseGenericMeasureInfo && (stat.min != null)) + if (shouldUseGenericMeasureInfo && (stat.min is not null)) { double temp; LanguagePrimitives.TryConvertTo(stat.min, out temp); @@ -912,12 +912,12 @@ private MeasureInfo CreateGenericMeasureInfo(Statistics stat, bool shouldUseGene gmi.Sum = sum; gmi.Average = average; gmi.StandardDeviation = StandardDeviation; - if (max != null) + if (max is not null) { gmi.Maximum = (double)max; } - if (min != null) + if (min is not null) { gmi.Minimum = (double)min; } 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..9e03fb33a90 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs @@ -145,7 +145,7 @@ protected override void BeginProcessing() // these complications in Exception handling are aim to make error messages better. if (e is InvalidCastException || e is ArgumentException) { - if (e.InnerException != null && e.InnerException is TypeResolver.AmbiguousTypeException) + if (e.InnerException is not null && e.InnerException is TypeResolver.AmbiguousTypeException) { ThrowTerminatingError( new ErrorRecord( @@ -171,7 +171,7 @@ protected override void BeginProcessing() throw; } - Diagnostics.Assert(type != null, "LanguagePrimitives.TryConvertTo failed but returned true"); + Diagnostics.Assert(type is not null, "LanguagePrimitives.TryConvertTo failed but returned true"); if (type.IsByRefLike) { @@ -205,10 +205,10 @@ protected override void BeginProcessing() if (ArgumentList is null || ArgumentList.Length == 0) { ConstructorInfo ci = type.GetConstructor(Type.EmptyTypes); - if (ci != null && ci.IsPublic) + if (ci is not null && ci.IsPublic) { _newObject = CallConstructor(type, new ConstructorInfo[] { ci }, new object[] { }); - if (_newObject != null && Property != null) + if (_newObject is not null && Property is not null) { // The method invocation is disabled for "Hashtable to Object conversion" (Win8:649519), but we need to keep it enabled for New-Object for compatibility to PSv2 _newObject = LanguagePrimitives.SetObjectProperties(_newObject, Property, type, CreateMemberNotFoundError, CreateMemberSetValueError, enableMethodCall: true); @@ -224,7 +224,7 @@ protected override void BeginProcessing() try { _newObject = Activator.CreateInstance(type); - if (_newObject != null && Property != null) + if (_newObject is not null && Property is not null) { // Win8:649519 _newObject = LanguagePrimitives.SetObjectProperties(_newObject, Property, type, CreateMemberNotFoundError, CreateMemberSetValueError, enableMethodCall: true); @@ -250,7 +250,7 @@ protected override void BeginProcessing() if (ctorInfos.Length != 0) { _newObject = CallConstructor(type, ctorInfos, ArgumentList); - if (_newObject != null && Property != null) + if (_newObject is not null && Property is not null) { // Win8:649519 _newObject = LanguagePrimitives.SetObjectProperties(_newObject, Property, type, CreateMemberNotFoundError, CreateMemberSetValueError, enableMethodCall: true); @@ -314,7 +314,7 @@ protected override void BeginProcessing() } } - if (comObject != null && Property != null) + if (comObject is not null && Property is not null) { // Win8:649519 comObject = LanguagePrimitives.SetObjectProperties(comObject, Property, type, CreateMemberNotFoundError, CreateMemberSetValueError, enableMethodCall: true); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewAliasCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewAliasCommand.cs index 3c95ebbc7de..10130a1eea3 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewAliasCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewAliasCommand.cs @@ -36,7 +36,7 @@ protected override void ProcessRecord() existingAlias = SessionState.Internal.GetAliasAtScope(Name, Scope); } - if (existingAlias != null) + if (existingAlias is not null) { // Throw if alias exists and is private... SessionState.ThrowIfNotVisible(this.CommandOrigin, existingAlias); @@ -121,7 +121,7 @@ protected override void ProcessRecord() // Write the alias to the pipeline if PassThru was specified - if (PassThru && result != null) + if (PassThru && result is not null) { WriteObject(result); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewEventCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewEventCommand.cs index 34c95a116f3..1d8271b3742 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewEventCommand.cs @@ -69,7 +69,7 @@ public PSObject[] EventArguments set { - if (_eventArguments != null) + if (_eventArguments is not null) { _eventArguments = value; } @@ -107,13 +107,13 @@ protected override void EndProcessing() object[] baseEventArgs = null; // Get the BaseObject from the event arguments - if (_eventArguments != null) + if (_eventArguments is not null) { baseEventArgs = new object[_eventArguments.Length]; int loopCounter = 0; foreach (PSObject eventArg in _eventArguments) { - if (eventArg != null) + if (eventArg is not null) baseEventArgs[loopCounter] = eventArg.BaseObject; loopCounter++; @@ -121,7 +121,7 @@ protected override void EndProcessing() } object messageSender = null; - if (_sender != null) { messageSender = _sender.BaseObject; } + if (_sender is not null) { messageSender = _sender.BaseObject; } // And then generate the event WriteObject(Events.GenerateEvent(_sourceIdentifier, messageSender, baseEventArgs, _messageData, true, false)); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs index c782bef104e..649dce6e383 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs @@ -97,7 +97,7 @@ public override bool Equals(object inputObject) return true; } - if (baseObject != null && inComingbaseObjectPropertyValue != null) + if (baseObject is not null && inComingbaseObjectPropertyValue is not null) { return baseObject.ToString().Equals(inComingbaseObjectPropertyValue.ToString(), StringComparison.OrdinalIgnoreCase); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs index 258cf507091..8dd70ecad2d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs @@ -57,7 +57,7 @@ public class ObjectCmdletBase : PSCmdlet [System.Diagnostics.CodeAnalysis.SuppressMessage("GoldMan", "#pw17903:UseOfLCID", Justification = "The CultureNumber is only used if the property has been set with a hex string starting with 0x")] public string Culture { - get { return _cultureInfo != null ? _cultureInfo.ToString() : null; } + get { return _cultureInfo is not null ? _cultureInfo.ToString() : null; } set { @@ -168,7 +168,7 @@ internal CultureInfo ConvertedCulture /// protected override void ProcessRecord() { - if (InputObject != null && InputObject != AutomationNull.Value) + if (InputObject is not null && InputObject != AutomationNull.Value) { InputObjects.Add(InputObject); } @@ -217,12 +217,12 @@ private static void ProcessExpressionParameter( new ParameterProcessor(new SortObjectExpressionParameterDefinition()) : new ParameterProcessor(new GroupObjectExpressionParameterDefinition()); - if (expr is null && inputObjects != null && inputObjects.Count > 0) + if (expr is null && inputObjects is not null && inputObjects.Count > 0) { expr = GetDefaultKeyPropertySet(inputObjects[0]); } - if (expr != null) + if (expr is not null) { List unexpandedParameterList = processor.ProcessParameters(expr, invocationContext); mshParameterList = ExpandExpressions(inputObjects, unexpandedParameterList); @@ -241,7 +241,7 @@ internal void ProcessExpressionParameter( new ParameterProcessor(new SortObjectExpressionParameterDefinition()) : new ParameterProcessor(new GroupObjectExpressionParameterDefinition()); - if (expr != null) + if (expr is not null) { if (_unexpandedParameterList is null) { @@ -274,7 +274,7 @@ private static List ExpandExpressions(List inputObjects, { List expandedParameterList = new List(); - if (unexpandedParameterList != null) + if (unexpandedParameterList is not null) { foreach (MshParameter unexpandedParameter in unexpandedParameterList) { @@ -286,7 +286,7 @@ private static List ExpandExpressions(List inputObjects, else { SortedDictionary expandedPropertyNames = new SortedDictionary(StringComparer.OrdinalIgnoreCase); - if (inputObjects != null) + if (inputObjects is not null) { foreach (object inputObject in inputObjects) { @@ -321,7 +321,7 @@ private static List ExpandExpressions(List inputObjects, // match property names on the incoming objects. private static void ExpandExpressions(PSObject inputObject, List UnexpandedParametersWithWildCardPattern, List expandedParameterList) { - if (UnexpandedParametersWithWildCardPattern != null) + if (UnexpandedParametersWithWildCardPattern is not null) { foreach (MshParameter unexpandedParameter in UnexpandedParametersWithWildCardPattern) { @@ -406,7 +406,7 @@ List mshParameterList private static bool isOrderEntryKeyDefined(object orderEntryKey) { - return orderEntryKey != null && orderEntryKey != AutomationNull.Value; + return orderEntryKey is not null && orderEntryKey != AutomationNull.Value; } private static OrderByPropertyComparer CreateComparer( @@ -422,7 +422,7 @@ private static OrderByPropertyComparer CreateComparer( } bool?[] ascendingOverrides = null; - if (mshParameterList != null && mshParameterList.Count != 0) + if (mshParameterList is not null && mshParameterList.Count != 0) { ascendingOverrides = new bool?[mshParameterList.Count]; for (int k = 0; k < ascendingOverrides.Length; k++) @@ -472,7 +472,7 @@ internal OrderByProperty( bool caseSensitive ) { - Diagnostics.Assert(cmdlet != null, "cmdlet must be an instance"); + Diagnostics.Assert(cmdlet is not null, "cmdlet must be an instance"); ProcessExpressionParameter(inputObjects, cmdlet, expr, out _mshParameterList); OrderMatrix = CreateOrderMatrix(cmdlet, inputObjects, _mshParameterList); @@ -502,9 +502,9 @@ internal OrderByPropertyEntry CreateOrderByPropertyEntry( bool isCaseSensitive, CultureInfo cultureInfo) { - Diagnostics.Assert(cmdlet != null, "cmdlet must be an instance"); + Diagnostics.Assert(cmdlet is not null, "cmdlet must be an instance"); - if (_unExpandedParametersWithWildCardPattern != null) + if (_unExpandedParametersWithWildCardPattern is not null) { ExpandExpressions(inputObject, _unExpandedParametersWithWildCardPattern, _mshParameterList); } @@ -543,8 +543,8 @@ internal static class OrderByPropertyEntryEvaluationHelper internal static OrderByPropertyEntry ProcessObject(PSObject inputObject, List mshParameterList, List errors, List propertyNotFoundMsgs, bool isCaseSensitive = false, CultureInfo cultureInfo = null, int originalIndex = -1) { - Diagnostics.Assert(errors != null, "errors cannot be null!"); - Diagnostics.Assert(propertyNotFoundMsgs != null, "propertyNotFoundMsgs cannot be null!"); + Diagnostics.Assert(errors is not null, "errors cannot be null!"); + Diagnostics.Assert(propertyNotFoundMsgs is not null, "propertyNotFoundMsgs cannot be null!"); OrderByPropertyEntry entry = new OrderByPropertyEntry(); entry.inputObject = inputObject; entry.originalIndex = originalIndex; @@ -683,7 +683,7 @@ internal static OrderByPropertyComparer CreateComparer(List result = Host.UI.Prompt(string.Empty, string.Empty, fdc); // Result can be null depending on the host implementation. One typical // example of a null return is for a canceled dialog. - if (result != null) + if (result is not null) { foreach (PSObject o in result.Values) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveAliasCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveAliasCommand.cs index 7b44a0c2664..9de2ed18a3a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveAliasCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveAliasCommand.cs @@ -56,7 +56,7 @@ protected override void ProcessRecord() existingAlias = SessionState.Internal.GetAliasAtScope(aliasName, Scope); } - if (existingAlias != null) + if (existingAlias is not null) { SessionState.Internal.RemoveAlias(aliasName, Force); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveEventCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveEventCommand.cs index 14acbbdf6af..9dc2fb915b0 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveEventCommand.cs @@ -29,7 +29,7 @@ public string SourceIdentifier { _sourceIdentifier = value; - if (value != null) + if (value is not null) { _matchPattern = WildcardPattern.Get(value, WildcardOptions.IgnoreCase); } @@ -79,7 +79,7 @@ protected override void ProcessRecord() PSEventArgs currentEvent = currentEvents[eventCounter - 1]; // If they specified a event identifier and we don't match, continue - if ((_sourceIdentifier != null) && + if ((_sourceIdentifier is not null) && (!_matchPattern.IsMatch(currentEvent.SourceIdentifier))) { continue; @@ -107,7 +107,7 @@ protected override void ProcessRecord() // Generate an error if we couldn't find the subscription identifier, // and no globbing was done. - if ((_sourceIdentifier != null) && + if ((_sourceIdentifier is not null) && (!WildcardPattern.ContainsWildcardCharacters(_sourceIdentifier)) && (!foundMatch)) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RunspaceAttribute.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RunspaceAttribute.cs index ee976bd562d..260ae7cb080 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RunspaceAttribute.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RunspaceAttribute.cs @@ -43,7 +43,7 @@ public override object Transform(EngineIntrinsics engineIntrinsics, object input // Try to coerce the input as a runspace Runspace runspace = LanguagePrimitives.FromObjectAs(inputData); - if (runspace != null) + if (runspace is not null) { return runspace; } 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..0a311f017f9 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs @@ -340,7 +340,7 @@ private void ProcessExpressionParameter() TerminatingErrorContext invocationContext = new TerminatingErrorContext(this); ParameterProcessor processor = new ParameterProcessor(new SelectObjectExpressionParameterDefinition()); - if ((Property != null) && (Property.Length != 0)) + if ((Property is not null) && (Property.Length != 0)) { // Build property list taking into account the wildcards and @{name=;expression=} @@ -357,7 +357,7 @@ private void ProcessExpressionParameter() _expandMshParameterList = processor.ProcessParameters(new string[] { ExpandProperty }, invocationContext); } - if (ExcludeProperty != null) + if (ExcludeProperty is not null) { _exclusionFilter = new PSPropertyExpressionFilter(ExcludeProperty); // ExcludeProperty implies -Property * for better UX @@ -464,7 +464,7 @@ private void ProcessParameter(MshParameter p, PSObject inputObject, List addedNoteProperties) { - Diagnostics.Assert(obj != null, "This command should never write null"); + Diagnostics.Assert(obj is not null, "This command should never write null"); if (!_unique) { @@ -669,7 +669,7 @@ private void SetPSCustomObject(PSObject psObj, bool newPSObject) private void ProcessObjectAndHandleErrors(PSObject pso) { - Diagnostics.Assert(pso != null, "Caller should verify pso != null"); + Diagnostics.Assert(pso is not null, "Caller should verify pso is not null"); try { @@ -700,7 +700,7 @@ protected override void BeginProcessing() /// protected override void ProcessRecord() { - if (InputObject != AutomationNull.Value && InputObject != null) + if (InputObject != AutomationNull.Value && InputObject is not null) { if (_indexSpecified) { @@ -710,7 +710,7 @@ protected override void ProcessRecord() { _selectObjectQueue.Enqueue(InputObject); PSObject streamingInputObject = _selectObjectQueue.StreamingDequeue(); - if (streamingInputObject != null) + if (streamingInputObject is not null) { ProcessObjectAndHandleErrors(streamingInputObject); } @@ -822,7 +822,7 @@ protected override void EndProcessing() } } - if (_uniques != null) + if (_uniques is not null) { foreach (UniquePSObjectHelper obj in _uniques) { 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..03612f72d9f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Send-MailMessage.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Send-MailMessage.cs @@ -233,19 +233,19 @@ protected override void BeginProcessing() AddAddressesToMailMessage(To, "to"); // Set the BCC address of the mail message - if (Bcc != null) + if (Bcc is not null) { AddAddressesToMailMessage(Bcc, "bcc"); } // Set the CC address of the mail message - if (Cc != null) + if (Cc is not null) { AddAddressesToMailMessage(Cc, "cc"); } // Set the Reply-To address of the mail message - if (ReplyTo != null) + if (ReplyTo is not null) { AddAddressesToMailMessage(ReplyTo, "replyTo"); } @@ -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 is null && globalEmailServer is not null) { SmtpServer = Convert.ToString(globalEmailServer.Value, CultureInfo.InvariantCulture); } @@ -298,7 +298,7 @@ protected override void BeginProcessing() _mSmtpClient.EnableSsl = true; } - if (Credential != null) + if (Credential is not null) { _mSmtpClient.UseDefaultCredentials = false; _mSmtpClient.Credentials = Credential.GetNetworkCredential(); @@ -315,7 +315,7 @@ protected override void BeginProcessing() protected override void ProcessRecord() { // Add the attachments - if (Attachments != null) + if (Attachments is not null) { string filepath = string.Empty; foreach (string attachFile in Attachments) @@ -353,7 +353,7 @@ protected override void EndProcessing() } catch (SmtpException ex) { - if (ex.InnerException != null) + if (ex.InnerException is not null) { ErrorRecord er = new ErrorRecord(new SmtpException(ex.InnerException.Message), "SmtpException", ErrorCategory.InvalidOperation, _mSmtpClient); WriteError(er); 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..61eb4a1167a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Set-PSBreakpoint.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Set-PSBreakpoint.cs @@ -125,7 +125,7 @@ protected override void ProcessRecord() // If there is a script, resolve its path Collection scripts = new Collection(); - if (Script != null) + if (Script is not null) { foreach (string script in Script) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetAliasCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetAliasCommand.cs index b2746625375..30c332f9431 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetAliasCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetAliasCommand.cs @@ -65,7 +65,7 @@ protected override void ProcessRecord() // Write the alias to the pipeline if PassThru was specified - if (PassThru && result != null) + if (PassThru && result is not null) { WriteObject(result); } 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..b069a47db18 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs @@ -373,7 +373,7 @@ private bool CanProcessRecordForOneCommand() { CommandInfo commandInfo; this.GetCommandInfoAndModules(out commandInfo, out _importedModules); - Diagnostics.Assert(commandInfo != null, "GetCommandInfoAndModules would throw a terminating error/exception"); + Diagnostics.Assert(commandInfo is not null, "GetCommandInfoAndModules would throw a terminating error/exception"); try { @@ -482,7 +482,7 @@ private void Dispose(bool isDisposing) { if (isDisposing) { - if (_errors != null) + if (_errors is not null) { _errors.Dispose(); _errors = null; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandCommandInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandCommandInfo.cs index abdcf93d630..f6ff6b3a238 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandCommandInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandCommandInfo.cs @@ -55,7 +55,7 @@ public ShowCommandCommandInfo(CommandInfo other) this.ParameterSets = new List().AsReadOnly(); } - if (other.Module != null) + if (other.Module is not null) { this.Module = new ShowCommandModuleInfo(other.Module); } @@ -78,7 +78,7 @@ public ShowCommandCommandInfo(PSObject other) this.ModuleName = other.Members["ModuleName"].Value as string; this.Definition = other.Members["Definition"].Value as string; this.ParameterSets = other.Members["ParameterSets"].Value as ICollection; - if (this.ParameterSets != null) + if (this.ParameterSets is not null) { // Simple case - the objects are still live because they came from in-proc. Just cast them back this.CommandType = (CommandTypes)(other.Members["CommandType"].Value); @@ -92,7 +92,7 @@ public ShowCommandCommandInfo(PSObject other) var parameterSets = (other.Members["ParameterSets"].Value as PSObject).BaseObject as System.Collections.ArrayList; this.ParameterSets = GetObjectEnumerable(parameterSets).Cast().Select(x => new ShowCommandParameterSetInfo(x)).ToList().AsReadOnly(); - if (other.Members["Module"] != null && other.Members["Module"].Value as PSObject != null) + if (other.Members["Module"] is not null && other.Members["Module"].Value as PSObject is not null) { this.Module = new ShowCommandModuleInfo(other.Members["Module"].Value as PSObject); } 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..9146aae63a2 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterInfo.cs @@ -33,7 +33,7 @@ public ShowCommandParameterInfo(CommandParameterInfo other) this.Position = other.Position; var validateSetAttribute = other.Attributes.Where(x => typeof(ValidateSetAttribute).IsAssignableFrom(x.GetType())).Cast().LastOrDefault(); - if (validateSetAttribute != null) + if (validateSetAttribute is not null) { this.HasParameterSet = true; this.ValidParamSetValues = validateSetAttribute.ValidValues; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowMarkdownCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowMarkdownCommand.cs index 2203fbb20a7..f8073bdab48 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowMarkdownCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowMarkdownCommand.cs @@ -226,7 +226,7 @@ private void ProcessMarkdownInfo(MarkdownInfo markdownInfo) /// protected override void EndProcessing() { - if (_powerShell != null) + if (_powerShell is not null) { _powerShell.Dispose(); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/StartSleepCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/StartSleepCommand.cs index 4fe5c641ff9..f9b24c13b48 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/StartSleepCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/StartSleepCommand.cs @@ -25,7 +25,7 @@ public void Dispose() { if (_disposed == false) { - if (_waitHandle != null) + if (_waitHandle is not null) { _waitHandle.Dispose(); _waitHandle = null; @@ -82,7 +82,7 @@ private void Sleep(int milliSecondsToSleep) } } - if (_waitHandle != null) + if (_waitHandle is not null) { _waitHandle.WaitOne(milliSecondsToSleep, true); } @@ -121,7 +121,7 @@ protected override void StopProcessing() lock (_syncObject) { _stopping = true; - if (_waitHandle != null) + if (_waitHandle is not null) { _waitHandle.Set(); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Tee-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Tee-Object.cs index 32048362b06..af7606cafc5 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Tee-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Tee-Object.cs @@ -131,7 +131,7 @@ private void Dispose(bool isDisposing) if (!_alreadyDisposed) { _alreadyDisposed = true; - if (isDisposing && _commandWrapper != null) + if (isDisposing && _commandWrapper is not null) { _commandWrapper.Dispose(); _commandWrapper = null; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TestJsonCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TestJsonCommand.cs index 668c5072841..4d396259fab 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TestJsonCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TestJsonCommand.cs @@ -80,7 +80,7 @@ protected override void BeginProcessing() try { - if (Schema != null) + if (Schema is not null) { try { @@ -93,7 +93,7 @@ protected override void BeginProcessing() ae.Handle(UnwrapException); } } - else if (SchemaFile != null) + else if (SchemaFile is not null) { try { @@ -142,10 +142,10 @@ protected override void ProcessRecord() { parsedJson = JObject.Parse(Json); - if (_jschema != null) + if (_jschema is not null) { var errorMessages = _jschema.Validate(parsedJson); - if (errorMessages != null && errorMessages.Count != 0) + if (errorMessages is not null && errorMessages.Count != 0) { result = false; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnregisterEventCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnregisterEventCommand.cs index f89b3d6e4cc..b62746508bd 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnregisterEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnregisterEventCommand.cs @@ -29,7 +29,7 @@ public string SourceIdentifier { _sourceIdentifier = value; - if (value != null) + if (value is not null) { _matchPattern = WildcardPattern.Get(value, WildcardOptions.IgnoreCase); } @@ -66,7 +66,7 @@ protected override void ProcessRecord() { // If the event identifier matches, remove the subscription if ( - ((_sourceIdentifier != null) && _matchPattern.IsMatch(subscriber.SourceIdentifier)) || + ((_sourceIdentifier is not null) && _matchPattern.IsMatch(subscriber.SourceIdentifier)) || ((SubscriptionId >= 0) && (subscriber.SubscriptionId == SubscriptionId)) ) { @@ -93,7 +93,7 @@ protected override void ProcessRecord() // Generate an error if we couldn't find the subscription identifier, // and no globbing was done. - if ((_sourceIdentifier != null) && + if ((_sourceIdentifier is not null) && (!WildcardPattern.ContainsWildcardCharacters(_sourceIdentifier)) && (!_foundMatch)) { 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..76ef5667f9d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-List.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-List.cs @@ -75,7 +75,7 @@ public class UpdateListCommand : PSCmdlet /// protected override void ProcessRecord() { - if (Property != null) + if (Property is not null) { if (InputObject is null) { @@ -89,7 +89,7 @@ protected override void ProcessRecord() } PSMemberInfo memberInfo = InputObject.Members[Property]; - if (memberInfo != null) + if (memberInfo is not null) { try { @@ -116,7 +116,7 @@ protected override void EndProcessing() { if (Property is null) { - if (InputObject != null) + if (InputObject is not null) { ThrowTerminatingError(NewError("MissingPropertyParameter", "MissingPropertyParameter", null)); } @@ -130,17 +130,17 @@ protected override void EndProcessing() private Hashtable CreateHashtable() { Hashtable hash = new Hashtable(2); - if (Add != null) + if (Add is not null) { hash.Add("Add", Add); } - if (Remove != null) + if (Remove is not null) { hash.Add("Remove", Remove); } - if (Replace != null) + if (Replace is not null) { hash.Add("Replace", Replace); } @@ -151,7 +151,7 @@ private Hashtable CreateHashtable() private PSListModifier CreatePSListModifier() { PSListModifier listModifier = new PSListModifier(); - if (Add != null) + if (Add is not null) { foreach (object obj in Add) { @@ -159,7 +159,7 @@ private PSListModifier CreatePSListModifier() } } - if (Remove != null) + if (Remove is not null) { foreach (object obj in Remove) { @@ -167,7 +167,7 @@ private PSListModifier CreatePSListModifier() } } - if (Replace != null) + if (Replace is not null) { foreach (object obj in Replace) { 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..01544c18df6 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-TypeData.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-TypeData.cs @@ -379,7 +379,7 @@ private void ProcessStrongTypeData() else { // Update successfully, we add the TypeData into cache - if (Context.InitialSessionState != null) + if (Context.InitialSessionState is not null) { Context.InitialSessionState.Types.Add(new SessionStateTypeEntry(type, false)); } @@ -415,22 +415,22 @@ private void ProcessDynamicType() GetMembers(type.Members); - if (_typeConverter != null) + if (_typeConverter is not null) { type.TypeConverter = _typeConverter; } - if (_typeAdapter != null) + if (_typeAdapter is not null) { type.TypeAdapter = _typeAdapter; } - if (_serializationMethod != null) + if (_serializationMethod is not null) { type.SerializationMethod = _serializationMethod; } - if (_targetTypeForDeserialization != null) + if (_targetTypeForDeserialization is not null) { type.TargetTypeForDeserialization = _targetTypeForDeserialization; } @@ -440,34 +440,34 @@ private void ProcessDynamicType() type.SerializationDepth = (uint)_serializationDepth; } - if (_defaultDisplayProperty != null) + if (_defaultDisplayProperty is not null) { type.DefaultDisplayProperty = _defaultDisplayProperty; } - if (_inheritPropertySerializationSet != null) + if (_inheritPropertySerializationSet is not null) { type.InheritPropertySerializationSet = _inheritPropertySerializationSet.Value; } - if (_stringSerializationSource != null) + if (_stringSerializationSource is not null) { type.StringSerializationSource = _stringSerializationSource; } - if (_defaultDisplayPropertySet != null) + if (_defaultDisplayPropertySet is not null) { PropertySetData defaultDisplayPropertySet = new PropertySetData(_defaultDisplayPropertySet); type.DefaultDisplayPropertySet = defaultDisplayPropertySet; } - if (_defaultKeyPropertySet != null) + if (_defaultKeyPropertySet is not null) { PropertySetData defaultKeyPropertySet = new PropertySetData(_defaultKeyPropertySet); type.DefaultKeyPropertySet = defaultKeyPropertySet; } - if (_propertySerializationSet != null) + if (_propertySerializationSet is not null) { PropertySetData propertySerializationSet = new PropertySetData(_propertySerializationSet); type.PropertySerializationSet = propertySerializationSet; @@ -503,7 +503,7 @@ private void ProcessDynamicType() else { // Update successfully, we add the TypeData into cache - if (Context.InitialSessionState != null) + if (Context.InitialSessionState is not null) { Context.InitialSessionState.Types.Add(new SessionStateTypeEntry(type, false)); } @@ -530,7 +530,7 @@ private void GetMembers(Dictionary members) { // If the MemberType is not specified, the MemberName, Value, and SecondValue parameters // should not be specified either - if (_memberName != null || HasBeenSpecified(_value1) || _value2 != null) + if (_memberName is not null || HasBeenSpecified(_value1) || _value2 is not null) { ThrowTerminatingError(NewError("MemberTypeIsMissing", UpdateDataStrings.MemberTypeIsMissing, null)); } @@ -611,7 +611,7 @@ private void EnsureValue1NotNullOrEmpty() private void EnsureValue2HasNotBeenSpecified() { - if (_value2 != null) + if (_value2 is not null) { ThrowTerminatingError(NewError("SecondValueShouldNotBeSpecified", UpdateDataStrings.ShouldNotBeSpecified, null, "SecondValue", _memberType)); } @@ -661,7 +661,7 @@ private AliasPropertyData GetAliasProperty() AliasPropertyData alias; string referencedName = GetParameterType(_value1); - if (_value2 != null) + if (_value2 is not null) { Type type = GetParameterType(_value2); alias = new AliasPropertyData(_memberName, referencedName, type); @@ -679,13 +679,13 @@ private ScriptPropertyData GetScriptProperty() EnsureValue1AndValue2AreNotBothNull(); ScriptBlock value1ScriptBlock = null; - if (_value1 != null) + if (_value1 is not null) { value1ScriptBlock = GetParameterType(_value1); } ScriptBlock value2ScriptBlock = null; - if (_value2 != null) + if (_value2 is not null) { value2ScriptBlock = GetParameterType(_value2); } @@ -701,13 +701,13 @@ private CodePropertyData GetCodeProperty() EnsureValue1AndValue2AreNotBothNull(); MethodInfo value1CodeReference = null; - if (_value1 != null) + if (_value1 is not null) { value1CodeReference = GetParameterType(_value1); } MethodInfo value2CodeReference = null; - if (_value2 != null) + if (_value2 is not null) { value2CodeReference = GetParameterType(_value2); } @@ -776,7 +776,7 @@ private void ProcessTypeFiles() // filename is available string target = UpdateDataStrings.UpdateTarget; - if (Context.InitialSessionState != null) + if (Context.InitialSessionState is not null) { // This hashSet is to detect if there are duplicate type files var fullFileNameHash = new HashSet(StringComparer.CurrentCultureIgnoreCase); @@ -800,7 +800,7 @@ private void ProcessTypeFiles() // Copy everything from context's TypeTable to newTypes foreach (var entry in Context.InitialSessionState.Types) { - if (entry.FileName != null) + if (entry.FileName is not null) { string resolvedPath = ModuleCmdletBase.ResolveRootedFilePath(entry.FileName, Context) ?? entry.FileName; if (!fullFileNameHash.Contains(resolvedPath)) @@ -838,13 +838,13 @@ private void ProcessTypeFiles() { try { - if (sste.TypeTable != null) + if (sste.TypeTable is not null) { var ex = new PSInvalidOperationException(UpdateDataStrings.CannotUpdateTypeWithTypeTable); this.WriteError(new ErrorRecord(ex, "CannotUpdateTypeWithTypeTable", ErrorCategory.InvalidOperation, null)); continue; } - else if (sste.FileName != null) + else if (sste.FileName is not null) { bool unused; Context.TypeTable.Update(sste.FileName, sste.FileName, errors, Context.AuthorizationManager, Context.InitialSessionState.Host, out unused); @@ -921,7 +921,7 @@ protected override void ProcessRecord() // filename is available string target = UpdateDataStrings.UpdateTarget; - if (Context.InitialSessionState != null) + if (Context.InitialSessionState is not null) { if (Context.InitialSessionState.DisableFormatUpdates) { @@ -949,7 +949,7 @@ protected override void ProcessRecord() // Always add InitialSessionState.Formats to the new list foreach (SessionStateFormatEntry entry in Context.InitialSessionState.Formats) { - if (entry.FileName != null) + if (entry.FileName is not null) { if (!fullFileNameHash.Contains(entry.FileName)) { @@ -989,18 +989,18 @@ protected override void ProcessRecord() { string name = ssfe.FileName; PSSnapInInfo snapin = ssfe.PSSnapIn; - if (snapin != null && !string.IsNullOrEmpty(snapin.Name)) + if (snapin is not null && !string.IsNullOrEmpty(snapin.Name)) { name = snapin.Name; } - if (ssfe.Formattable != null) + if (ssfe.Formattable is not null) { var ex = new PSInvalidOperationException(UpdateDataStrings.CannotUpdateFormatWithFormatTable); this.WriteError(new ErrorRecord(ex, "CannotUpdateFormatWithFormatTable", ErrorCategory.InvalidOperation, null)); continue; } - else if (ssfe.FormatData != null) + else if (ssfe.FormatData is not null) { entries.Add(new PSSnapInTypeAndFormatErrors(name, ssfe.FormatData)); } @@ -1122,7 +1122,7 @@ protected override void ProcessRecord() Dictionary> fileToIndexMap = new Dictionary>(StringComparer.OrdinalIgnoreCase); List indicesToRemove = new List(); - if (Context.InitialSessionState != null) + if (Context.InitialSessionState is not null) { for (int index = 0; index < Context.InitialSessionState.Types.Count; index++) { @@ -1158,7 +1158,7 @@ protected override void ProcessRecord() indicesToRemove.Sort(); for (int i = indicesToRemove.Count - 1; i >= 0; i--) { - if (Context.InitialSessionState != null) + if (Context.InitialSessionState is not null) { Context.InitialSessionState.Types.RemoveItem(indicesToRemove[i]); } @@ -1166,7 +1166,7 @@ protected override void ProcessRecord() try { - if (Context.InitialSessionState != null) + if (Context.InitialSessionState is not null) { bool oldRefreshTypeFormatSetting = Context.InitialSessionState.RefreshTypeAndFormatSetting; try @@ -1230,7 +1230,7 @@ protected override void ProcessRecord() else { // Type is removed successfully, add it into the cache - if (Context.InitialSessionState != null) + if (Context.InitialSessionState is not null) { Context.InitialSessionState.Types.Add(new SessionStateTypeEntry(type, true)); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Var.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Var.cs index fdffcb029e9..e2784ca5059 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Var.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Var.cs @@ -492,7 +492,7 @@ protected override void ProcessRecord() SessionState.PSVariable.GetAtScope(Name, Scope); } - if (varFound != null) + if (varFound is not null) { SessionStateException sessionStateException = new SessionStateException( @@ -521,12 +521,12 @@ protected override void ProcessRecord() { PSVariable newVariable = new PSVariable(Name, Value, Option); - if (_visibility != null) + if (_visibility is not null) { newVariable.Visibility = (SessionStateEntryVisibility)_visibility; } - if (Description != null) + if (Description is not null) { newVariable.Description = Description; } @@ -714,7 +714,7 @@ public SwitchParameter PassThru /// protected override void BeginProcessing() { - if (Name != null && Name.Length > 0) + if (Name is not null && Name.Length > 0) { _nameIsFormalParameter = true; } @@ -775,7 +775,7 @@ protected override void EndProcessing() } else { - if (_valueList != null) + if (_valueList is not null) { if (_valueList.Count == 1) { @@ -858,7 +858,7 @@ private void SetVariable(string[] varNames, object varValue) newOptions = ScopedItemOptions.Private; } - if (_options != null) + if (_options is not null) { newOptions |= (ScopedItemOptions)_options; } @@ -883,7 +883,7 @@ private void SetVariable(string[] varNames, object varValue) varToSet.Description = Description; // If visibility was specified, set it on the variable - if (_visibility != null) + if (_visibility is not null) { varToSet.Visibility = Visibility; } @@ -907,7 +907,7 @@ private void SetVariable(string[] varNames, object varValue) SessionState.Internal.SetVariableAtScope(varToSet, Scope, Force, origin); } - if (_passThru && result != null) + if (_passThru && result is not null) { WriteObject(result); } @@ -977,12 +977,12 @@ private void SetVariable(string[] varNames, object varValue) } } - if (Description != null) + if (Description is not null) { matchingVariable.Description = Description; } - if (_options != null) + if (_options is not null) { matchingVariable.Options = (ScopedItemOptions)_options; } @@ -995,7 +995,7 @@ private void SetVariable(string[] varNames, object varValue) } // If visibility was specified, set it on the variable - if (_visibility != null) + if (_visibility is not null) { matchingVariable.Visibility = Visibility; } @@ -1019,7 +1019,7 @@ private void SetVariable(string[] varNames, object varValue) continue; } - if (_passThru && result != null) + if (_passThru && result is not null) { WriteObject(result); } @@ -1368,7 +1368,7 @@ protected override void ProcessRecord() private PSVariable ClearValue(PSVariable matchingVariable) { PSVariable result = matchingVariable; - if (Scope != null) + if (Scope is not null) { matchingVariable.Value = null; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WaitEventCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WaitEventCommand.cs index 54fa9f2af1b..3f7c38205af 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WaitEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WaitEventCommand.cs @@ -98,7 +98,7 @@ protected override void ProcessRecord() // Unsubscribe, and write the event information we received Events.ReceivedEvents.PSEventReceived -= ReceivedEvents_PSEventReceived; - if (_receivedEvent != null) + if (_receivedEvent is not null) { WriteObject(_receivedEvent); } 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..b7f8b877804 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 @@ -167,14 +167,14 @@ private static bool CheckIsText(string contentType) // Media types registered with Windows as having a perceived type of text, are text using (RegistryKey contentTypeKey = Registry.ClassesRoot.OpenSubKey(@"MIME\Database\Content Type\" + contentType)) { - if (contentTypeKey != null) + if (contentTypeKey is not null) { string extension = contentTypeKey.GetValue("Extension") as string; - if (extension != null) + if (extension is not null) { using (RegistryKey extensionKey = Registry.ClassesRoot.OpenSubKey(extension)) { - if (extensionKey != null) + if (extensionKey is not null) { string perceivedType = extensionKey.GetValue("PerceivedType") as string; isText = (perceivedType == "text"); 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..2f9ca7eaa17 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 @@ -178,7 +178,7 @@ private bool TryConvertToXml(string xml, out object doc, ref Exception exRef) doc = null; } - return (doc != null); + return (doc is not null); } private bool TryConvertToJson(string json, out object obj, ref Exception exRef) @@ -196,7 +196,7 @@ private bool TryConvertToJson(string json, out object obj, ref Exception exRef) JToken.Parse(json); } - if (error != null) + if (error is not null) { exRef = error.Exception; obj = null; 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..a1c02d05ba3 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 @@ -396,7 +396,7 @@ public virtual string CustomMethod internal virtual void ValidateParameters() { // sessions - if ((WebSession != null) && (SessionVariable != null)) + if ((WebSession is not null) && (SessionVariable is not null)) { ErrorRecord error = GetValidationError(WebCmdletStrings.SessionConflict, "WebCmdletSessionConflictException"); @@ -411,7 +411,7 @@ internal virtual void ValidateParameters() ThrowTerminatingError(error); } - if ((Authentication != WebAuthenticationType.None) && (Token != null) && (Credential != null)) + if ((Authentication != WebAuthenticationType.None) && (Token is not null) && (Credential is not null)) { ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationTokenConflict, "WebCmdletAuthenticationTokenConflictException"); @@ -439,7 +439,7 @@ internal virtual void ValidateParameters() ThrowTerminatingError(error); } - if (!AllowUnencryptedAuthentication && (Credential != null || UseDefaultCredentials) && (Uri.Scheme != "https")) + if (!AllowUnencryptedAuthentication && (Credential is not null || UseDefaultCredentials) && (Uri.Scheme != "https")) { ErrorRecord error = GetValidationError(WebCmdletStrings.AllowUnencryptedAuthenticationRequired, "WebCmdletAllowUnencryptedAuthenticationRequiredException"); @@ -447,7 +447,7 @@ internal virtual void ValidateParameters() } // credentials - if (UseDefaultCredentials && (Credential != null)) + if (UseDefaultCredentials && (Credential is not null)) { ErrorRecord error = GetValidationError(WebCmdletStrings.CredentialConflict, "WebCmdletCredentialConflictException"); @@ -455,13 +455,13 @@ internal virtual void ValidateParameters() } // Proxy server - if (ProxyUseDefaultCredentials && (ProxyCredential != null)) + if (ProxyUseDefaultCredentials && (ProxyCredential is not null)) { ErrorRecord error = GetValidationError(WebCmdletStrings.ProxyCredentialConflict, "WebCmdletProxyCredentialConflictException"); ThrowTerminatingError(error); } - else if ((Proxy is null) && ((ProxyCredential != null) || ProxyUseDefaultCredentials)) + else if ((Proxy is null) && ((ProxyCredential is not null) || ProxyUseDefaultCredentials)) { ErrorRecord error = GetValidationError(WebCmdletStrings.ProxyUriNotSupplied, "WebCmdletProxyUriNotSuppliedException"); @@ -469,21 +469,21 @@ internal virtual void ValidateParameters() } // request body content - if ((Body != null) && (InFile != null)) + if ((Body is not null) && (InFile is not null)) { ErrorRecord error = GetValidationError(WebCmdletStrings.BodyConflict, "WebCmdletBodyConflictException"); ThrowTerminatingError(error); } - if ((Body != null) && (Form != null)) + if ((Body is not null) && (Form is not null)) { ErrorRecord error = GetValidationError(WebCmdletStrings.BodyFormConflict, "WebCmdletBodyFormConflictException"); ThrowTerminatingError(error); } - if ((InFile != null) && (Form != null)) + if ((InFile is not null) && (Form is not null)) { ErrorRecord error = GetValidationError(WebCmdletStrings.FormInFileConflict, "WebCmdletFormInFileConflictException"); @@ -491,7 +491,7 @@ internal virtual void ValidateParameters() } // validate InFile path - if (InFile != null) + if (InFile is not null) { ProviderInfo provider = null; ErrorRecord errorRecord = null; @@ -543,7 +543,7 @@ internal virtual void ValidateParameters() errorRecord = new ErrorRecord(driveNotFound.ErrorRecord, driveNotFound); } - if (errorRecord != null) + if (errorRecord is not null) { ThrowTerminatingError(errorRecord); } @@ -574,7 +574,7 @@ internal virtual void PrepareSession() WebSession = new WebRequestSession(); } - if (SessionVariable != null) + if (SessionVariable is not null) { // save the session back to the PS environment if requested PSVariableIntrinsics vi = SessionState.PSVariable; @@ -584,7 +584,7 @@ internal virtual void PrepareSession() // // handle credentials // - if (Credential != null && Authentication == WebAuthenticationType.None) + if (Credential is not null && Authentication == WebAuthenticationType.None) { // get the relevant NetworkCredential NetworkCredential netCred = Credential.GetNetworkCredential(); @@ -593,7 +593,7 @@ internal virtual void PrepareSession() // supplying a credential overrides the UseDefaultCredentials setting WebSession.UseDefaultCredentials = false; } - else if ((Credential != null || null != Token) && Authentication != WebAuthenticationType.None) + else if ((Credential is not null || null != Token) && Authentication != WebAuthenticationType.None) { ProcessAuthentication(); } @@ -602,7 +602,7 @@ internal virtual void PrepareSession() WebSession.UseDefaultCredentials = true; } - if (CertificateThumbprint != null) + if (CertificateThumbprint is not null) { X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); @@ -621,7 +621,7 @@ internal virtual void PrepareSession() } } - if (Certificate != null) + if (Certificate is not null) { WebSession.AddCertificate(Certificate); } @@ -629,17 +629,17 @@ internal virtual void PrepareSession() // // handle the user agent // - if (UserAgent != null) + if (UserAgent is not null) { // store the UserAgent string WebSession.UserAgent = UserAgent; } - if (Proxy != null) + if (Proxy is not null) { WebProxy webProxy = new WebProxy(Proxy); webProxy.BypassProxyOnLocal = false; - if (ProxyCredential != null) + if (ProxyCredential is not null) { webProxy.Credentials = ProxyCredential.GetNetworkCredential(); } @@ -659,7 +659,7 @@ internal virtual void PrepareSession() } // store the other supplied headers - if (Headers != null) + if (Headers is not null) { foreach (string key in Headers.Keys) { @@ -727,12 +727,12 @@ private Uri PrepareUri(Uri uri) // preprocess Body if content is a dictionary and method is GET (set as query) IDictionary bodyAsDictionary; LanguagePrimitives.TryConvertTo(Body, out bodyAsDictionary); - if ((bodyAsDictionary != null) + if ((bodyAsDictionary is not null) && ((IsStandardMethodSet() && (Method == WebRequestMethod.Default || Method == WebRequestMethod.Get)) || (IsCustomMethodSet() && CustomMethod.ToUpperInvariant() == "GET"))) { UriBuilder uriBuilder = new UriBuilder(uri); - if (uriBuilder.Query != null && uriBuilder.Query.Length > 1) + if (uriBuilder.Query is not null && uriBuilder.Query.Length > 1) { uriBuilder.Query = uriBuilder.Query.Substring(1) + "&" + FormatDictionary(bodyAsDictionary); } @@ -785,7 +785,7 @@ private string FormatDictionary(IDictionary content) // URLEncode the key and value string encodedKey = WebUtility.UrlEncode(key); string encodedValue = string.Empty; - if (value != null) + if (value is not null) { encodedValue = WebUtility.UrlEncode(value.ToString()); } @@ -991,7 +991,7 @@ internal virtual HttpClient GetHttpClient(bool handleRedirect) // the UseDefaultCredentials flag overrides other supplied credentials handler.UseDefaultCredentials = true; } - else if (WebSession.Credentials != null) + else if (WebSession.Credentials is not null) { handler.Credentials = WebSession.Credentials; } @@ -1000,12 +1000,12 @@ internal virtual HttpClient GetHttpClient(bool handleRedirect) { handler.UseProxy = false; } - else if (WebSession.Proxy != null) + else if (WebSession.Proxy is not null) { handler.Proxy = WebSession.Proxy; } - if (WebSession.Certificates != null) + if (WebSession.Certificates is not null) { handler.ClientCertificates.AddRange(WebSession.Certificates); } @@ -1134,7 +1134,7 @@ internal virtual HttpRequestMessage GetRequest(Uri uri) } // Set 'Transfer-Encoding' - if (TransferEncoding != null) + if (TransferEncoding is not null) { request.Headers.TransferEncodingChunked = true; var headerValue = new TransferCodingHeaderValue(TransferEncoding); @@ -1168,7 +1168,7 @@ internal virtual void FillRequestStream(HttpRequestMessage request) if (request is null) { throw new ArgumentNullException(nameof(request)); } // set the content type - if (ContentType != null) + if (ContentType is not null) { WebSession.ContentHeaders[HttpKnownHeaderNames.ContentType] = ContentType; // request @@ -1185,7 +1185,7 @@ internal virtual void FillRequestStream(HttpRequestMessage request) } } - if (Form != null) + if (Form is not null) { // Content headers will be set by MultipartFormDataContent which will throw unless we clear them first WebSession.ContentHeaders.Clear(); @@ -1200,13 +1200,13 @@ internal virtual void FillRequestStream(HttpRequestMessage request) SetRequestContent(request, formData); } // coerce body into a usable form - else if (Body != null) + else if (Body is not null) { object content = Body; // make sure we're using the base object of the body, not the PSObject wrapper PSObject psBody = Body as PSObject; - if (psBody != null) + if (psBody is not null) { content = psBody.BaseObject; } @@ -1243,7 +1243,7 @@ internal virtual void FillRequestStream(HttpRequestMessage request) (string)LanguagePrimitives.ConvertTo(content, typeof(string), CultureInfo.InvariantCulture)); } } - else if (InFile != null) // copy InFile data + else if (InFile is not null) // copy InFile data { try { @@ -1355,7 +1355,7 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM _cancelToken = new CancellationTokenSource(); response = client.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, _cancelToken.Token).GetAwaiter().GetResult(); - if (keepAuthorization && IsRedirectCode(response.StatusCode) && response.Headers.Location != null) + if (keepAuthorization && IsRedirectCode(response.StatusCode) && response.Headers.Location is not null) { _cancelToken.Cancel(); _cancelToken = null; @@ -1403,7 +1403,7 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM { FillRequestStream(requestWithoutRange); long requestContentLength = 0; - if (requestWithoutRange.Content != null) + if (requestWithoutRange.Content is not null) { requestContentLength = requestWithoutRange.Content.Headers.ContentLength.Value; } @@ -1472,9 +1472,9 @@ protected override void ProcessRecord() // if the request contains an authorization header and PreserveAuthorizationOnRedirect is not set, // it needs to be stripped on the first redirect. - bool keepAuthorization = WebSession != null + bool keepAuthorization = WebSession is not null && - WebSession.Headers != null + WebSession.Headers is not null && PreserveAuthorizationOnRedirect.IsPresent && @@ -1500,7 +1500,7 @@ protected override void ProcessRecord() try { long requestContentLength = 0; - if (request.Content != null) + if (request.Content is not null) requestContentLength = request.Content.Headers.ContentLength.Value; string reqVerboseMsg = string.Format(CultureInfo.CurrentCulture, @@ -1554,7 +1554,7 @@ protected override void ProcessRecord() } finally { - if (reader != null) + if (reader is not null) { reader.Dispose(); } @@ -1595,7 +1595,7 @@ protected override void ProcessRecord() catch (HttpRequestException ex) { ErrorRecord er = new ErrorRecord(ex, "WebCmdletWebResponseException", ErrorCategory.InvalidOperation, request); - if (ex.InnerException != null) + if (ex.InnerException is not null) { er.ErrorDetails = new ErrorDetails(ex.InnerException.Message); } @@ -1635,7 +1635,7 @@ protected override void ProcessRecord() /// protected override void StopProcessing() { - if (_cancelToken != null) + if (_cancelToken is not null) { _cancelToken.Cancel(); } @@ -1687,7 +1687,7 @@ internal long SetRequestContent(HttpRequestMessage request, string content) return 0; Encoding encoding = null; - if (ContentType != null) + if (ContentType is not null) { // If Content-Type contains the encoding format (as CharSet), use this encoding format // to encode the Body of the WebRequest sent to the server. Default Encoding format @@ -1737,7 +1737,7 @@ internal long SetRequestContent(HttpRequestMessage request, XmlNode xmlNode) byte[] bytes = null; XmlDocument doc = xmlNode as XmlDocument; - if (doc != null && (doc.FirstChild as XmlDeclaration) != null) + if (doc is not null && (doc.FirstChild as XmlDeclaration) is not null) { XmlDeclaration decl = doc.FirstChild as XmlDeclaration; Encoding encoding = Encoding.GetEncoding(decl.Encoding); 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..54ae4567b2f 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 @@ -187,7 +187,7 @@ private void SetResponse(HttpResponseMessage response, Stream contentStream) BaseResponse = response; MemoryStream ms = contentStream as MemoryStream; - if (ms != null) + if (ms is not null) { _rawContentStream = ms; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertFromJsonCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertFromJsonCommand.cs index 955786248f7..8ff7c259111 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertFromJsonCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertFromJsonCommand.cs @@ -115,13 +115,13 @@ private bool ConvertFromJsonHelper(string input) ErrorRecord error = null; object result = JsonObject.ConvertFromJson(input, AsHashtable.IsPresent, Depth, out error); - if (error != null) + if (error is not null) { ThrowTerminatingError(error); } WriteObject(result, !NoEnumerate.IsPresent); - return (result != null); + return (result is not null); } #endregion overrides diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs index 92e67f5681a..f1cfdb82214 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs @@ -123,7 +123,7 @@ protected override void EndProcessing() // null is returned only if the pipeline is stopping (e.g. ctrl+c is signaled). // in that case, we shouldn't write the null to the output pipe. string output = JsonObject.ConvertToJson(objectToProcess, in context); - if (output != null) + if (output is not null) { WriteObject(output); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs index dc2f734d6bd..a15700c085b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs @@ -27,7 +27,7 @@ internal static Dictionary> GetHeadersDictionary(Htt // HttpResponseMessage.Content.Headers. The remaining headers are in HttpResponseMessage.Headers. // The keys in both should be unique with no duplicates between them. // Added for backwards compatibility with PowerShell 5.1 and earlier. - if (response.Content != null) + if (response.Content is not null) { foreach (var entry in response.Content.Headers) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObject.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObject.cs index d1a4cde2115..efa654fae0a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObject.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObject.cs @@ -47,7 +47,7 @@ public FormObject(string id, string method, string action) internal void AddField(string key, string value) { string test; - if (key != null && !Fields.TryGetValue(key, out test)) + if (key is not null && !Fields.TryGetValue(key, out test)) { Fields[key] = value; } 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..5c30b1cd80d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs @@ -261,7 +261,7 @@ private static PSObject PopulateFromJDictionary(JObject entries, DuplicateMember case JArray list: { var listResult = PopulateFromJArray(list, out error); - if (error != null) + if (error is not null) { return null; } @@ -273,7 +273,7 @@ private static PSObject PopulateFromJDictionary(JObject entries, DuplicateMember { // Dictionary var dicResult = PopulateFromJDictionary(dic, new DuplicateMemberHashSet(dic.Count), out error); - if (error != null) + if (error is not null) { return null; } @@ -309,7 +309,7 @@ private static ICollection PopulateFromJArray(JArray list, out ErrorReco { // Array var listResult = PopulateFromJArray(subList, out error); - if (error != null) + if (error is not null) { return null; } @@ -321,7 +321,7 @@ private static ICollection PopulateFromJArray(JArray list, out ErrorReco { // Dictionary var dicResult = PopulateFromJDictionary(dic, new DuplicateMemberHashSet(dic.Count), out error); - if (error != null) + if (error is not null) { return null; } @@ -366,7 +366,7 @@ private static Hashtable PopulateHashTableFromJDictionary(JObject entries, out E { // Array var listResult = PopulateHashTableFromJArray(list, out error); - if (error != null) + if (error is not null) { return null; } @@ -378,7 +378,7 @@ private static Hashtable PopulateHashTableFromJDictionary(JObject entries, out E { // Dictionary var dicResult = PopulateHashTableFromJDictionary(dic, out error); - if (error != null) + if (error is not null) { return null; } @@ -413,7 +413,7 @@ private static ICollection PopulateHashTableFromJArray(JArray list, out { // Array var listResult = PopulateHashTableFromJArray(array, out error); - if (error != null) + if (error is not null) { return null; } @@ -425,7 +425,7 @@ private static ICollection PopulateHashTableFromJArray(JArray list, out { // Dictionary var dicResult = PopulateHashTableFromJDictionary(dic, out error); - if (error != null) + if (error is not null) { return null; } @@ -504,7 +504,7 @@ private static object ProcessValue(object obj, int currentDepth, in ConvertToJso PSObject pso = obj as PSObject; - if (pso != null) + if (pso is not null) { obj = pso.BaseObject; } @@ -561,7 +561,7 @@ private static object ProcessValue(object obj, int currentDepth, in ConvertToJso { if (currentDepth > context.MaxDepth) { - if (pso != null && pso.ImmediateBaseObjectIsEmpty) + if (pso is not null && pso.ImmediateBaseObjectIsEmpty) { // The obj is a pure PSObject, we convert the original PSObject to a string, // instead of its base object in this case @@ -578,14 +578,14 @@ private static object ProcessValue(object obj, int currentDepth, in ConvertToJso else { IDictionary dict = obj as IDictionary; - if (dict != null) + if (dict is not null) { rv = ProcessDictionary(dict, currentDepth, in context); } else { IEnumerable enumerable = obj as IEnumerable; - if (enumerable != null) + if (enumerable is not null) { rv = ProcessEnumerable(enumerable, currentDepth, in context); } @@ -711,7 +711,7 @@ private static object ProcessDictionary(IDictionary dict, int depth, in ConvertT dict.GetType().FullName); var exception = new InvalidOperationException(errorMsg); - if (context.Cmdlet != null) + if (context.Cmdlet is not null) { var errorRecord = new ErrorRecord(exception, "NonStringKeyInDictionary", ErrorCategory.InvalidOperation, dict); context.Cmdlet.ThrowTerminatingError(errorRecord); @@ -780,7 +780,7 @@ private static object ProcessCustomObject(object o, int depth, in ConvertToJs if (!info2.IsDefined(typeof(T), true)) { MethodInfo getMethod = info2.GetGetMethod(); - if ((getMethod != null) && (getMethod.GetParameters().Length == 0)) + if ((getMethod is not null) && (getMethod.GetParameters().Length == 0)) { object value; try 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..2c75517b5cf 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs @@ -222,7 +222,7 @@ private void Initialize() ProgressRecord record = new ProgressRecord(StreamHelper.ActivityId, WebCmdletStrings.ReadResponseProgressActivity, "statusDescriptionPlaceholder"); for (int read = 1; 0 < read; totalLength += read) { - if (_ownerCmdlet != null) + if (_ownerCmdlet is not null) { record.StatusDescription = StringUtil.Format(WebCmdletStrings.ReadResponseProgressStatus, totalLength); _ownerCmdlet.WriteProgress(record); @@ -241,7 +241,7 @@ private void Initialize() } } - if (_ownerCmdlet != null) + if (_ownerCmdlet is not null) { record.StatusDescription = StringUtil.Format(WebCmdletStrings.ReadResponseComplete, totalLength); record.RecordType = ProgressRecordType.Completed; @@ -474,7 +474,7 @@ internal static Stream GetResponseStream(HttpResponseMessage response) // HttpClient by default will automatically decompress GZip and Deflate content. // We keep this decompression logic here just in case. - if (contentEncoding != null && contentEncoding.Count > 0) + if (contentEncoding is not null && contentEncoding.Count > 0) { if (contentEncoding.Contains("gzip")) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebCmdletElementCollection.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebCmdletElementCollection.cs index fada385d4ac..ef557ba07eb 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebCmdletElementCollection.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebCmdletElementCollection.cs @@ -55,7 +55,7 @@ private PSObject Find(string nameOrId, bool findById) foreach (PSObject candidate in this) { var namePropInfo = candidate.Properties[(findById ? "id" : "name")]; - if (namePropInfo != null && (string)namePropInfo.Value == nameOrId) + if (namePropInfo is not null && (string)namePropInfo.Value == nameOrId) { return candidate; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs index 5676a122776..da2db06496f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs @@ -35,13 +35,13 @@ protected override void ProcessRecord() // MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) + if (mshCommandRuntime is not null) { DebugRecord record = new DebugRecord(Message); InvocationInfo invocationInfo = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo; - if (invocationInfo != null) + if (invocationInfo is not null) { record.SetInvocationInfo(invocationInfo); } @@ -83,13 +83,13 @@ protected override void ProcessRecord() // MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) + if (mshCommandRuntime is not null) { VerboseRecord record = new VerboseRecord(Message); InvocationInfo invocationInfo = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo; - if (invocationInfo != null) + if (invocationInfo is not null) { record.SetInvocationInfo(invocationInfo); } @@ -131,13 +131,13 @@ protected override void ProcessRecord() // MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) + if (mshCommandRuntime is not null) { WarningRecord record = new WarningRecord(Message); InvocationInfo invocationInfo = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo; - if (invocationInfo != null) + if (invocationInfo is not null) { record.SetInvocationInfo(invocationInfo); } @@ -178,7 +178,7 @@ public sealed class WriteInformationCommand : PSCmdlet /// protected override void BeginProcessing() { - if (Tags != null) + if (Tags is not null) { foreach (string tag in Tags) { @@ -303,7 +303,7 @@ public class WriteOrThrowErrorCommand : PSCmdlet protected override void ProcessRecord() { ErrorRecord errorRecord = this.ErrorRecord; - if (errorRecord != null) + if (errorRecord is not null) { // copy constructor errorRecord = new ErrorRecord(errorRecord, null); @@ -330,7 +330,7 @@ protected override void ProcessRecord() TargetObject ); - if (this.Exception != null && !string.IsNullOrEmpty(msg)) + if (this.Exception is not null && !string.IsNullOrEmpty(msg)) { errorRecord.ErrorDetails = new ErrorDetails(msg); } @@ -368,7 +368,7 @@ protected override void ProcessRecord() // 2005/07/14-913791 "write-error output is confusing and misleading" // set InvocationInfo to the script not the command InvocationInfo myInvocation = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo; - if (myInvocation != null) + if (myInvocation is not null) { errorRecord.SetInvocationInfo(myInvocation); errorRecord.PreserveInvocationInfoOnce = true; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs index 7c2f2e44bf9..a8002075423 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs @@ -50,11 +50,11 @@ public SwitchParameter NoNewline // private string ProcessObject(object o) { - if (o != null) + if (o is not null) { string s = o as string; IEnumerable enumerable = null; - if (s != null) + if (s is not null) { // strings are IEnumerable, so we special case them if (s.Length > 0) @@ -62,7 +62,7 @@ private string ProcessObject(object o) return s; } } - else if ((enumerable = o as IEnumerable) != null) + else if ((enumerable = o as IEnumerable) is not null) { // unroll enumerables, including arrays. @@ -71,7 +71,7 @@ private string ProcessObject(object o) foreach (object element in enumerable) { - if (printSeparator && Separator != null) + if (printSeparator && Separator is not null) { result.Append(Separator.ToString()); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs index 8736965fd61..62ed5cfcfa4 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs @@ -136,7 +136,7 @@ protected override void ProcessRecord() { - if (_serializer != null) + if (_serializer is not null) { _serializer.Serialize(InputObject); _xw.Flush(); @@ -149,7 +149,7 @@ protected override void EndProcessing() { - if (_serializer != null) + if (_serializer is not null) { _serializer.Done(); _serializer = null; @@ -192,7 +192,7 @@ protected override void StopProcessing() private void CreateFileStream() { - Dbg.Assert(Path != null, "FileName is mandatory parameter"); + Dbg.Assert(Path is not null, "FileName is mandatory parameter"); if (!ShouldProcess(Path)) return; @@ -232,9 +232,9 @@ private void CreateFileStream() void CleanUp() { - if (_fs != null) + if (_fs is not null) { - if (_xw != null) + if (_xw is not null) { _xw.Dispose(); _xw = null; @@ -321,7 +321,7 @@ public void Dispose() if (!_disposed) { GC.SuppressFinalize(this); - if (_helper != null) + if (_helper is not null) { _helper.Dispose(); _helper = null; @@ -340,7 +340,7 @@ public void Dispose() /// protected override void ProcessRecord() { - if (Path != null) + if (Path is not null) { foreach (string path in Path) { @@ -439,10 +439,10 @@ protected override void ProcessRecord() { CreateMemoryStream(); - if (_serializer != null) + if (_serializer is not null) _serializer.SerializeAsStream(InputObject); - if (_serializer != null) + if (_serializer is not null) { _serializer.DoneAsStream(); _serializer = null; @@ -458,7 +458,7 @@ protected override void ProcessRecord() } else { - if (_serializer != null) + if (_serializer is not null) _serializer.Serialize(InputObject); } } @@ -467,7 +467,7 @@ protected override void ProcessRecord() /// protected override void EndProcessing() { - if (_serializer != null) + if (_serializer is not null) { _serializer.Done(); _serializer = null; @@ -577,9 +577,9 @@ private void CreateMemoryStream() /// private void CleanUp() { - if (_ms != null) + if (_ms is not null) { - if (_xw != null) + if (_xw is not null) { _xw.Dispose(); _xw = null; @@ -637,8 +637,8 @@ internal class ImportXmlHelper : IDisposable internal ImportXmlHelper(string fileName, PSCmdlet cmdlet, bool isLiteralPath) { - Dbg.Assert(fileName != null, "filename is mandatory"); - Dbg.Assert(cmdlet != null, "cmdlet is mandatory"); + Dbg.Assert(fileName is not null, "filename is mandatory"); + Dbg.Assert(cmdlet is not null, "cmdlet is mandatory"); _path = fileName; _cmdlet = cmdlet; _isLiteralPath = isLiteralPath; @@ -684,7 +684,7 @@ internal void CreateFileStream() private void CleanUp() { - if (_fs != null) + if (_fs is not null) { _fs.Dispose(); _fs = null; @@ -751,10 +751,10 @@ internal void Import() object result = _deserializer.Deserialize(); PSObject psObject = result as PSObject; - if (psObject != null) + if (psObject is not null) { ICollection c = psObject.BaseObject as ICollection; - if (c != null) + if (c is not null) { foreach (object o in c) { @@ -789,7 +789,7 @@ internal void Import() internal void Stop() { - if (_deserializer != null) + if (_deserializer is not null) { _deserializer.Stop(); } @@ -874,7 +874,7 @@ public string[] LiteralPath private void WriteResults(XmlNodeList foundXmlNodes, string filePath) { - Dbg.Assert(foundXmlNodes != null, "Caller should verify foundNodes != null"); + Dbg.Assert(foundXmlNodes is not null, "Caller should verify foundNodes is not null"); foreach (XmlNode foundXmlNode in foundXmlNodes) { @@ -889,10 +889,10 @@ private void WriteResults(XmlNodeList foundXmlNodes, string filePath) private void ProcessXmlNode(XmlNode xmlNode, string filePath) { - Dbg.Assert(xmlNode != null, "Caller should verify xmlNode != null"); + Dbg.Assert(xmlNode is not null, "Caller should verify xmlNode is not null"); XmlNodeList xList; - if (Namespace != null) + if (Namespace is not null) { XmlNamespaceManager xmlns = AddNameSpaceTable(this.ParameterSetName, xmlNode as XmlDocument, Namespace); xList = xmlNode.SelectNodes(XPath, xmlns); @@ -1140,7 +1140,7 @@ public override string ToString() /// private string ToString(string directory) { - string displayPath = (directory != null) ? RelativePath(directory) : _path; + string displayPath = (directory is not null) ? RelativePath(directory) : _path; return FormatLine(GetNodeText(), displayPath); } @@ -1151,9 +1151,9 @@ private string ToString(string directory) internal string GetNodeText() { string nodeText = string.Empty; - if (Node != null) + if (Node is not null) { - if (Node.Value != null) + if (Node.Value is not null) { nodeText = Node.Value.Trim(); } 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..c1c205fd3b0 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs @@ -228,7 +228,7 @@ protected override void ProcessRecord() /// protected override void EndProcessing() { - if (_pipeline != null) + if (_pipeline is not null) { TurnOnTracing(_matchingSources, false); @@ -247,7 +247,7 @@ protected override void EndProcessing() /// protected override void StopProcessing() { - if (_pipeline != null) + if (_pipeline is not null) { _pipeline.Stop(); } @@ -295,7 +295,7 @@ public void Dispose() ClearStoredState(); _matchingSources = null; - if (_pipeline != null) + if (_pipeline is not null) { _pipeline.Dispose(); _pipeline = null; @@ -303,7 +303,7 @@ public void Dispose() // If there are any file streams, close those as well. - if (this.FileStreams != null) + if (this.FileStreams is not null) { foreach (FileStream fileStream in this.FileStreams) { @@ -446,7 +446,7 @@ public override int Write(object obj) { ErrorRecord errorRecord = ConvertToErrorRecord(obj); - if (errorRecord != null) + if (errorRecord is not null) { _cmdlet.WriteError(errorRecord); } @@ -490,7 +490,7 @@ public override int Write(object obj, bool enumerateCollection) foreach (object o in LanguagePrimitives.GetEnumerable(obj)) { ErrorRecord errorRecord = ConvertToErrorRecord(o); - if (errorRecord != null) + if (errorRecord is not null) { numWritten++; _cmdlet.WriteError(errorRecord); @@ -500,7 +500,7 @@ public override int Write(object obj, bool enumerateCollection) else { ErrorRecord errorRecord = ConvertToErrorRecord(obj); - if (errorRecord != null) + if (errorRecord is not null) { numWritten++; _cmdlet.WriteError(errorRecord); @@ -522,7 +522,7 @@ private static ErrorRecord ConvertToErrorRecord(object obj) { ErrorRecord result = null; PSObject mshobj = obj as PSObject; - if (mshobj != null) + if (mshobj is not null) { object baseObject = mshobj.BaseObject; if (!(baseObject is PSCustomObject)) @@ -532,7 +532,7 @@ private static ErrorRecord ConvertToErrorRecord(object obj) } ErrorRecord errorRecordResult = obj as ErrorRecord; - if (errorRecordResult != null) + if (errorRecordResult is not null) { result = errorRecordResult; } 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..d5b94dfa011 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceListenerCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceListenerCommandBase.cs @@ -220,7 +220,7 @@ internal void AddTraceListenersToSources(Collection matchingSourc AddListenerToSources(matchingSources, _hostListener); } - if (FileListener != null) + if (FileListener is not null) { if (_fileListeners is null) { @@ -290,7 +290,7 @@ internal void AddTraceListenersToSources(Collection matchingSourc { // remove readonly attributes on the file System.IO.FileInfo fInfo = new System.IO.FileInfo(resolvedPath); - if (fInfo != null) + if (fInfo is not null) { // Save some disk write time by checking whether file is readonly.. if ((fInfo.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) @@ -327,7 +327,7 @@ internal void AddTraceListenersToSources(Collection matchingSourc fileOpenError = unauthorized; } - if (fileOpenError != null) + if (fileOpenError is not null) { ErrorRecord errorRecord = new ErrorRecord( @@ -352,7 +352,7 @@ internal void AddTraceListenersToSources(Collection matchingSourc error = notSupported; } - if (error != null) + if (error is not null) { ErrorRecord errorRecord = new ErrorRecord( diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs index dcb4e2e2418..ef154271790 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs @@ -486,7 +486,7 @@ private static bool TryParseSettingFileHelper(string[] args, int settingFileArgI { if (settingFileArgIndex >= args.Length) { - if (parser != null) + if (parser is not null) { parser.WriteCommandLineError( CommandLineParameterParserStrings.MissingSettingsFileArgument); @@ -502,7 +502,7 @@ private static bool TryParseSettingFileHelper(string[] args, int settingFileArgI } catch (Exception ex) { - if (parser != null) + if (parser is not null) { string error = string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.InvalidSettingsFileArgument, args[settingFileArgIndex], ex.Message); parser.WriteCommandLineError(error); @@ -513,7 +513,7 @@ private static bool TryParseSettingFileHelper(string[] args, int settingFileArgI if (!System.IO.File.Exists(configFile)) { - if (parser != null) + if (parser is not null) { string error = string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.SettingsFileNotExists, configFile); parser.WriteCommandLineError(error); @@ -546,7 +546,7 @@ internal static void EarlyParse(string[] args) { if (args is null) { - Dbg.Assert(args != null, "Argument 'args' to EarlyParseHelper should never be null"); + Dbg.Assert(args is not null, "Argument 'args' to EarlyParseHelper should never be null"); return; } @@ -604,7 +604,7 @@ private static (string SwitchKey, bool ShouldBreak) GetSwitchKey(string[] args, if (!CharExtensions.IsDash(switchKey[0]) && switchKey[0] != '/') { // then its a file - if (parser != null) + if (parser is not null) { --argIndex; parser.ParseFile(args, ref argIndex, noexitSeen); @@ -637,7 +637,7 @@ private static string NormalizeFilePath(string path) private static bool MatchSwitch(string switchKey, string match, string smallestUnambiguousMatch) { - Dbg.Assert(switchKey != null, "need a value"); + Dbg.Assert(switchKey is not null, "need a value"); Dbg.Assert(!string.IsNullOrEmpty(match), "need a value"); Dbg.Assert(match.Trim().ToLowerInvariant() == match, "match should be normalized to lowercase w/ no outside whitespace"); Dbg.Assert(smallestUnambiguousMatch.Trim().ToLowerInvariant() == smallestUnambiguousMatch, "match should be normalized to lowercase w/ no outside whitespace"); @@ -651,7 +651,7 @@ private static bool MatchSwitch(string switchKey, string match, string smallestU private void ShowHelp() { - Dbg.Assert(_helpText != null, "_helpText should not be null"); + Dbg.Assert(_helpText is not null, "_helpText should not be null"); _hostUI.WriteLine(string.Empty); _hostUI.Write(_helpText); if (_showExtendedHelp) @@ -717,7 +717,7 @@ internal void Parse(string[] args) private void ParseHelper(string[] args) { - Dbg.Assert(args != null, "Argument 'args' to ParseHelper should never be null"); + Dbg.Assert(args is not null, "Argument 'args' to ParseHelper should never be null"); bool noexitSeen = false; for (int i = 0; i < args.Length; ++i) @@ -1188,7 +1188,7 @@ bool TryGetBoolValue(string arg, out bool boolValue) exceptionMessage = e.Message; } - if (exceptionMessage != null) + if (exceptionMessage is not null) { WriteCommandLineError( string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.InvalidFileArgument, args[i], exceptionMessage), @@ -1238,7 +1238,7 @@ bool TryGetBoolValue(string arg, out bool boolValue) // If there was a pending parameter, add a named parameter // using the pending parameter and current argument - if (pendingParameter != null) + if (pendingParameter is not null) { _collectedArgs.Add(new CommandParameter(pendingParameter, arg)); pendingParameter = null; @@ -1285,7 +1285,7 @@ bool TryGetBoolValue(string arg, out bool boolValue) private bool ParseCommand(string[] args, ref int i, bool noexitSeen, bool isEncoded) { - if (_commandLineCommand != null) + if (_commandLineCommand is not null) { // we've already set the command, so squawk @@ -1406,7 +1406,7 @@ private bool CollectArgs(string[] args, ref int i) try { object[] a = StringToBase64Converter.Base64ToArgsConverter(args[i]); - if (a != null) + if (a is not null) { foreach (object obj in a) { diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs index cc94a51d97e..43f3052daec 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs @@ -2984,7 +2984,7 @@ private static HostException CreateHostException( internal static void MimicKeyPress(INPUT[] inputs) { - Dbg.Assert(inputs != null && inputs.Length > 0, "inputs should not be null or empty"); + Dbg.Assert(inputs is not null && inputs.Length > 0, "inputs should not be null or empty"); var numberOfSuccessfulEvents = NativeMethods.SendInput((uint)inputs.Length, inputs, Marshal.SizeOf()); if (numberOfSuccessfulEvents == 0) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs index 5db4ca48169..bc5fd9ea88f 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs @@ -102,7 +102,7 @@ internal sealed partial class ConsoleHost internal static int Start(string bannerText, string helpText, string[] args) { #if DEBUG - if (Environment.GetEnvironmentVariable("POWERSHELL_DEBUG_STARTUP") != null) + if (Environment.GetEnvironmentVariable("POWERSHELL_DEBUG_STARTUP") is not null) { while (!System.Diagnostics.Debugger.IsAttached) { @@ -184,7 +184,7 @@ internal static int Start(string bannerText, string helpText, string[] args) if ((s_cpp.ServerMode && s_cpp.NamedPipeServerMode) || (s_cpp.ServerMode && s_cpp.SocketServerMode) || (s_cpp.NamedPipeServerMode && s_cpp.SocketServerMode)) { s_tracer.TraceError("Conflicting server mode parameters, parameters must be used exclusively."); - if (s_theConsoleHost != null) + if (s_theConsoleHost is not null) { s_theConsoleHost.ui.WriteErrorLine(ConsoleHostStrings.ConflictingServerModeParameters); } @@ -230,7 +230,7 @@ internal static int Start(string bannerText, string helpText, string[] args) else { // Run PowerShell in normal console mode. - if (hostException != null) + if (hostException is not null) { // Unable to create console host. throw hostException; @@ -262,7 +262,7 @@ internal static int Start(string bannerText, string helpText, string[] args) } finally { - if (s_theConsoleHost != null) + if (s_theConsoleHost is not null) { #if LEGACYTELEMETRY TelemetryAPI.ReportExitTelemetry(s_theConsoleHost); @@ -362,14 +362,14 @@ private static bool BreakIntoDebugger() Debugger debugger = null; lock (host.hostGlobalLock) { - if (host._runspaceRef.Runspace != null && - host._runspaceRef.Runspace.GetCurrentlyRunningPipeline() != null) + if (host._runspaceRef.Runspace is not null && + host._runspaceRef.Runspace.GetCurrentlyRunningPipeline() is not null) { debugger = host._runspaceRef.Runspace.Debugger; } } - if (debugger != null) + if (debugger is not null) { debugger.SetDebuggerStepMode(true); return true; @@ -423,7 +423,7 @@ private static void SpinUpBreakHandlerThread(bool shouldEndSession) private static void HandleBreak() { ConsoleHost consoleHost = s_theConsoleHost; - if (consoleHost != null) + if (consoleHost is not null) { if (consoleHost.InDebugMode) { @@ -452,10 +452,10 @@ private static void HandleBreak() if (consoleHost.ShouldEndSession) { var runspaceRef = ConsoleHost.SingletonInstance._runspaceRef; - if (runspaceRef != null) + if (runspaceRef is not null) { var runspace = runspaceRef.Runspace; - if (runspace != null) + if (runspace is not null) { runspace.Close(); } @@ -476,7 +476,7 @@ private static void HandleBreak() private static bool StopPipeline(Pipeline cmd) { - if (cmd != null && + if (cmd is not null && (cmd.PipelineStateInfo.State == PipelineState.Running || cmd.PipelineStateInfo.State == PipelineState.Disconnected)) { @@ -507,7 +507,7 @@ internal static ConsoleHost SingletonInstance { get { - Dbg.Assert(s_theConsoleHost != null, "CreateSingletonInstance should be called before calling this method"); + Dbg.Assert(s_theConsoleHost is not null, "CreateSingletonInstance should be called before calling this method"); return s_theConsoleHost; } } @@ -565,7 +565,7 @@ public override PSHostUserInterface UI { get { - Dbg.Assert(ui != null, "ui should have been allocated in ctor"); + Dbg.Assert(ui is not null, "ui should have been allocated in ctor"); return ui; } } @@ -578,17 +578,17 @@ public void PushRunspace(Runspace newRunspace) if (_runspaceRef is null) { return; } RemoteRunspace remoteRunspace = newRunspace as RemoteRunspace; - Dbg.Assert(remoteRunspace != null, "Expected remoteRunspace != null"); + Dbg.Assert(remoteRunspace is not null, "Expected remoteRunspace is not null"); remoteRunspace.StateChanged += HandleRemoteRunspaceStateChanged; // Unsubscribe the local session debugger. - if (_runspaceRef.Runspace.Debugger != null) + if (_runspaceRef.Runspace.Debugger is not null) { _runspaceRef.Runspace.Debugger.DebuggerStop -= OnExecutionSuspended; } // Subscribe to debugger stop event. - if (remoteRunspace.Debugger != null) + if (remoteRunspace.Debugger is not null) { remoteRunspace.Debugger.DebuggerStop += OnExecutionSuspended; } @@ -600,7 +600,7 @@ public void PushRunspace(Runspace newRunspace) _runspaceRef.Override(remoteRunspace, hostGlobalLock, out _isRunspacePushed); RunspacePushed.SafeInvoke(this, EventArgs.Empty); - if (this.runningCmd != null) + if (this.runningCmd is not null) { EnterPSSessionCommand.ContinueCommand( remoteRunspace, @@ -660,7 +660,7 @@ public void PopRunspace() this.ShouldEndSession = true; } - if (_runspaceRef.Runspace.Debugger != null) + if (_runspaceRef.Runspace.Debugger is not null) { // Unsubscribe pushed runspace debugger. _runspaceRef.Runspace.Debugger.DebuggerStop -= OnExecutionSuspended; @@ -1013,7 +1013,7 @@ public override void EnterNestedPrompt() Executor.CurrentExecutor = null; lock (hostGlobalLock) { - IsNested = oldCurrent != null || this.ui.IsCommandCompletionRunning; + IsNested = oldCurrent is not null || this.ui.IsCommandCompletionRunning; } InputLoop.RunNewInputLoop(this, IsNested); @@ -1171,7 +1171,7 @@ private void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArg Exception e = null; - if (args != null) + if (args is not null) { e = (Exception)args.ExceptionObject; } @@ -1206,7 +1206,7 @@ private void Dispose(bool isDisposingNotFinalizing) if (!_isDisposed) { #if !UNIX - Dbg.Assert(breakHandlerGcHandle != null, "break handler should be set"); + Dbg.Assert(breakHandlerGcHandle is not null, "break handler should be set"); ConsoleControl.RemoveBreakHandler(); if (breakHandlerGcHandle.IsAllocated) { @@ -1221,17 +1221,17 @@ private void Dispose(bool isDisposingNotFinalizing) StopTranscribing(); } - if (_outputSerializer != null) + if (_outputSerializer is not null) { _outputSerializer.End(); } - if (_errorSerializer != null) + if (_errorSerializer is not null) { _errorSerializer.End(); } - if (_runspaceRef != null) + if (_runspaceRef is not null) { // NTRAID#Windows Out Of Band Releases-925297-2005/12/14 try @@ -1381,7 +1381,7 @@ internal TextWriter ConsoleTextWriter { get { - Dbg.Assert(_consoleWriter != null, "consoleWriter should have been initialized"); + Dbg.Assert(_consoleWriter is not null, "consoleWriter should have been initialized"); return _consoleWriter; } } @@ -1401,7 +1401,7 @@ internal TextWriter ConsoleTextWriter /// private uint Run(CommandLineParameterParser cpp, bool isPrestartWarned) { - Dbg.Assert(cpp != null, "CommandLine parameter parser cannot be null."); + Dbg.Assert(cpp is not null, "CommandLine parameter parser cannot be null."); uint exitCode = ExitCodeSuccess; do @@ -1525,7 +1525,7 @@ private uint DoRunspaceLoop(string initialCommand, bool skipProfiles, Collection private Exception InitializeRunspaceHelper(string command, Executor exec, Executor.ExecutionOptions options) { Dbg.Assert(!string.IsNullOrEmpty(command), "command should have a value"); - Dbg.Assert(exec != null, "non-null Executor instance needed"); + Dbg.Assert(exec is not null, "non-null Executor instance needed"); s_runspaceInitTracer.WriteLine("running command {0}", command); @@ -1540,7 +1540,7 @@ private Exception InitializeRunspaceHelper(string command, Executor exec, Execut exec.ExecuteCommand(command, out e, options); } - if (e != null) + if (e is not null) { ReportException(e, exec); } @@ -1554,7 +1554,7 @@ private void CreateRunspace(object runspaceCreationArgs) try { args = runspaceCreationArgs as RunspaceCreationEventArgs; - Dbg.Assert(args != null, "Event Arguments to CreateRunspace should not be null"); + Dbg.Assert(args is not null, "Event Arguments to CreateRunspace should not be null"); DoCreateRunspace(args.InitialCommand, args.SkipProfiles, args.StaMode, args.ConfigurationName, args.InitialCommandArgs); } catch (ConsoleHostStartupException startupException) @@ -1614,7 +1614,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(DefaultInitialSessionState != null, "DefaultInitialSessionState should not be null"); + Dbg.Assert(DefaultInitialSessionState is not null, "DefaultInitialSessionState should not be null"); s_runspaceInitTracer.WriteLine("Calling RunspaceFactory.CreateRunspace"); try @@ -1718,7 +1718,7 @@ private void OpenConsoleRunspace(Runspace runspace, bool staMode) private void DoRunspaceInitialization(bool skipProfiles, string initialCommand, string configurationName, Collection initialCommandArgs) { - if (_runspaceRef.Runspace.Debugger != null) + if (_runspaceRef.Runspace.Debugger is not null) { _runspaceRef.Runspace.Debugger.SetDebugMode(DebugModes.LocalScript | DebugModes.RemoteScript); _runspaceRef.Runspace.Debugger.DebuggerStop += this.OnExecutionSuspended; @@ -1727,7 +1727,7 @@ private void DoRunspaceInitialization(bool skipProfiles, string initialCommand, Executor exec = new Executor(this, false, false); // If working directory was specified, set it - if (s_cpp != null && s_cpp.WorkingDirectory != null) + if (s_cpp is not null && s_cpp.WorkingDirectory is not null) { Pipeline tempPipeline = exec.CreatePipeline(); var command = new Command("Set-Location"); @@ -1744,7 +1744,7 @@ private void DoRunspaceInitialization(bool skipProfiles, string initialCommand, exec.ExecuteCommandHelper(tempPipeline, out exception, Executor.ExecutionOptions.AddOutputter); } - if (exception != null) + if (exception is not null) { _lastRunspaceInitializationException = exception; ReportException(exception, exec); @@ -1829,7 +1829,7 @@ private void DoRunspaceInitialization(bool skipProfiles, string initialCommand, #endif // If a file was specified as the argument to run, then run it... - if (s_cpp != null && s_cpp.File != null) + if (s_cpp is not null && s_cpp.File is not null) { string filePath = s_cpp.File; @@ -1850,7 +1850,7 @@ private void DoRunspaceInitialization(bool skipProfiles, string initialCommand, tempPipeline.Commands.Add(c); - if (initialCommandArgs != null) + if (initialCommandArgs is not null) { // add the args passed to the command. @@ -1895,7 +1895,7 @@ private void DoRunspaceInitialization(bool skipProfiles, string initialCommand, // Pipeline.Invoke has thrown, that's bad. It means the script did not actually // execute properly. These exceptions should be reflected in the exit code - if (e1 != null) + if (e1 is not null) { if (!_noExit) { @@ -1919,7 +1919,7 @@ private void DoRunspaceInitialization(bool skipProfiles, string initialCommand, Pipeline tempPipeline = exec.CreatePipeline(initialCommand, true); - if (initialCommandArgs != null) + if (initialCommandArgs is not null) { // add the args passed to the command. @@ -1955,7 +1955,7 @@ private void DoRunspaceInitialization(bool skipProfiles, string initialCommand, exec.ExecuteCommandHelper(tempPipeline, out e1, Executor.ExecutionOptions.AddOutputter); } - if (e1 != null) + if (e1 is not null) { // Remember last exception _lastRunspaceInitializationException = e1; @@ -2032,8 +2032,8 @@ private void WriteErrorLine(string line) // Removed HandleUnexpectedExceptions infrastructure private void ReportException(Exception e, Executor exec) { - Dbg.Assert(e != null, "must supply an Exception"); - Dbg.Assert(exec != null, "must supply an Executor"); + Dbg.Assert(e is not null, "must supply an Exception"); + Dbg.Assert(exec is not null, "must supply an Executor"); // NTRAID#Windows Out Of Band Releases-915506-2005/09/09 // Removed HandleUnexpectedExceptions infrastructure @@ -2048,7 +2048,7 @@ private void ReportException(Exception e, Executor exec) IContainsErrorRecord icer = e as IContainsErrorRecord; - if (icer != null) + if (icer is not null) { error = icer.ErrorRecord; } @@ -2074,7 +2074,7 @@ private void ReportException(Exception e, Executor exec) exec.ExecuteCommandHelper(tempPipeline, out e1, Executor.ExecutionOptions.AddOutputter); } - if (e1 != null) + if (e1 is not null) { // that didn't work. Write out the error ourselves as a last resort. @@ -2106,7 +2106,7 @@ private void ReportExceptionFallback(Exception e, string header) // See if the exception has an error record attached to it... ErrorRecord er = null; IContainsErrorRecord icer = e as IContainsErrorRecord; - if (icer != null) + if (icer is not null) er = icer.ErrorRecord; if (e is PSRemotingTransportException) @@ -2124,7 +2124,7 @@ private void ReportExceptionFallback(Exception e, string header) } // Add the position message for the error if it's available. - if (er != null && er.InvocationInfo != null) + if (er is not null && er.InvocationInfo is not null) Console.Error.WriteLine(er.InvocationInfo.PositionMessage); } @@ -2149,7 +2149,7 @@ private void OnExecutionSuspended(object sender, DebuggerStopEventArgs e) { // Check local runspace internalHost to see if debugging is enabled. LocalRunspace localrunspace = LocalRunspace; - if ((localrunspace != null) && !localrunspace.ExecutionContext.EngineHostInterface.DebuggerEnabled) { return; } + if ((localrunspace is not null) && !localrunspace.ExecutionContext.EngineHostInterface.DebuggerEnabled) { return; } _debuggerStopEventArgs = e; InputLoop baseLoop = null; @@ -2161,7 +2161,7 @@ private void OnExecutionSuspended(object sender, DebuggerStopEventArgs e) // For remote debugging block data coming from the main (not-nested) // running command. baseLoop = InputLoop.GetNonNestedLoop(); - if (baseLoop != null) + if (baseLoop is not null) { baseLoop.BlockCommandOutput(); } @@ -2195,7 +2195,7 @@ private void OnExecutionSuspended(object sender, DebuggerStopEventArgs e) // // Write the source line // - if (e.InvocationInfo != null) + if (e.InvocationInfo is not null) { // line = StringUtil.Format(ConsoleHostStrings.DebuggerSourceCodeFormat, scriptFileName, e.InvocationInfo.ScriptLineNumber, e.InvocationInfo.Line); WriteDebuggerMessage(e.InvocationInfo.PositionMessage); @@ -2209,7 +2209,7 @@ private void OnExecutionSuspended(object sender, DebuggerStopEventArgs e) finally { _debuggerStopEventArgs = null; - if (baseLoop != null) + if (baseLoop is not null) { baseLoop.ResumeCommandOutput(); } @@ -2416,7 +2416,7 @@ internal void Run(bool inputLoopIsNested) System.Management.Automation.Host.PSHostUserInterface c = _parent.UI; ConsoleHostUserInterface ui = c as ConsoleHostUserInterface; - Dbg.Assert(ui != null, "Host.UI should return an instance."); + Dbg.Assert(ui is not null, "Host.UI should return an instance."); bool inBlockMode = false; bool previousResponseWasEmpty = false; @@ -2525,7 +2525,7 @@ internal void Run(bool inputLoopIsNested) } } - Dbg.Assert(line != null, "line should not be null"); + Dbg.Assert(line is not null, "line should not be null"); Dbg.Assert(line.Length > 0 || _parent.InDebugMode, "line should not be empty unless the host is in debug mode"); Dbg.Assert(!inBlockMode, "should not be in block mode at point of pipeline execution"); @@ -2535,18 +2535,18 @@ internal void Run(bool inputLoopIsNested) { DebuggerCommandResults results = ProcessDebugCommand(line, out e); - if (results.ResumeAction != null) + if (results.ResumeAction is not null) { _parent.ExitDebugMode(results.ResumeAction.Value); } - if (e != null) + if (e is not null) { var ex = e as PSInvalidOperationException; if (e is PSRemotingTransportException || e is RemoteException || - (ex != null && - ex.ErrorRecord != null && + (ex is not null && + ex.ErrorRecord is not null && ex.ErrorRecord.FullyQualifiedErrorId.Equals("Debugger:CannotProcessCommandNotStopped", StringComparison.OrdinalIgnoreCase))) { // Debugger session is broken. Exit nested loop. @@ -2586,7 +2586,7 @@ e is RemoteException || bht = _parent._breakHandlerThread; } - if (bht != null) + if (bht is not null) { bht.Join(); } @@ -2596,14 +2596,14 @@ e is RemoteException || ui.ResetProgress(); - if (e != null) + if (e is not null) { // Handle incomplete parse and other errors. inBlockMode = HandleErrors(e, line, inBlockMode, ref inputBlock); // If a remote runspace is pushed and it is not in a good state // then pop it. - if (_isRunspacePushed && (_parent.Runspace != null) && + if (_isRunspacePushed && (_parent.Runspace is not null) && ((_parent.Runspace.RunspaceStateInfo.State != RunspaceState.Opened) || (_parent.Runspace.RunspaceAvailability != RunspaceAvailability.Available))) { @@ -2629,7 +2629,7 @@ e is RemoteException || internal void BlockCommandOutput() { RemotePipeline rCmdPipeline = _parent.runningCmd as RemotePipeline; - if (rCmdPipeline != null) + if (rCmdPipeline is not null) { rCmdPipeline.DrainIncomingData(); rCmdPipeline.SuspendIncomingData(); @@ -2643,7 +2643,7 @@ internal void BlockCommandOutput() internal void ResumeCommandOutput() { RemotePipeline rCmdPipeline = _parent.runningCmd as RemotePipeline; - if (rCmdPipeline != null) + if (rCmdPipeline is not null) { rCmdPipeline.ResumeIncomingData(); } @@ -2655,7 +2655,7 @@ internal void ResumeCommandOutput() private bool HandleErrors(Exception e, string line, bool inBlockMode, ref StringBuilder inputBlock) { - Dbg.Assert(e != null, "Exception reference should not be null."); + Dbg.Assert(e is not null, "Exception reference should not be null."); if (IsIncompleteParseException(e)) { @@ -2794,7 +2794,7 @@ private string EvaluatePrompt() if (_isRunspacePushed) { RemoteRunspace remoteRunspace = _parent.Runspace as RemoteRunspace; - if (remoteRunspace != null) + if (remoteRunspace is not null) { promptString = HostUtilities.GetRemotePrompt(remoteRunspace, promptString, _parent._inPushedConfiguredSession); } @@ -2827,11 +2827,11 @@ private string EvaluateDebugPrompt() } PSObject prompt = output.ReadAndRemoveAt0(); - string promptString = (prompt != null) ? (prompt.BaseObject as string) : null; - if (promptString != null) + string promptString = (prompt is not null) ? (prompt.BaseObject as string) : null; + if (promptString is not null) { RemoteRunspace remoteRunspace = _parent.Runspace as RemoteRunspace; - if (remoteRunspace != null) + if (remoteRunspace is not null) { promptString = HostUtilities.GetRemotePrompt(remoteRunspace, promptString, _parent._inPushedConfiguredSession); } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs index aec2aa527cb..fc68b832940 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs @@ -371,7 +371,7 @@ public override catch (HostException e) { Win32Exception win32exception = e.InnerException as Win32Exception; - if (win32exception != null && + if (win32exception is not null && win32exception.NativeErrorCode == 0x57) { throw PSTraceSource.NewArgumentOutOfRangeException("value", value, @@ -821,7 +821,7 @@ public override string WindowTitle const int MaxWindowTitleLength = 1023; const int MinWindowTitleLength = 0; - if (value != null) + if (value is not null) { if ( value.Length >= MinWindowTitleLength && diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostTranscript.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostTranscript.cs index 419e2d52d56..060d2a241b4 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostTranscript.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostTranscript.cs @@ -112,7 +112,7 @@ internal void WriteToTranscript(ReadOnlySpan text, bool newLine) { lock (_transcriptionStateLock) { - if (_isTranscribing && _transcriptionWriter != null) + if (_isTranscribing && _transcriptionWriter is not null) { if (newLine) { diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs index 51703ee385f..7fd6f3c5746 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs @@ -57,7 +57,7 @@ internal partial class ConsoleHostUserInterface : System.Management.Automation.H internal ConsoleHostUserInterface(ConsoleHost parent) { - Dbg.Assert(parent != null, "parent may not be null"); + Dbg.Assert(parent is not null, "parent may not be null"); _parent = parent; _rawui = new ConsoleHostRawUserInterface(this); @@ -98,7 +98,7 @@ public override PSHostRawUserInterface RawUI { get { - Dbg.Assert(_rawui != null, "rawui should have been created by ctor"); + Dbg.Assert(_rawui is not null, "rawui should have been created by ctor"); // no locking because this is read-only, and allocated in the ctor. @@ -136,7 +136,7 @@ internal bool IsCommandCompletionRunning { get { - return _commandCompletionPowerShell != null && + return _commandCompletionPowerShell is not null && _commandCompletionPowerShell.InvocationStateInfo.State == PSInvocationState.Running; } } @@ -207,7 +207,7 @@ public override string ReadLineMaskedAsString() } StringBuilder resultSb = result as StringBuilder; - Dbg.Assert(resultSb != null, "ReadLineMaskedAsString did not return a stringBuilder"); + Dbg.Assert(resultSb is not null, "ReadLineMaskedAsString did not return a stringBuilder"); return resultSb.ToString(); } @@ -240,7 +240,7 @@ public override SecureString ReadLineAsSecureString() } SecureString secureResult = result as SecureString; - System.Management.Automation.Diagnostics.Assert(secureResult != null, "ReadLineSafe did not return a SecureString"); + System.Management.Automation.Diagnostics.Assert(secureResult is not null, "ReadLineSafe did not return a SecureString"); return secureResult; } @@ -725,7 +725,7 @@ private void WriteImpl(string value, bool newLine) } // If the test hook is set, write to it and continue. - if (s_h != null) + if (s_h is not null) { if (newLine) { @@ -1475,7 +1475,7 @@ internal string ReadLine(bool endOnTab, string initialContent, out ReadLineResul result = ReadLineResult.endedOnEnter; // If the test hook is set, read from it. - if (s_h != null) return s_h.ReadLine(); + if (s_h is not null) return s_h.ReadLine(); string restOfLine = null; @@ -1492,7 +1492,7 @@ internal string ReadLine(bool endOnTab, string initialContent, out ReadLineResul PostRead(); } - if (restOfLine != null) + if (restOfLine is not null) s += restOfLine; return s; @@ -1626,7 +1626,7 @@ private string ReadLineFromConsole(bool endOnTab, string initialContent, bool ca keyInfo = Console.ReadKey(true); #else s += ConsoleControl.ReadConsole(handle, initialContent.Length, inputBuffer, MaxInputLineLength, endOnTab, out keyState); - Dbg.Assert(s != null, "s should never be null"); + Dbg.Assert(s is not null, "s should never be null"); #endif #if UNIX @@ -1850,7 +1850,7 @@ private string ReadLineFromConsole(bool endOnTab, string initialContent, bool ca Dbg.Assert( (s is null && result == ReadLineResult.endedOnBreak) - || (s != null && result != ReadLineResult.endedOnBreak), + || (s is not null && result != ReadLineResult.endedOnBreak), "s should only be null if input ended with a break"); return s; @@ -1999,7 +1999,7 @@ internal string ReadLineWithTabCompletion(Executor exec) } var completionResult = commandCompletion.GetNextResult(rlResult == ReadLineResult.endedOnTab); - if (completionResult != null) + if (completionResult is not null) { completedInput = completionInput.Substring(0, commandCompletion.ReplacementIndex) + completionResult.CompletionText; @@ -2131,7 +2131,7 @@ private CommandCompletion GetNewCompletionResults(string input) var runspace = _parent.Runspace; var debugger = runspace.Debugger; - if ((debugger != null) && debugger.InBreakpoint) + if ((debugger is not null) && debugger.InBreakpoint) { // If in debug stop mode do command completion though debugger process command. try @@ -2171,7 +2171,7 @@ private bool TryInvokeUserDefinedReadLine(out string input) // this function. var runspace = _parent.LocalRunspace; - if (runspace != null && + if (runspace is not null && runspace.Engine.Context.EngineIntrinsics.InvokeCommand.GetCommands(CustomReadlineCommand, CommandTypes.Function | CommandTypes.Cmdlet, nameIsPattern: false).Any()) { @@ -2179,7 +2179,7 @@ private bool TryInvokeUserDefinedReadLine(out string input) { PowerShell ps; if ((runspace.ExecutionContext.EngineHostInterface.NestedPromptCount > 0) && - (Runspace.DefaultRunspace != null)) + (Runspace.DefaultRunspace is not null)) { ps = PowerShell.Create(RunspaceMode.CurrentRunspace); } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs index f5091bee082..73deab170f3 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs @@ -28,7 +28,7 @@ class ConsoleHostUserInterface : System.Management.Automation.Host.PSHostUserInt // so we need the lock lock (_instanceLock) { - if (_progPaneUpdateTimer != null) + if (_progPaneUpdateTimer is not null) { // Stop update a progress pane and destroy timer _progPaneUpdateTimer.Dispose(); @@ -39,9 +39,9 @@ class ConsoleHostUserInterface : System.Management.Automation.Host.PSHostUserInt // So we cannot guarantee the flag is truly set to 0. // 2. When creating a new timer in 'HandleIncomingProgressRecord', we will set the flag to 1 anyway - if (_progPane != null) + if (_progPane is not null) { - Dbg.Assert(_pendingProgress != null, "How can you have a progress pane and no backing data structure?"); + Dbg.Assert(_pendingProgress is not null, "How can you have a progress pane and no backing data structure?"); _progPane.Hide(); _progPane = null; @@ -60,7 +60,7 @@ class ConsoleHostUserInterface : System.Management.Automation.Host.PSHostUserInt void HandleIncomingProgressRecord(Int64 sourceId, ProgressRecord record) { - Dbg.Assert(record != null, "record should not be null"); + Dbg.Assert(record is not null, "record should not be null"); if (_pendingProgress is null) { @@ -113,7 +113,7 @@ class ConsoleHostUserInterface : System.Management.Automation.Host.PSHostUserInt void PreWrite() { - if (_progPane != null) + if (_progPane is not null) { _progPane.Hide(); } @@ -123,7 +123,7 @@ class ConsoleHostUserInterface : System.Management.Automation.Host.PSHostUserInt void PostWrite() { - if (_progPane != null) + if (_progPane is not null) { _progPane.Show(); } @@ -152,7 +152,7 @@ class ConsoleHostUserInterface : System.Management.Automation.Host.PSHostUserInt void PreRead() { - if (_progPane != null) + if (_progPane is not null) { _progPane.Hide(); } @@ -162,7 +162,7 @@ class ConsoleHostUserInterface : System.Management.Automation.Host.PSHostUserInt void PostRead() { - if (_progPane != null) + if (_progPane is not null) { _progPane.Show(); } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs index 2b9aa7d799c..7d511ef7403 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs @@ -46,7 +46,7 @@ private static { foreach (FieldDescription fd in descriptions) { - if (fd != null) + if (fd is not null) { if (!string.IsNullOrEmpty(fd.HelpMessage)) { @@ -175,7 +175,7 @@ public override fieldType = typeof(string); } - if (fieldType.GetInterface(typeof(IList).FullName) != null) + if (fieldType.GetInterface(typeof(IList).FullName) is not null) { // field is a type implementing IList ArrayList inputList = new ArrayList(); // stores all converted user input before @@ -292,7 +292,7 @@ out object convertedObj SecureString secureString = ReadLineAsSecureString(); convertedObj = secureString; cancelInput = (convertedObj is null); - if ((secureString != null) && (secureString.Length == 0) && listInput) + if ((secureString is not null) && (secureString.Length == 0) && listInput) { endListInput = true; } @@ -309,7 +309,7 @@ out object convertedObj targetName: string.Empty); convertedObj = credential; cancelInput = (convertedObj is null); - if ((credential != null) && (credential.Password.Length == 0) && listInput) + if ((credential is not null) && (credential.Password.Length == 0) && listInput) { endListInput = true; } @@ -344,8 +344,8 @@ out object convertedObj private string PromptReadInput(string fieldPrompt, FieldDescription desc, bool fieldEchoOnPrompt, bool listInput, out bool endListInput, out bool cancelled) { - Dbg.Assert(fieldPrompt != null, "fieldPrompt should never be null when PromptReadInput is called"); - Dbg.Assert(desc != null, "desc should never be null when PromptReadInput is called"); + Dbg.Assert(fieldPrompt is not null, "fieldPrompt should never be null when PromptReadInput is called"); + Dbg.Assert(desc is not null, "desc should never be null when PromptReadInput is called"); string processedInputString = null; endListInput = false; @@ -364,7 +364,7 @@ private string PromptReadInput(string fieldPrompt, FieldDescription desc, bool f { object userInput = ReadLineSafe(false, null); string userInputString = userInput as string; - System.Management.Automation.Diagnostics.Assert(userInputString != null, "ReadLineSafe did not return a string"); + System.Management.Automation.Diagnostics.Assert(userInputString is not null, "ReadLineSafe did not return a string"); rawInputString = userInputString; } @@ -406,7 +406,7 @@ private string PromptReadInput(string fieldPrompt, FieldDescription desc, bool f /// An object of type fieldType that inputString represents. private PromptCommonInputErrors PromptTryConvertTo(Type fieldType, bool isFromRemoteHost, string inputString, out object convertedObj) { - Dbg.Assert(fieldType != null, "fieldType should never be null when PromptTryConvertTo is called"); + Dbg.Assert(fieldType is not null, "fieldType should never be null when PromptTryConvertTo is called"); convertedObj = inputString; // do not do any type conversion if the prompt request is coming from a remote host @@ -423,7 +423,7 @@ private PromptCommonInputErrors PromptTryConvertTo(Type fieldType, bool isFromRe catch (PSInvalidCastException e) { Exception innerE = e.InnerException; - if (innerE != null) + if (innerE is not null) { if (innerE is OverflowException) { @@ -478,9 +478,9 @@ private PromptCommonInputErrors PromptTryConvertTo(Type fieldType, bool isFromRe private string PromptCommandMode(string input, FieldDescription desc, out bool inputDone) { - Dbg.Assert(input != null && input.StartsWith(PromptCommandPrefix, StringComparison.OrdinalIgnoreCase), + Dbg.Assert(input is not null && input.StartsWith(PromptCommandPrefix, StringComparison.OrdinalIgnoreCase), string.Format(CultureInfo.InvariantCulture, "input should start with {0}", PromptCommandPrefix)); - Dbg.Assert(desc != null, "desc should never be null when PromptCommandMode is called"); + Dbg.Assert(desc is not null, "desc should never be null when PromptCommandMode is called"); string command = input.Substring(1); inputDone = true; diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs index d05dee0e446..08ff4fbe62f 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs @@ -185,7 +185,7 @@ public Collection PromptForChoice(string caption, Dictionary defaultChoiceKeys = new Dictionary(); - if (defaultChoices != null) + if (defaultChoices is not null) { foreach (int defaultChoice in defaultChoices) { @@ -294,7 +294,7 @@ private void WriteChoicePrompt(string[,] hotkeysAndPlainLabels, Dictionary defaultChoiceKeys, bool shouldEmulateForMultipleChoiceSelection) { - System.Management.Automation.Diagnostics.Assert(defaultChoiceKeys != null, "defaultChoiceKeys cannot be null."); + System.Management.Automation.Diagnostics.Assert(defaultChoiceKeys is not null, "defaultChoiceKeys cannot be null."); ConsoleColor fg = RawUI.ForegroundColor; ConsoleColor bg = RawUI.BackgroundColor; @@ -411,8 +411,8 @@ private string ReadChoiceResponse(out ReadLineResult result) private void ShowChoiceHelp(Collection choices, string[,] hotkeysAndPlainLabels) { - Dbg.Assert(choices != null, "choices: expected a value"); - Dbg.Assert(hotkeysAndPlainLabels != null, "hotkeysAndPlainLabels: expected a value"); + Dbg.Assert(choices is not null, "choices: expected a value"); + Dbg.Assert(hotkeysAndPlainLabels is not null, "hotkeysAndPlainLabels: expected a value"); for (int i = 0; i < choices.Count; ++i) { diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleTextWriter.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleTextWriter.cs index c875bc0c506..98beeeb2384 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleTextWriter.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleTextWriter.cs @@ -21,7 +21,7 @@ class ConsoleTextWriter : TextWriter : base(System.Globalization.CultureInfo.CurrentCulture) { - Dbg.Assert(ui != null, "ui needs a value"); + Dbg.Assert(ui is not null, "ui needs a value"); _ui = ui; } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs index 8e79059141a..93d04b8155e 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs @@ -52,7 +52,7 @@ internal enum ExecutionOptions /// internal Executor(ConsoleHost parent, bool useNestedPipelines, bool isPromptFunctionExecutor) { - Dbg.Assert(parent != null, "parent should not be null"); + Dbg.Assert(parent is not null, "parent should not be null"); _parent = parent; this.useNestedPipelines = useNestedPipelines; @@ -111,7 +111,7 @@ private void AsyncPipelineFailureHandler(Exception ex) { ErrorRecord er = null; IContainsErrorRecord cer = ex as IContainsErrorRecord; - if (cer != null) + if (cer is not null) { er = cer.ErrorRecord; // Exception inside the error record is ParentContainsErrorRecordException which @@ -250,7 +250,7 @@ internal void ExecuteCommandAsyncHelper(Pipeline tempPipeline, out Exception exc pipelineWaiter.Wait(); // report error if pipeline failed - if (tempPipeline.PipelineStateInfo.State == PipelineState.Failed && tempPipeline.PipelineStateInfo.Reason != null) + if (tempPipeline.PipelineStateInfo.State == PipelineState.Failed && tempPipeline.PipelineStateInfo.Reason is not null) { if (_parent.OutputFormat == Serialization.DataFormat.Text) { @@ -331,7 +331,7 @@ internal Collection ExecuteCommand(string command, out Exception excep var addOutputter = ((options & ExecutionOptions.AddOutputter) > 0); if (addOutputter && !_parent.RunspaceRef.IsRunspaceOverridden && - _parent.RunspaceRef.Runspace.ExecutionContext.Modules != null && + _parent.RunspaceRef.Runspace.ExecutionContext.Modules is not null && _parent.RunspaceRef.Runspace.ExecutionContext.Modules.IsImplicitRemotingModuleLoaded && Utils.TryRunAsImplicitBatch(command, _parent.RunspaceRef.Runspace)) { @@ -358,7 +358,7 @@ private Command GetOutDefaultCommand(bool endOfStatement) internal Collection ExecuteCommandHelper(Pipeline tempPipeline, out Exception exceptionThrown, ExecutionOptions options) { - Dbg.Assert(tempPipeline != null, "command should have a value"); + Dbg.Assert(tempPipeline is not null, "command should have a value"); exceptionThrown = null; @@ -394,7 +394,7 @@ internal Collection ExecuteCommandHelper(Pipeline tempPipeline, out Ex } var lastCmd = executeCommands.Last(); - if (!((lastCmd.CommandText != null) && + if (!((lastCmd.CommandText is not null) && (lastCmd.CommandText.Equals("Out-Default", StringComparison.OrdinalIgnoreCase))) ) { @@ -449,7 +449,7 @@ internal Collection ExecuteCommand(string command) do { result = ExecuteCommand(command, out e, ExecutionOptions.None); - if (e != null) + if (e is not null) { break; } @@ -488,7 +488,7 @@ internal string ExecuteCommandAndGetResultAsString(string command, out Exception { Collection streamResults = ExecuteCommand(command, out exceptionThrown, ExecutionOptions.None); - if (exceptionThrown != null) + if (exceptionThrown is not null) { break; } @@ -506,7 +506,7 @@ internal string ExecuteCommandAndGetResultAsString(string command, out Exception // ToString() on the PSObject because there is no default runspace // available. PSObject msho = streamResults[0] as PSObject; - if (msho != null) + if (msho is not null) result = msho.BaseObject.ToString(); else result = streamResults[0].ToString(); @@ -564,7 +564,7 @@ internal string ExecuteCommandAndGetResultAsString(string command, out Exception { Collection streamResults = ExecuteCommand(command, out exceptionThrown, ExecutionOptions.None); - if (exceptionThrown != null) + if (exceptionThrown is not null) { break; } @@ -593,7 +593,7 @@ private void Cancel() lock (_instanceStateLock) { - if (_pipeline != null && !_cancelled) + if (_pipeline is not null && !_cancelled) { _cancelled = true; @@ -610,7 +610,7 @@ private void Cancel() internal void BlockCommandOutput() { RemotePipeline remotePipeline = _pipeline as RemotePipeline; - if (remotePipeline != null) + if (remotePipeline is not null) { // Waits until queued data is handled. remotePipeline.DrainIncomingData(); @@ -623,7 +623,7 @@ internal void BlockCommandOutput() internal void ResumeCommandOutput() { RemotePipeline remotePipeline = _pipeline as RemotePipeline; - if (remotePipeline != null) + if (remotePipeline is not null) { // Resumes data flow. remotePipeline.ResumeIncomingData(); @@ -721,7 +721,7 @@ internal static void CancelCurrentExecutor() temp = s_currentExecutor; } - if (temp != null) + if (temp is not null) { temp.Cancel(); } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs index cfe7f0c16e1..55eff588061 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs @@ -78,7 +78,7 @@ public static int Start(string consoleFilePath, [MarshalAs(UnmanagedType.LPArray } catch (HostException e) { - if (e.InnerException != null && e.InnerException.GetType() == typeof(Win32Exception)) + if (e.InnerException is not null && e.InnerException.GetType() == typeof(Win32Exception)) { Win32Exception win32e = e.InnerException as Win32Exception; diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs index 269115eb1e2..65b790f5b52 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs @@ -47,7 +47,7 @@ class PendingProgress void Update(Int64 sourceId, ProgressRecord record) { - Dbg.Assert(record != null, "record should not be null"); + Dbg.Assert(record is not null, "record should not be null"); do { @@ -62,9 +62,9 @@ class PendingProgress ProgressNode foundNode = FindNodeById(sourceId, record.ActivityId, out listWhereFound, out indexWhereFound); - if (foundNode != null) + if (foundNode is not null) { - Dbg.Assert(listWhereFound != null, "node found, but list not identified"); + Dbg.Assert(listWhereFound is not null, "node found, but list not identified"); Dbg.Assert(indexWhereFound >= 0, "node found, but index not returned"); if (record.RecordType == ProgressRecordType.Completed) @@ -119,7 +119,7 @@ class PendingProgress if (newNode.ParentActivityId >= 0) { ProgressNode parentNode = FindNodeById(newNode.SourceId, newNode.ParentActivityId); - if (parentNode != null) + if (parentNode is not null) { if (parentNode.Children is null) { @@ -187,9 +187,9 @@ class PendingProgress #if DEBUG || ASSERTIONS_TRACE ProgressNode nodeToRemove = (ProgressNode)nodes[indexToRemove]; - Dbg.Assert(nodes != null, "can't remove nodes from a null list"); + Dbg.Assert(nodes is not 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(nodes[indexToRemove] is not null, "no node at specified index"); Dbg.Assert(nodeToRemove.Children is null || nodeToRemove.Children.Count == 0, "can't remove a node with children"); #endif @@ -207,16 +207,16 @@ class PendingProgress { ProgressNode nodeToRemove = (ProgressNode)nodes[indexToRemove]; - Dbg.Assert(nodes != null, "can't remove nodes from a null list"); + Dbg.Assert(nodes is not null, "can't remove nodes from a null list"); Dbg.Assert(indexToRemove < nodes.Count, "index is not in list"); - Dbg.Assert(nodeToRemove != null, "no node at specified index"); + Dbg.Assert(nodeToRemove is not null, "no node at specified index"); if (nodeToRemove is null) { return; } - if (nodeToRemove.Children != null) + if (nodeToRemove.Children is not null) { // promote the children. @@ -479,7 +479,7 @@ internal override for (int i = 0; i < nodes.Count; ++i) { ProgressNode node = (ProgressNode)nodes[i]; - Dbg.Assert(node != null, "nodes should not contain null elements"); + Dbg.Assert(node is not null, "nodes should not contain null elements"); if (node.Age >= oldestSoFar && node.Style == style) { @@ -487,11 +487,11 @@ internal override oldestSoFar = found.Age; } - if (node.Children != null) + if (node.Children is not null) { ProgressNode child = FindOldestNodeOfGivenStyle(node.Children, oldestSoFar, style); - if (child != null) + if (child is not null) { // In this universe, parents can be younger than their children. We found a child older than us. @@ -502,7 +502,7 @@ internal override } #if DEBUG || ASSERTIONS_TRACE - if (found != null) + if (found is not null) { Dbg.Assert(found.Style == style, "unexpected style"); Dbg.Assert(found.Age >= oldestSoFar, "unexpected age"); @@ -566,7 +566,7 @@ internal override string[] Render(int maxWidth, int maxHeight, PSHostRawUserInterface rawUI) { - Dbg.Assert(_topLevelNodes != null, "Shouldn't need to render progress if no data exists"); + Dbg.Assert(_topLevelNodes is not null, "Shouldn't need to render progress if no data exists"); Dbg.Assert(maxWidth > 0, "maxWidth is too small"); Dbg.Assert(maxHeight >= 3, "maxHeight is too small"); @@ -636,8 +636,8 @@ internal override void RenderHelper(ArrayList strings, ArrayList nodes, int indentation, int maxWidth, PSHostRawUserInterface rawUI) { - Dbg.Assert(strings != null, "strings should not be null"); - Dbg.Assert(nodes != null, "nodes should not be null"); + Dbg.Assert(strings is not null, "strings should not be null"); + Dbg.Assert(nodes is not null, "nodes should not be null"); if (nodes is null) { @@ -650,7 +650,7 @@ internal override node.Render(strings, indentation, maxWidth, rawUI); - if (node.Children != null) + if (node.Children is not null) { // indent only if the rendering of node actually added lines to the strings. @@ -737,14 +737,14 @@ private int TallyHeight(PSHostRawUserInterface rawUi, int maxHeight, int maxWidt for (int i = 0; i < nodes.Count; ++i) { ProgressNode node = (ProgressNode)nodes[i]; - Dbg.Assert(node != null, "nodes should not contain null elements"); + Dbg.Assert(node is not null, "nodes should not contain null elements"); if (node.Style != style) { return false; } - if (node.Children != null) + if (node.Children is not null) { if (!AllNodesHaveGivenStyle(node.Children, style)) { @@ -899,7 +899,7 @@ internal override int CompressToFit(PSHostRawUserInterface rawUi, int maxHeight, int maxWidth) { - Dbg.Assert(_topLevelNodes != null, "Shouldn't need to compress if no data exists"); + Dbg.Assert(_topLevelNodes is not null, "Shouldn't need to compress if no data exists"); int nodesCompressed = 0; @@ -1000,14 +1000,14 @@ internal static for (int i = 0; i < nodes.Count; ++i) { ProgressNode node = (ProgressNode)nodes[i]; - Dbg.Assert(node != null, "nodes should not contain null elements"); + Dbg.Assert(node is not null, "nodes should not contain null elements"); if (!v.Visit(node, nodes, i)) { return; } - if (node.Children != null) + if (node.Children is not null) { VisitNodes(node.Children, v); } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressNode.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressNode.cs index 35066c0bf09..5bbb6e06993 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressNode.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressNode.cs @@ -85,7 +85,7 @@ namespace Microsoft.PowerShell void Render(ArrayList strCollection, int indentation, int maxWidth, PSHostRawUserInterface rawUI) { - Dbg.Assert(strCollection != null, "strCollection should not be null"); + Dbg.Assert(strCollection is not null, "strCollection should not be null"); Dbg.Assert(indentation >= 0, "indentation is negative"); Dbg.Assert(this.RecordType != ProgressRecordType.Completed, "should never render completed records"); diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs index f34125fb4f0..32b23228964 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs @@ -46,7 +46,7 @@ class ProgressPane { get { - return (_savedRegion != null); + return (_savedRegion is not null); } } @@ -169,7 +169,7 @@ class ProgressPane void Show(PendingProgress pendingProgress) { - Dbg.Assert(pendingProgress != null, "pendingProgress may not be null"); + Dbg.Assert(pendingProgress is not null, "pendingProgress may not be null"); _bufSize = _rawui.BufferSize; @@ -192,7 +192,7 @@ class ProgressPane // NTRAID#Windows OS Bugs-1061752-2004/12/15-sburns should read a skin setting here... BufferCell[,] newRegion = _rawui.NewBufferCellArray(contents, _ui.ProgressForegroundColor, _ui.ProgressBackgroundColor); - Dbg.Assert(newRegion != null, "NewBufferCellArray has failed!"); + Dbg.Assert(newRegion is not null, "NewBufferCellArray has failed!"); if (_progressRegion is null) { diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs index 47fd6df2c7e..f5b8e087b91 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs @@ -65,7 +65,7 @@ class WrappedSerializer : Serialization : base(dataFormat, streamName) { - Dbg.Assert(output != null, "output should have a value"); + Dbg.Assert(output is not null, "output should have a value"); textWriter = output; switch (format) @@ -154,7 +154,7 @@ class WrappedDeserializer : Serialization : base(dataFormat, streamName) { - Dbg.Assert(input != null, "input should have a value"); + Dbg.Assert(input is not null, "input should have a value"); // If the data format is none - do nothing... if (dataFormat == DataFormat.None) @@ -206,7 +206,7 @@ class WrappedDeserializer : Serialization return null; } - if (_firstLine != null) + if (_firstLine is not null) { o = _firstLine; _firstLine = null; diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/StartTranscriptCmdlet.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/StartTranscriptCmdlet.cs index 75cef89b93f..51c6d0a4f8f 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/StartTranscriptCmdlet.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/StartTranscriptCmdlet.cs @@ -169,7 +169,7 @@ protected override void BeginProcessing() if (value is null) { // If they've specified an output directory, use it. Otherwise, use "My Documents" - if (OutputDirectory != null) + if (OutputDirectory is not null) { _outFilename = System.Management.Automation.Host.PSHostUserInterface.GetTranscriptPath(OutputDirectory, false); _isLiteralPath = true; diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/StopTranscriptCmdlet.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/StopTranscriptCmdlet.cs index 9fae35ac83e..6f0c5e336eb 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/StopTranscriptCmdlet.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/StopTranscriptCmdlet.cs @@ -26,7 +26,7 @@ protected override try { string outFilename = Host.UI.StopTranscribing(); - if (outFilename != null) + if (outFilename is not null) { PSObject outputObject = new PSObject( StringUtil.Format(TranscriptStrings.TranscriptionStopped, outFilename)); diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/UpdatesNotification.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/UpdatesNotification.cs index 8052015248f..f50528b9d6e 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/UpdatesNotification.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/UpdatesNotification.cs @@ -90,7 +90,7 @@ internal static void ShowUpdateNotification(PSHostUserInterface hostUI) updateFilePath: out _, out SemanticVersion lastUpdateVersion, lastUpdateDate: out _) - && lastUpdateVersion != null) + && lastUpdateVersion is not null) { string releaseTag = lastUpdateVersion.ToString(); string notificationMsgTemplate = s_notificationType == NotificationType.LTS @@ -145,7 +145,7 @@ internal static async Task CheckForUpdates() // Daily builds do not support update notifications string preReleaseLabel = PSVersionInfo.PSCurrentVersion.PreReleaseLabel; - if (preReleaseLabel != null && preReleaseLabel.StartsWith("daily", StringComparison.OrdinalIgnoreCase)) + if (preReleaseLabel is not null && preReleaseLabel.StartsWith("daily", StringComparison.OrdinalIgnoreCase)) { return; } @@ -168,7 +168,7 @@ internal static async Task CheckForUpdates() out DateTime lastUpdateDate); DateTime today = DateTime.UtcNow; - if (parseSuccess && updateFilePath != null && (today - lastUpdateDate).TotalDays < 7) + if (parseSuccess && updateFilePath is not null && (today - lastUpdateDate).TotalDays < 7) { // There is an existing update file, and the last update was less than 1 week ago. // It's unlikely a new version is released within 1 week, so we can skip this check. @@ -232,7 +232,7 @@ internal static async Task CheckForUpdates() SemanticVersion baselineVersion = lastUpdateVersion ?? PSVersionInfo.PSCurrentVersion; Release release = await QueryNewReleaseAsync(baselineVersion); - if (release != null) + if (release is not null) { // The date part of the string is 'YYYY-MM-DD'. const int dateLength = 10; diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs index 2ffa18d2132..6150f533e6d 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs @@ -292,7 +292,7 @@ to fill the passed in ETW data descriptor. dataDescriptor->Reserved = 0; string sRet = data as string; - if (sRet != null) + if (sRet is not null) { dataDescriptor->Size = (uint)((sRet.Length + 1) * 2); return sRet; @@ -615,7 +615,7 @@ public bool WriteTransferEvent(ref EventDescriptor eventDescriptor, Guid related int argCount = 0; EventData* userDataPtr = null; - if ((eventPayload != null) && (eventPayload.Length != 0)) + if ((eventPayload is not null) && (eventPayload.Length != 0)) { argCount = eventPayload.Length; if (argCount > s_etwMaxNumberArguments) @@ -650,7 +650,7 @@ public bool WriteTransferEvent(ref EventDescriptor eventDescriptor, Guid related currentBuffer += s_basicTypeAllocationBufferSize; totalEventSize += userDataPtr->Size; userDataPtr++; - if (isString != null) + if (isString is not null) { if (stringIndex < s_etwAPIMaxStringCount) { @@ -676,42 +676,42 @@ public bool WriteTransferEvent(ref EventDescriptor eventDescriptor, Guid related v4 = dataString[4], v5 = dataString[5], v6 = dataString[6], v7 = dataString[7]) { userDataPtr = (EventData*)userData; - if (dataString[0] != null) + if (dataString[0] is not null) { userDataPtr[stringPosition[0]].DataPointer = (ulong)v0; } - if (dataString[1] != null) + if (dataString[1] is not null) { userDataPtr[stringPosition[1]].DataPointer = (ulong)v1; } - if (dataString[2] != null) + if (dataString[2] is not null) { userDataPtr[stringPosition[2]].DataPointer = (ulong)v2; } - if (dataString[3] != null) + if (dataString[3] is not null) { userDataPtr[stringPosition[3]].DataPointer = (ulong)v3; } - if (dataString[4] != null) + if (dataString[4] is not null) { userDataPtr[stringPosition[4]].DataPointer = (ulong)v4; } - if (dataString[5] != null) + if (dataString[5] is not null) { userDataPtr[stringPosition[5]].DataPointer = (ulong)v5; } - if (dataString[6] != null) + if (dataString[6] is not null) { userDataPtr[stringPosition[6]].DataPointer = (ulong)v6; } - if (dataString[7] != null) + if (dataString[7] is not null) { userDataPtr[stringPosition[7]].DataPointer = (ulong)v7; } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs index 8af9fa53e9d..c53b7978cbc 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs @@ -143,14 +143,14 @@ public sealed override void TraceData(TraceEventCache eventCache, string source, return; } - if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, null)) + if (Filter is not null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, null)) { return; } StringBuilder dataString = new StringBuilder(s_defaultPayloadSize); - if (data != null) + if (data is not null) { dataString.Append(data.ToString()); } @@ -171,7 +171,7 @@ public sealed override void TraceData(TraceEventCache eventCache, string source, return; } - if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, null)) + if (Filter is not null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, null)) { return; } @@ -179,11 +179,11 @@ public sealed override void TraceData(TraceEventCache eventCache, string source, int index; StringBuilder dataString = new StringBuilder(s_defaultPayloadSize); - if ((data != null) && (data.Length > 0)) + if ((data is not null) && (data.Length > 0)) { for (index = 0; index < (data.Length - 1); index++) { - if (data[index] != null) + if (data[index] is not null) { dataString.Append(data[index].ToString()); dataString.Append(Delimiter); @@ -194,7 +194,7 @@ public sealed override void TraceData(TraceEventCache eventCache, string source, } } - if (data[index] != null) + if (data[index] is not null) { dataString.Append(data[index].ToString()); } @@ -220,7 +220,7 @@ public sealed override void TraceEvent(TraceEventCache eventCache, string source return; } - if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, null)) + if (Filter is not null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, null)) { return; } @@ -237,7 +237,7 @@ public sealed override void TraceEvent(TraceEventCache eventCache, string source return; } - if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, null)) + if (Filter is not null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, null)) { return; } @@ -257,7 +257,7 @@ public sealed override void TraceEvent(TraceEventCache eventCache, string source return; } - if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, null)) + if (Filter is not null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, null)) { return; } @@ -279,7 +279,7 @@ public sealed override void TraceEvent(TraceEventCache eventCache, string source public override void Fail(string message, string detailMessage) { StringBuilder failMessage = new StringBuilder(message); - if (detailMessage != null) + if (detailMessage is not null) { failMessage.Append(" "); failMessage.Append(detailMessage); diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs index 8858b067f8a..707399a026e 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs @@ -678,7 +678,7 @@ public static void EvtSetChannelConfigProperty(EventLogHandle handle, UnsafeNati using (taskMem) { - if (val != null) + if (val is not null) { switch (enumType) { diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/AddLocalGroupMemberCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/AddLocalGroupMemberCommand.cs index 375a8101075..da4c06348e4 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/AddLocalGroupMemberCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/AddLocalGroupMemberCommand.cs @@ -120,11 +120,11 @@ protected override void ProcessRecord() { try { - if (Group != null) + if (Group is not null) ProcessGroup(Group); - else if (Name != null) + else if (Name is not null) ProcessName(Name); - else if (SID != null) + else if (SID is not null) ProcessSid(SID); } catch (GroupNotFoundException ex) @@ -138,7 +138,7 @@ protected override void ProcessRecord() /// protected override void EndProcessing() { - if (sam != null) + if (sam is not null) { sam.Dispose(); sam = null; @@ -185,7 +185,7 @@ private LocalPrincipal MakePrincipal(string groupId, LocalPrincipal member) { LocalPrincipal principal = null; // if the member has a SID, we can use it directly - if (member.SID != null) + if (member.SID is not null) { principal = member; } @@ -193,7 +193,7 @@ private LocalPrincipal MakePrincipal(string groupId, LocalPrincipal member) { SecurityIdentifier sid = this.TrySid(member.Name); - if (sid != null) + if (sid is not null) { member.SID = sid; principal = member; @@ -252,10 +252,10 @@ private void ProcessGroup(LocalGroup group) foreach (var member in this.Member) { LocalPrincipal principal = MakePrincipal(groupId, member); - if (principal != null) + if (principal is not null) { var ex = sam.AddLocalGroupMember(group, principal); - if (ex != null) + if (ex is not null) { WriteError(ex.MakeErrorRecord()); } @@ -286,10 +286,10 @@ private void ProcessSid(SecurityIdentifier groupSid) foreach (var member in this.Member) { LocalPrincipal principal = MakePrincipal(groupSid.ToString(), member); - if (principal != null) + if (principal is not null) { var ex = sam.AddLocalGroupMember(groupSid, principal); - if (ex != null) + if (ex is not null) { WriteError(ex.MakeErrorRecord()); } diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/DisableLocalUserCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/DisableLocalUserCommand.cs index 09e7bdf9452..4ee747ae40f 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/DisableLocalUserCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/DisableLocalUserCommand.cs @@ -130,7 +130,7 @@ protected override void ProcessRecord() /// protected override void EndProcessing() { - if (sam != null) + if (sam is not null) { sam.Dispose(); sam = null; @@ -148,7 +148,7 @@ protected override void EndProcessing() /// private void ProcessNames() { - if (Name != null) + if (Name is not null) { foreach (var name in Name) { @@ -170,7 +170,7 @@ private void ProcessNames() /// private void ProcessSids() { - if (SID != null) + if (SID is not null) { foreach (var sid in SID) { @@ -192,7 +192,7 @@ private void ProcessSids() /// private void ProcessUsers() { - if (InputObject != null) + if (InputObject is not null) { foreach (var user in InputObject) { diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/EnableLocalUserCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/EnableLocalUserCommand.cs index e321a03e266..8aadfecf5f6 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/EnableLocalUserCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/EnableLocalUserCommand.cs @@ -130,7 +130,7 @@ protected override void ProcessRecord() /// protected override void EndProcessing() { - if (sam != null) + if (sam is not null) { sam.Dispose(); sam = null; @@ -148,7 +148,7 @@ protected override void EndProcessing() /// private void ProcessNames() { - if (Name != null) + if (Name is not null) { foreach (var name in Name) { @@ -170,7 +170,7 @@ private void ProcessNames() /// private void ProcessSids() { - if (SID != null) + if (SID is not null) { foreach (var sid in SID) { @@ -192,7 +192,7 @@ private void ProcessSids() /// private void ProcessUsers() { - if (InputObject != null) + if (InputObject is not null) { foreach (var user in InputObject) { diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupCommand.cs index 3965c362335..e00561ec19a 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupCommand.cs @@ -98,7 +98,7 @@ protected override void ProcessRecord() /// protected override void EndProcessing() { - if (sam != null) + if (sam is not null) { sam.Dispose(); sam = null; @@ -117,7 +117,7 @@ protected override void EndProcessing() /// private void ProcessNames() { - if (Name != null) + if (Name is not null) { foreach (var name in Name) { @@ -149,7 +149,7 @@ private void ProcessNames() /// private void ProcessSids() { - if (SID != null) + if (SID is not null) { foreach (var sid in SID) { diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupMemberCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupMemberCommand.cs index a10300e9065..e40a0b84d00 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupMemberCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupMemberCommand.cs @@ -120,14 +120,14 @@ protected override void ProcessRecord() { IEnumerable principals = null; - if (Group != null) + if (Group is not null) principals = ProcessGroup(Group); - else if (Name != null) + else if (Name is not null) principals = ProcessName(Name); - else if (SID != null) + else if (SID is not null) principals = ProcessSid(SID); - if (principals != null) + if (principals is not null) WriteObject(principals, true); } catch (Exception ex) @@ -141,7 +141,7 @@ protected override void ProcessRecord() /// protected override void EndProcessing() { - if (sam != null) + if (sam is not null) { sam.Dispose(); sam = null; @@ -178,7 +178,7 @@ private IEnumerable ProcessesMembership(IEnumerable protected override void EndProcessing() { - if (sam != null) + if (sam is not null) { sam.Dispose(); sam = null; @@ -119,7 +119,7 @@ protected override void EndProcessing() /// private void ProcessNames() { - if (Name != null) + if (Name is not null) { foreach (var nm in Name) { @@ -151,7 +151,7 @@ private void ProcessNames() /// private void ProcessSids() { - if (SID != null) + if (SID is not null) { foreach (var s in SID) { diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalGroupCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalGroupCommand.cs index 59e4f4ca13f..ca756caa749 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalGroupCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalGroupCommand.cs @@ -101,7 +101,7 @@ protected override void ProcessRecord() /// protected override void EndProcessing() { - if (sam != null) + if (sam is not null) { sam.Dispose(); sam = null; diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalUserCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalUserCommand.cs index b3916f46071..06809abe10c 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalUserCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalUserCommand.cs @@ -275,7 +275,7 @@ protected override void ProcessRecord() /// protected override void EndProcessing() { - if (sam != null) + if (sam is not null) { sam.Dispose(); sam = null; diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupCommand.cs index 0c0af710af1..fee91a46ab0 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupCommand.cs @@ -123,7 +123,7 @@ protected override void ProcessRecord() /// protected override void EndProcessing() { - if (sam != null) + if (sam is not null) { sam.Dispose(); sam = null; @@ -141,7 +141,7 @@ protected override void EndProcessing() /// private void ProcessNames() { - if (Name != null) + if (Name is not null) { foreach (var name in Name) { @@ -163,7 +163,7 @@ private void ProcessNames() /// private void ProcessSids() { - if (SID != null) + if (SID is not null) { foreach (var sid in SID) { @@ -185,7 +185,7 @@ private void ProcessSids() /// private void ProcessGroups() { - if (InputObject != null) + if (InputObject is not null) { foreach (var group in InputObject) { diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupMemberCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupMemberCommand.cs index 7e132405b2a..6dad0fd2c27 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupMemberCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupMemberCommand.cs @@ -120,11 +120,11 @@ protected override void ProcessRecord() { try { - if (Group != null) + if (Group is not null) ProcessGroup(Group); - else if (Name != null) + else if (Name is not null) ProcessName(Name); - else if (SID != null) + else if (SID is not null) ProcessSid(SID); } catch (GroupNotFoundException ex) @@ -138,7 +138,7 @@ protected override void ProcessRecord() /// protected override void EndProcessing() { - if (sam != null) + if (sam is not null) { sam.Dispose(); sam = null; @@ -184,7 +184,7 @@ private LocalPrincipal MakePrincipal(string groupId, LocalPrincipal member) LocalPrincipal principal = null; // if the member has a SID, we can use it directly - if (member.SID != null) + if (member.SID is not null) { principal = member; } @@ -192,7 +192,7 @@ private LocalPrincipal MakePrincipal(string groupId, LocalPrincipal member) { SecurityIdentifier sid = this.TrySid(member.Name); - if (sid != null) + if (sid is not null) { member.SID = sid; principal = member; @@ -251,10 +251,10 @@ private void ProcessGroup(LocalGroup group) foreach (var member in this.Member) { LocalPrincipal principal = MakePrincipal(groupId, member); - if (principal != null) + if (principal is not null) { var ex = sam.RemoveLocalGroupMember(group, principal); - if (ex != null) + if (ex is not null) { WriteError(ex.MakeErrorRecord()); } @@ -285,10 +285,10 @@ private void ProcessSid(SecurityIdentifier groupSid) foreach (var member in this.Member) { LocalPrincipal principal = MakePrincipal(groupSid.ToString(), member); - if (principal != null) + if (principal is not null) { var ex = sam.RemoveLocalGroupMember(groupSid, principal); - if (ex != null) + if (ex is not null) { WriteError(ex.MakeErrorRecord()); } diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalUserCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalUserCommand.cs index 0c61da2e117..92906c12ff2 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalUserCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalUserCommand.cs @@ -124,7 +124,7 @@ protected override void ProcessRecord() /// protected override void EndProcessing() { - if (sam != null) + if (sam is not null) { sam.Dispose(); sam = null; @@ -142,7 +142,7 @@ protected override void EndProcessing() /// private void ProcessNames() { - if (Name != null) + if (Name is not null) { foreach (var name in Name) { @@ -164,7 +164,7 @@ private void ProcessNames() /// private void ProcessSids() { - if (SID != null) + if (SID is not null) { foreach (var sid in SID) { @@ -186,7 +186,7 @@ private void ProcessSids() /// private void ProcessUsers() { - if (InputObject != null) + if (InputObject is not null) { foreach (var user in InputObject) { diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalGroupCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalGroupCommand.cs index f32e3365086..2fed6e4caa7 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalGroupCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalGroupCommand.cs @@ -136,7 +136,7 @@ protected override void ProcessRecord() /// protected override void EndProcessing() { - if (sam != null) + if (sam is not null) { sam.Dispose(); sam = null; @@ -154,7 +154,7 @@ protected override void EndProcessing() /// private void ProcessName() { - if (Name != null) + if (Name is not null) { try { @@ -173,7 +173,7 @@ private void ProcessName() /// private void ProcessSid() { - if (SID != null) + if (SID is not null) { try { @@ -192,7 +192,7 @@ private void ProcessSid() /// private void ProcessGroup() { - if (InputObject != null) + if (InputObject is not null) { try { diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalUserCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalUserCommand.cs index e6b1297a7d5..49a4267a839 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalUserCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalUserCommand.cs @@ -136,7 +136,7 @@ protected override void ProcessRecord() /// protected override void EndProcessing() { - if (sam != null) + if (sam is not null) { sam.Dispose(); sam = null; @@ -154,7 +154,7 @@ protected override void EndProcessing() /// private void ProcessName() { - if (Name != null) + if (Name is not null) { try { @@ -173,7 +173,7 @@ private void ProcessName() /// private void ProcessSid() { - if (SID != null) + if (SID is not null) { try { @@ -192,7 +192,7 @@ private void ProcessSid() /// private void ProcessUser() { - if (InputObject != null) + if (InputObject is not null) { try { diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalGroupCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalGroupCommand.cs index b1943971e3d..24ef80419e8 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalGroupCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalGroupCommand.cs @@ -121,19 +121,19 @@ protected override void ProcessRecord() { LocalGroup group = null; - if (InputObject != null) + if (InputObject is not null) { if (CheckShouldProcess(InputObject.ToString())) group = InputObject; } - else if (Name != null) + else if (Name is not null) { group = sam.GetLocalGroup(Name); if (!CheckShouldProcess(Name)) group = null; } - else if (SID != null) + else if (SID is not null) { group = sam.GetLocalGroup(SID); @@ -141,7 +141,7 @@ protected override void ProcessRecord() group = null; } - if (group != null) + if (group is not null) { var delta = group.Clone(); @@ -160,7 +160,7 @@ protected override void ProcessRecord() /// protected override void EndProcessing() { - if (sam != null) + if (sam is not null) { sam.Dispose(); sam = null; diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalUserCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalUserCommand.cs index 8fafa52c9e4..dbd2cbbd175 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalUserCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalUserCommand.cs @@ -231,19 +231,19 @@ protected override void ProcessRecord() { LocalUser user = null; - if (InputObject != null) + if (InputObject is not null) { if (CheckShouldProcess(InputObject.ToString())) user = InputObject; } - else if (Name != null) + else if (Name is not null) { user = sam.GetLocalUser(Name); if (!CheckShouldProcess(Name)) user = null; } - else if (SID != null) + else if (SID is not null) { user = sam.GetLocalUser(SID); @@ -303,7 +303,7 @@ protected override void ProcessRecord() /// protected override void EndProcessing() { - if (sam != null) + if (sam is not null) { sam.Dispose(); sam = null; diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Extensions.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Extensions.cs index 007966cb0a8..7756adb56b7 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Extensions.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Extensions.cs @@ -73,11 +73,11 @@ internal static class PSExtensions internal static bool HasParameter(this PSCmdlet cmdlet, string parameterName) { var invocation = cmdlet.MyInvocation; - if (invocation != null) + if (invocation is not null) { var parameters = invocation.BoundParameters; - if (parameters != null) + if (parameters is not null) { // PowerShell sets the parameter names in the BoundParameters dictionary // to their "proper" casing, so we don't have to do a case-insensitive search. @@ -189,7 +189,7 @@ internal static ErrorRecord MakeErrorRecord(this Exception ex, object target = n // having to have multiple exception handlers in every cmdlet command. var exTemp = ex as LocalAccountsException; - if (exTemp != null) + if (exTemp is not null) return MakeErrorRecord(exTemp, target ?? exTemp.Target); return new ErrorRecord(ex, diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Sam.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Sam.cs index e87147fd35d..306d221c95a 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Sam.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Sam.cs @@ -2136,7 +2136,7 @@ private void UpdateUser(LocalUser user, if ( properties != UserProperties.None || passwordExpired != PasswordExpiredState.Unchanged - || password != null) + || password is not null) { IntPtr userHandle = IntPtr.Zero; UInt32 status = 0; @@ -2268,7 +2268,7 @@ private void SetUserData(IntPtr userHandle, if (setFlags.HasFlag(UserProperties.UserMayChangePassword)) SetUserMayChangePassword(userHandle, sourceUser.SID, sourceUser.UserMayChangePassword); - if (password != null) + if (password is not null) SetUserPassword(userHandle, password, passwordExpired); } finally @@ -2399,7 +2399,7 @@ private void SetSamDacl(IntPtr objectHandle, RawAcl rawAcl) var sd = new SECURITY_DESCRIPTOR() { Revision = 1 }; ipsd = Marshal.AllocHGlobal(Marshal.SizeOf()); - if (rawAcl != null && rawAcl.BinaryLength > 0) + if (rawAcl is not null && rawAcl.BinaryLength > 0) { Marshal.StructureToPtr(sd, ipsd, false); @@ -2466,7 +2466,7 @@ private bool GetUserMayChangePassword(IntPtr userHandle, SecurityIdentifier user foreach (var a in rawAcl) { var ace = a as CommonAce; - if (ace != null && ace.AceType == AceType.AccessAllowed) + if (ace is not null && ace.AceType == AceType.AccessAllowed) { if (ace.SecurityIdentifier == worldSid || ace.SecurityIdentifier == userSid) @@ -2506,12 +2506,12 @@ private void SetUserMayChangePassword(IntPtr userHandle, SecurityIdentifier user var changed = false; var rawAcl = GetSamDacl(userHandle); - if (rawAcl != null) + if (rawAcl is not null) { foreach (var a in rawAcl) { var ace = a as CommonAce; - if (ace != null && ace.AceType == AceType.AccessAllowed) + if (ace is not null && ace.AceType == AceType.AccessAllowed) { if (ace.SecurityIdentifier == worldSid || ace.SecurityIdentifier == userSid) @@ -2581,7 +2581,7 @@ private void SetUserPassword(IntPtr userHandle, System.Security.SecureString password, PasswordExpiredState passwordExpired) { - if (password != null) + if (password is not null) { USER_SET_PASSWORD_INFORMATION info = new USER_SET_PASSWORD_INFORMATION(); IntPtr buffer = IntPtr.Zero; @@ -2878,7 +2878,7 @@ private void ThrowOnFailure(UInt32 ntStatus, Context context = null) { var ex = MakeException(ntStatus, context); - if (ex != null) + if (ex is not null) throw ex; } } @@ -3167,7 +3167,7 @@ public string VersionString { get { - if (_versionString != null) + if (_versionString is not null) { return _versionString; } diff --git a/src/Microsoft.PowerShell.MarkdownRender/FencedCodeBlockRenderer.cs b/src/Microsoft.PowerShell.MarkdownRender/FencedCodeBlockRenderer.cs index 121c7ee01fa..22543e75c20 100644 --- a/src/Microsoft.PowerShell.MarkdownRender/FencedCodeBlockRenderer.cs +++ b/src/Microsoft.PowerShell.MarkdownRender/FencedCodeBlockRenderer.cs @@ -18,7 +18,7 @@ internal class FencedCodeBlockRenderer : VT100ObjectRenderer { protected override void Write(VT100Renderer renderer, FencedCodeBlock obj) { - if (obj?.Lines.Lines != null) + if (obj?.Lines.Lines is not null) { foreach (StringLine codeLine in obj.Lines.Lines) { diff --git a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJob.cs b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJob.cs index 48c9fd056d7..250e6d530ca 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJob.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJob.cs @@ -84,7 +84,7 @@ public override bool HasMoreData { get { - return (_job != null) ? + return (_job is not null) ? _job.HasMoreData : (Output.Count > 0 || @@ -167,7 +167,7 @@ public override void StartJob() { lock (SyncRoot) { - if (_job != null && !IsFinishedState(_job.JobStateInfo.State)) + if (_job is not null && !IsFinishedState(_job.JobStateInfo.State)) { string msg = StringUtil.Format(ScheduledJobErrorStrings.JobAlreadyRunning, _jobDefinition.Name); throw new PSInvalidOperationException(msg); @@ -429,7 +429,7 @@ private void SerializeStatusInfo(SerializationInfo info) Location, Command, StatusMessage, - (_job != null) ? _job.JobStateInfo.State : JobStateInfo.State, + (_job is not null) ? _job.JobStateInfo.State : JobStateInfo.State, HasMoreData, PSBeginTime, PSEndTime, @@ -449,11 +449,11 @@ private void SerializeResultsInfo(SerializationInfo info) Collection debug = new Collection(); Collection information = new Collection(); - if (_job != null) + if (_job is not null) { // Collect data from "live" job. - if (JobStateInfo.Reason != null) + if (JobStateInfo.Reason is not null) { error.Add(new ErrorRecord(JobStateInfo.Reason, "ScheduledJobFailedState", ErrorCategory.InvalidResult, null)); } @@ -465,7 +465,7 @@ private void SerializeResultsInfo(SerializationInfo info) foreach (Job childJob in ChildJobs) { - if (childJob.JobStateInfo.Reason != null) + if (childJob.JobStateInfo.Reason is not null) { error.Add(new ErrorRecord(childJob.JobStateInfo.Reason, "ScheduledJobFailedState", ErrorCategory.InvalidResult, null)); } @@ -609,7 +609,7 @@ private void DeserializeResultsInfo(SerializationInfo info) internal void Update(ScheduledJob fromJob) { // We do not update "live" jobs. - if (_job != null || fromJob == null) + if (_job is not null || fromJob == null) { return; } @@ -711,7 +711,7 @@ private Job StartJobCommand(System.Management.Automation.PowerShell powerShell) // Start the job. Collection rtn = powerShell.Invoke(); - if (rtn != null && rtn.Count == 1) + if (rtn is not null && rtn.Count == 1) { job = rtn[0].BaseObject as Job; } @@ -732,7 +732,7 @@ private void HandleJobStateChanged(object sender, JobStateEventArgs e) Runspace disposeRunspace = null; lock (SyncRoot) { - if (_job != null && + if (_job is not null && IsFinishedState(_job.JobStateInfo.State)) { disposePowerShell = _powerShell; @@ -742,12 +742,12 @@ private void HandleJobStateChanged(object sender, JobStateEventArgs e) } } - if (disposePowerShell != null) + if (disposePowerShell is not null) { disposePowerShell.Dispose(); } - if (disposeRunspace != null) + if (disposeRunspace is not null) { disposeRunspace.Dispose(); } @@ -776,12 +776,12 @@ private StatusInfo Status StatusInfo statusInfo; lock (SyncRoot) { - if (_statusInfo != null) + if (_statusInfo is not null) { // Pass back static status. statusInfo = _statusInfo; } - else if (_job != null) + else if (_job is not null) { // Create current job status. statusInfo = new StatusInfo( @@ -822,7 +822,7 @@ private StatusInfo Status private void CopyOutput(ICollection fromOutput) { PSDataCollection output = CopyResults(fromOutput); - if (output != null) + if (output is not null) { try { @@ -835,7 +835,7 @@ private void CopyOutput(ICollection fromOutput) private void CopyError(ICollection fromError) { PSDataCollection error = CopyResults(fromError); - if (error != null) + if (error is not null) { try { @@ -848,7 +848,7 @@ private void CopyError(ICollection fromError) private void CopyWarning(ICollection fromWarning) { PSDataCollection warning = CopyResults(fromWarning); - if (warning != null) + if (warning is not null) { try { @@ -861,7 +861,7 @@ private void CopyWarning(ICollection fromWarning) private void CopyVerbose(ICollection fromVerbose) { PSDataCollection verbose = CopyResults(fromVerbose); - if (verbose != null) + if (verbose is not null) { try { @@ -874,7 +874,7 @@ private void CopyVerbose(ICollection fromVerbose) private void CopyProgress(ICollection fromProgress) { PSDataCollection progress = CopyResults(fromProgress); - if (progress != null) + if (progress is not null) { try { @@ -887,7 +887,7 @@ private void CopyProgress(ICollection fromProgress) private void CopyDebug(ICollection fromDebug) { PSDataCollection debug = CopyResults(fromDebug); - if (debug != null) + if (debug is not null) { try { @@ -900,7 +900,7 @@ private void CopyDebug(ICollection fromDebug) private void CopyInformation(ICollection fromInformation) { PSDataCollection information = CopyResults(fromInformation); - if (information != null) + if (information is not null) { try { @@ -912,7 +912,7 @@ private void CopyInformation(ICollection fromInformation) private PSDataCollection CopyResults(ICollection fromResults) { - if (fromResults != null && fromResults.Count > 0) + if (fromResults is not null && fromResults.Count > 0) { PSDataCollection returnResults = new PSDataCollection(); foreach (var item in fromResults) @@ -931,7 +931,7 @@ private void AddSetShouldExitToHost() if (!_allowSetShouldExit || _host == null) { return; } PSObject hostPrivateData = _host.PrivateData as PSObject; - if (hostPrivateData != null) + if (hostPrivateData is not null) { // Adds or replaces. hostPrivateData.Properties.Add(new PSNoteProperty(AllowHostSetShouldExit, true)); @@ -943,7 +943,7 @@ private void RemoveSetShouldExitFromHost() if (!_allowSetShouldExit || _host == null) { return; } PSObject hostPrivateData = _host.PrivateData as PSObject; - if (hostPrivateData != null) + if (hostPrivateData is not null) { // Removes if exists. hostPrivateData.Properties.Remove(AllowHostSetShouldExit); @@ -1267,7 +1267,7 @@ public void GetObjectData( info.AddValue("Status_MoreData", _hasMoreData); info.AddValue("Status_Definition", _definition); - if (_startTime != null) + if (_startTime is not null) { info.AddValue("Status_StartTime", _startTime); } @@ -1276,7 +1276,7 @@ public void GetObjectData( info.AddValue("Status_StartTime", DateTime.MinValue); } - if (_stopTime != null) + if (_stopTime is not null) { info.AddValue("Status_StopTime", _stopTime); } diff --git a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobDefinition.cs b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobDefinition.cs index 650c643ecf9..15a9658b69f 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobDefinition.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobDefinition.cs @@ -219,7 +219,7 @@ public ScheduledJobDefinition( _invocationInfo = invocationInfo; SetTriggers(triggers, false); - _options = (options != null) ? new ScheduledJobOptions(options) : + _options = (options is not null) ? new ScheduledJobOptions(options) : new ScheduledJobOptions(); _options.JobDefinition = this; @@ -456,14 +456,14 @@ private void AddToJobStore() } finally { - if (fs != null) + if (fs is not null) { fs.Close(); } } // If credentials are provided then update permissions. - if (Credential != null) + if (Credential is not null) { UpdateFilePermissions(Credential.UserName); } @@ -491,14 +491,14 @@ private void UpdateJobStore() } finally { - if (fs != null) + if (fs is not null) { fs.Close(); } } // If credentials are provided then update permissions. - if (Credential != null) + if (Credential is not null) { UpdateFilePermissions(Credential.UserName); } @@ -536,7 +536,7 @@ private void UpdateFilePermissions(string user) ex = e; } - if (ex != null) + if (ex is not null) { string msg = StringUtil.Format(ScheduledJobErrorStrings.ErrorSettingAccessPermissions, this.Name, Credential.UserName); throw new ScheduledJobException(msg, ex); @@ -578,7 +578,7 @@ private void LoadRepository() /// private void ValidateTriggers(IEnumerable triggers) { - if (triggers != null) + if (triggers is not null) { foreach (var trigger in triggers) { @@ -646,7 +646,7 @@ private void UpdateJobRunNames( continue; } - if (job != null) + if (job is not null) { job.Name = newDefName; job.Definition = definition; @@ -712,7 +712,7 @@ internal void SyncWithWTS() notFoundEx = e; } - if (notFoundEx != null) + if (notFoundEx is not null) { // There is no corresponding Task Scheduler item for this // scheduled job definition. Remove this definition from @@ -764,7 +764,7 @@ internal void RenameAndSave(string newName) ex = e; } - if (ex != null) + if (ex is not null) { string msg; if (!string.IsNullOrEmpty(ex.Message)) @@ -829,7 +829,7 @@ internal void RenameAndSave(string newName) // If any part of renaming the various scheduled job components fail, // aggressively remove scheduled job corrupted state and inform user. - if (ex != null) + if (ex is not null) { try { @@ -919,7 +919,7 @@ public void Register() ex = e; } - if (ex != null) + if (ex is not null) { if (corruptedFile) { @@ -982,7 +982,7 @@ public void Register() ex = e; } - if (ex != null) + if (ex is not null) { // Clean up job store. RemoveFromJobStore(); @@ -1042,7 +1042,7 @@ public void Save() ex = e; } - if (ex != null) + if (ex is not null) { // We want this object to remain synchronized with what is in WTS. SyncWithWTS(); @@ -1078,7 +1078,7 @@ public void Save() ex = e; } - if (ex != null) + if (ex is not null) { // Remove this from WTS for consistency. RemoveFromWTS(true); @@ -1157,7 +1157,7 @@ public void Remove(bool force) Dispose(); } - if (ex != null) + if (ex is not null) { string msg = StringUtil.Format(ScheduledJobErrorStrings.ErrorRemovingDefinitionStore, this.Name); throw new ScheduledJobException(msg, ex); @@ -1213,10 +1213,10 @@ public void RunAsTask() ex = e; } - if (ex != null) + if (ex is not null) { string msg; - if (reason != null) + if (reason is not null) { msg = StringUtil.Format(ScheduledJobErrorStrings.ErrorRunningAsTaskWithReason, this.Name, reason); } @@ -1401,7 +1401,7 @@ public void SetTriggers( _currentTriggerId = 0; _triggers = new Dictionary(); - if (newTriggers != null) + if (newTriggers is not null) { foreach (ScheduledJobTrigger trigger in newTriggers) { @@ -1511,7 +1511,7 @@ public void UpdateOptions( // options == null is allowed and signals the use default // Task Scheduler options. - _options = (options != null) ? new ScheduledJobOptions(options) : + _options = (options is not null) ? new ScheduledJobOptions(options) : new ScheduledJobOptions(); _options.JobDefinition = this; @@ -1606,7 +1606,7 @@ public void SetName( { IsDisposed(); - _name = (name != null) ? name : string.Empty; + _name = (name is not null) ? name : string.Empty; if (save) { @@ -1667,7 +1667,7 @@ internal static Dictionary RefreshRepositoryFromStore( { jobDefinitionNamesHash.Remove(jobDef.Name); - if (itemFound != null) + if (itemFound is not null) { itemFound(jobDef); } @@ -1683,7 +1683,7 @@ internal static Dictionary RefreshRepositoryFromStore( ScheduledJobDefinition jobDefinition = ScheduledJobDefinition.LoadDefFromStore(jobDefinitionName, null); Repository.AddOrReplace(jobDefinition); - if (itemFound != null) + if (itemFound is not null) { itemFound(jobDefinition); } @@ -1744,7 +1744,7 @@ internal static ScheduledJobDefinition LoadDefFromStore( } finally { - if (fs != null) + if (fs is not null) { fs.Close(); } @@ -1814,7 +1814,7 @@ public static ScheduledJobDefinition LoadFromStore( corruptedFile = true; } - if (ex != null) + if (ex is not null) { // // Remove definition if corrupted. @@ -1965,7 +1965,7 @@ public Job2 Run() // so that ScheduledJobSourceAdapter knows where the results are // to be stored. ScheduledJob schedJob = job as ScheduledJob; - if (schedJob != null) + if (schedJob is not null) { schedJob.Definition = this; schedJob.AllowSetShouldExit = true; @@ -2056,14 +2056,14 @@ public Job2 Run() ex = e; } - if (ex != null) + if (ex is not null) { // Log error. _tracer.WriteScheduledJobErrorEvent( this.Name, ex.Message, ex.StackTrace.ToString(), - (ex.InnerException != null) ? ex.InnerException.Message : string.Empty); + (ex.InnerException is not null) ? ex.InnerException.Message : string.Empty); throw ex; } @@ -2527,7 +2527,7 @@ private void DeserializeInvocationInfo(SerializationInfo info) // ScriptBlock string script = info.GetString("InvocationParam_ScriptBlock"); - if (script != null) + if (script is not null) { parameters.Add(ScriptBlockParameter, ScriptBlock.Create(script)); } @@ -2557,7 +2557,7 @@ private void DeserializeInvocationInfo(SerializationInfo info) // ArgumentList object[] argList = (object[])info.GetValue("InvocationParam_ArgList", typeof(object[])); - if (argList != null) + if (argList is not null) { parameters.Add(ArgumentListParameter, argList); } diff --git a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobSourceAdapter.cs b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobSourceAdapter.cs index 53434c729e7..bdb198c6070 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobSourceAdapter.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobSourceAdapter.cs @@ -387,12 +387,12 @@ internal static void SaveJobToStore(ScheduledJob job) } finally { - if (fsStatus != null) + if (fsStatus is not null) { fsStatus.Close(); } - if (fsResults != null) + if (fsResults is not null) { fsResults.Close(); } @@ -538,7 +538,7 @@ internal static Job2 LoadJobFromStore(string definitionName, DateTime jobRun) } finally { - if (fsResults != null) + if (fsResults is not null) { fsResults.Close(); } @@ -550,7 +550,7 @@ internal static Job2 LoadJobFromStore(string definitionName, DateTime jobRun) ScheduledJobStore.RemoveJobRun(definitionName, jobRun); } - if (ex != null) + if (ex is not null) { string msg = StringUtil.Format(ScheduledJobErrorStrings.CantLoadJobRunFromStore, definitionName, jobRun); throw new ScheduledJobException(msg, ex); @@ -742,7 +742,7 @@ private static void UpdateRepositoryObjects(FileSystemEventArgs e) { } // Update job in repository based on new job store data. - if (job != null) + if (job is not null) { updateJob.Update(job as ScheduledJob); } diff --git a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobStore.cs b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobStore.cs index bd9d7439696..2f44963bc0c 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobStore.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobStore.cs @@ -152,7 +152,7 @@ public static IEnumerable GetJobDefinitions() // Directory names are identical to the corresponding scheduled job definition names. string directoryPath = GetDirectoryPath(); IEnumerable definitions = Directory.EnumerateDirectories(directoryPath); - return (definitions != null) ? definitions : new Collection() as IEnumerable; + return (definitions is not null) ? definitions : new Collection() as IEnumerable; } /// @@ -242,7 +242,7 @@ public static Collection GetJobRunsForDefinitionPath( Collection jobRunInfos = new Collection(); IEnumerable jobRuns = Directory.EnumerateDirectories(definitionOutputPath); - if (jobRuns != null) + if (jobRuns is not null) { // Job run directory names are the date/times that the job was started. foreach (string jobRun in jobRuns) diff --git a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobTrigger.cs b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobTrigger.cs index a507e3161af..7baa1592699 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobTrigger.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobTrigger.cs @@ -103,7 +103,7 @@ public TimeSpan? RepetitionInterval set { // A TimeSpan value of zero is equivalent to a null value. - _repInterval = (value != null && value.Value == TimeSpan.Zero) ? + _repInterval = (value is not null && value.Value == TimeSpan.Zero) ? null : value; } } @@ -118,7 +118,7 @@ public TimeSpan? RepetitionDuration set { // A TimeSpan value of zero is equivalent to a null value. - _repDuration = (value != null && value.Value == TimeSpan.Zero) ? + _repDuration = (value is not null && value.Value == TimeSpan.Zero) ? null : value; } } @@ -368,7 +368,7 @@ internal void Validate() throw new ScheduledJobException(msg); } - if (_repInterval != null || _repDuration != null) + if (_repInterval is not null || _repDuration is not null) { ValidateOnceRepetitionParams(_repInterval, _repDuration); } @@ -550,7 +550,7 @@ public static ScheduledJobTrigger CreateWeeklyTrigger( Int32 id, bool enabled) { - List lDaysOfWeek = (daysOfWeek != null) ? new List(daysOfWeek) : null; + List lDaysOfWeek = (daysOfWeek is not null) ? new List(daysOfWeek) : null; return new ScheduledJobTrigger( enabled, @@ -812,7 +812,7 @@ private CimInstance ConvertToOnce(ScheduledJobTrigger trigger, CimSession cimSes cimInstance.CimInstanceProperties["RandomDelay"].Value = ScheduledJobWTS.ConvertTimeSpanToWTSString(trigger.RandomDelay); - if (trigger.RepetitionInterval != null && trigger.RepetitionDuration != null) + if (trigger.RepetitionInterval is not null && trigger.RepetitionDuration is not null) { CimClass cimRepClass = cimSession.GetClass(CIM_TRIGGER_NAMESPACE, "MSFT_TaskRepetitionPattern"); CimInstance cimRepInstance = new CimInstance(cimRepClass); @@ -886,7 +886,7 @@ private static void AddCommonProperties(ScheduledJobTrigger trigger, CimInstance { cimInstance.CimInstanceProperties["Enabled"].Value = trigger.Enabled; - if (trigger.At != null) + if (trigger.At is not null) { cimInstance.CimInstanceProperties["StartBoundary"].Value = ScheduledJobWTS.ConvertDateTimeToString(trigger.At); } diff --git a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobWTS.cs b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobWTS.cs index a8d76ef7da8..217f0e0b646 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobWTS.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobWTS.cs @@ -81,7 +81,7 @@ public Collection GetJobTriggers( Collection jobTriggers = new Collection(); ITriggerCollection iTriggerCollection = iTaskDefinition.Triggers; - if (iTriggerCollection != null) + if (iTriggerCollection is not null) { foreach (ITrigger iTrigger in iTriggerCollection) { @@ -373,7 +373,7 @@ private void AddTaskTrigger( { iTrigger = iTaskDefinition.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_BOOT); IBootTrigger iBootTrigger = iTrigger as IBootTrigger; - Debug.Assert(iBootTrigger != null); + Debug.Assert(iBootTrigger is not null); iBootTrigger.Delay = ConvertTimeSpanToWTSString(jobTrigger.RandomDelay); @@ -387,7 +387,7 @@ private void AddTaskTrigger( { iTrigger = iTaskDefinition.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_LOGON); ILogonTrigger iLogonTrigger = iTrigger as ILogonTrigger; - Debug.Assert(iLogonTrigger != null); + Debug.Assert(iLogonTrigger is not null); iLogonTrigger.UserId = ScheduledJobTrigger.IsAllUsers(jobTrigger.User) ? null : jobTrigger.User; iLogonTrigger.Delay = ConvertTimeSpanToWTSString(jobTrigger.RandomDelay); @@ -402,13 +402,13 @@ private void AddTaskTrigger( { iTrigger = iTaskDefinition.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_TIME); ITimeTrigger iTimeTrigger = iTrigger as ITimeTrigger; - Debug.Assert(iTimeTrigger != null); + Debug.Assert(iTimeTrigger is not null); iTimeTrigger.RandomDelay = ConvertTimeSpanToWTSString(jobTrigger.RandomDelay); // Time trigger repetition. - if (jobTrigger.RepetitionInterval != null && - jobTrigger.RepetitionDuration != null) + if (jobTrigger.RepetitionInterval is not null && + jobTrigger.RepetitionDuration is not null) { iTimeTrigger.Repetition.Interval = ConvertTimeSpanToWTSString(jobTrigger.RepetitionInterval.Value); if (jobTrigger.RepetitionDuration.Value == TimeSpan.MaxValue) @@ -433,7 +433,7 @@ private void AddTaskTrigger( { iTrigger = iTaskDefinition.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_DAILY); IDailyTrigger iDailyTrigger = iTrigger as IDailyTrigger; - Debug.Assert(iDailyTrigger != null); + Debug.Assert(iDailyTrigger is not null); iDailyTrigger.RandomDelay = ConvertTimeSpanToWTSString(jobTrigger.RandomDelay); iDailyTrigger.DaysInterval = (short)jobTrigger.Interval; @@ -449,7 +449,7 @@ private void AddTaskTrigger( { iTrigger = iTaskDefinition.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_WEEKLY); IWeeklyTrigger iWeeklyTrigger = iTrigger as IWeeklyTrigger; - Debug.Assert(iWeeklyTrigger != null); + Debug.Assert(iWeeklyTrigger is not null); iWeeklyTrigger.RandomDelay = ConvertTimeSpanToWTSString(jobTrigger.RandomDelay); iWeeklyTrigger.WeeksInterval = (short)jobTrigger.Interval; @@ -577,7 +577,7 @@ private void AddTaskAction( ScheduledJobDefinition definition) { IExecAction iExecAction = iTaskDefinition.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC) as IExecAction; - Debug.Assert(iExecAction != null); + Debug.Assert(iExecAction is not null); iExecAction.Id = ScheduledJobTaskActionId; iExecAction.Path = definition.PSExecutionPath; diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/DisableJobDefinitionBase.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/DisableJobDefinitionBase.cs index d06020ed3d6..a95760c503f 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/DisableJobDefinitionBase.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/DisableJobDefinitionBase.cs @@ -116,7 +116,7 @@ protected override void ProcessRecord() string verbName = Enabled ? VerbsLifecycle.Enable : VerbsLifecycle.Disable; - if (definition != null && + if (definition is not null && ShouldProcess(definition.Name, verbName)) { try diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/EnableDisableCmdletBase.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/EnableDisableCmdletBase.cs index c00626e6d64..14026eb93c2 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/EnableDisableCmdletBase.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/EnableDisableCmdletBase.cs @@ -67,7 +67,7 @@ protected override void ProcessRecord() foreach (ScheduledJobTrigger trigger in _triggers) { trigger.Enabled = Enabled; - if (trigger.JobDefinition != null) + if (trigger.JobDefinition is not null) { trigger.UpdateJobDefinition(); } diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/GetScheduledJobOption.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/GetScheduledJobOption.cs index 4de3131b223..0460c1ae14f 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/GetScheduledJobOption.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/GetScheduledJobOption.cs @@ -92,7 +92,7 @@ protected override void ProcessRecord() } // Return options from the definition object. - if (definition != null) + if (definition is not null) { WriteObject(definition.Options); } diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/RegisterJobDefinition.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/RegisterJobDefinition.cs index e473f91dfd4..2e8acaf886f 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/RegisterJobDefinition.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/RegisterJobDefinition.cs @@ -251,7 +251,7 @@ protected override void ProcessRecord() break; } - if (definition != null) + if (definition is not null) { // Set the MaxCount value if available. if (MyInvocation.BoundParameters.ContainsKey(nameof(MaxResultCount))) @@ -292,21 +292,21 @@ protected override void ProcessRecord() catch (ScheduledJobException e) { // Check for access denied error. - if (e.InnerException != null && e.InnerException is System.UnauthorizedAccessException) + if (e.InnerException is not null && e.InnerException is System.UnauthorizedAccessException) { string msg = StringUtil.Format(ScheduledJobErrorStrings.UnauthorizedAccessError, definition.Name); Exception reason = new RuntimeException(msg, e); ErrorRecord errorRecord = new ErrorRecord(reason, "UnauthorizedAccessToRegisterScheduledJobDefinition", ErrorCategory.PermissionDenied, definition); WriteError(errorRecord); } - else if (e.InnerException != null && e.InnerException is System.IO.DirectoryNotFoundException) + else if (e.InnerException is not null && e.InnerException is System.IO.DirectoryNotFoundException) { string msg = StringUtil.Format(ScheduledJobErrorStrings.DirectoryNotFoundError, definition.Name); Exception reason = new RuntimeException(msg, e); ErrorRecord errorRecord = new ErrorRecord(reason, "DirectoryNotFoundWhenRegisteringScheduledJobDefinition", ErrorCategory.ObjectNotFound, definition); WriteError(errorRecord); } - else if (e.InnerException != null && e.InnerException is System.Runtime.Serialization.InvalidDataContractException) + else if (e.InnerException is not null && e.InnerException is System.Runtime.Serialization.InvalidDataContractException) { string innerMsg = (!string.IsNullOrEmpty(e.InnerException.Message)) ? e.InnerException.Message : string.Empty; string msg = StringUtil.Format(ScheduledJobErrorStrings.CannotSerializeData, definition.Name, innerMsg); @@ -390,12 +390,12 @@ private Dictionary CreateCommonParameters() parameterCollection.Add(ScheduledJobInvocationInfo.RunAs32Parameter, RunAs32.ToBool()); parameterCollection.Add(ScheduledJobInvocationInfo.AuthenticationParameter, Authentication); - if (InitializationScript != null) + if (InitializationScript is not null) { parameterCollection.Add(ScheduledJobInvocationInfo.InitializationScriptParameter, InitializationScript); } - if (ArgumentList != null) + if (ArgumentList is not null) { parameterCollection.Add(ScheduledJobInvocationInfo.ArgumentListParameter, ArgumentList); } diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/SchedJobCmdletBase.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/SchedJobCmdletBase.cs index e8112877019..8c7da9f3773 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/SchedJobCmdletBase.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/SchedJobCmdletBase.cs @@ -455,7 +455,7 @@ private bool ValidateJobDefinition(ScheduledJobDefinition definition) ex = e; } - if (ex != null) + if (ex is not null) { WriteErrorLoadingDefinition(definition.Name, ex); } diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/SetJobDefinition.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/SetJobDefinition.cs index 0d56f5640e4..22c56ee8951 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/SetJobDefinition.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/SetJobDefinition.cs @@ -300,7 +300,7 @@ protected override void ProcessRecord() addedTrigger = true; } - if (Trigger != null || ScheduledJobOption != null || Credential != null || addedTrigger) + if (Trigger is not null || ScheduledJobOption is not null || Credential is not null || addedTrigger) { // Save definition to file and update WTS. _definition.Save(); @@ -320,14 +320,14 @@ protected override void ProcessRecord() { ErrorRecord errorRecord; - if (e.InnerException != null && + if (e.InnerException is not null && e.InnerException is System.UnauthorizedAccessException) { string msg = StringUtil.Format(ScheduledJobErrorStrings.NoAccessOnSetJobDefinition, _definition.Name); errorRecord = new ErrorRecord(new RuntimeException(msg, e), "NoAccessFailureOnSetJobDefinition", ErrorCategory.InvalidOperation, _definition); } - else if (e.InnerException != null && + else if (e.InnerException is not null && e.InnerException is System.IO.IOException) { string msg = StringUtil.Format(ScheduledJobErrorStrings.IOFailureOnSetJobDefinition, _definition.Name); @@ -364,7 +364,7 @@ private void UpdateExecutionDefinition() private void UpdateDefinition() { - if (_name != null && + if (_name is not null && string.Compare(_name, _definition.Name, StringComparison.OrdinalIgnoreCase) != 0) { _definition.RenameAndSave(_name); @@ -377,17 +377,17 @@ private void UpdateDefinition() _definition.SetExecutionHistoryLength(MaxResultCount, false); } - if (Credential != null) + if (Credential is not null) { _definition.Credential = Credential; } - if (Trigger != null) + if (Trigger is not null) { _definition.SetTriggers(Trigger, false); } - if (ScheduledJobOption != null) + if (ScheduledJobOption is not null) { _definition.UpdateOptions(ScheduledJobOption, false); } @@ -403,11 +403,11 @@ private void UpdateJobInvocationInfo() string name = _definition.Name; string command; - if (ScriptBlock != null) + if (ScriptBlock is not null) { command = ScriptBlock.ToString(); } - else if (FilePath != null) + else if (FilePath is not null) { command = FilePath; } @@ -484,7 +484,7 @@ private Dictionary UpdateParameters() } // ScriptBlock - if (ScriptBlock != null) + if (ScriptBlock is not null) { // FilePath cannot also be specified. if (newParameters.ContainsKey(ScheduledJobInvocationInfo.FilePathParameter)) @@ -503,7 +503,7 @@ private Dictionary UpdateParameters() } // FilePath - if (FilePath != null) + if (FilePath is not null) { // ScriptBlock cannot also be specified. if (newParameters.ContainsKey(ScheduledJobInvocationInfo.ScriptBlockParameter)) @@ -527,7 +527,7 @@ private Dictionary UpdateParameters() // Clear existing argument list only if new scriptblock or script file path was specified // (in this case old argument list is invalid). if (newParameters.ContainsKey(ScheduledJobInvocationInfo.ArgumentListParameter) && - (ScriptBlock != null || FilePath != null)) + (ScriptBlock is not null || FilePath is not null)) { newParameters.Remove(ScheduledJobInvocationInfo.ArgumentListParameter); } diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/SetJobTrigger.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/SetJobTrigger.cs index 4eeab7fcc72..3b7f9713e00 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/SetJobTrigger.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/SetJobTrigger.cs @@ -264,7 +264,7 @@ protected override void ProcessRecord() } ScheduledJobDefinition definition = trigger.JobDefinition; - if (definition != null) + if (definition is not null) { bool jobUpdateFailed = false; @@ -513,7 +513,7 @@ private bool ValidateOnceParams(ScheduledJobTrigger trigger = null) } } - if (trigger != null) + if (trigger is not null) { if (trigger.At == null && !MyInvocation.BoundParameters.ContainsKey(nameof(At))) { @@ -564,7 +564,7 @@ private bool ValidateDailyParams(ScheduledJobTrigger trigger = null) return false; } - if (trigger != null) + if (trigger is not null) { if (trigger.At == null && !MyInvocation.BoundParameters.ContainsKey(nameof(At))) { @@ -608,7 +608,7 @@ private bool ValidateWeeklyParams(ScheduledJobTrigger trigger = null) return false; } - if (trigger != null) + if (trigger is not null) { if (trigger.At == null && !MyInvocation.BoundParameters.ContainsKey(nameof(At))) { diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/SetScheduledJobOption.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/SetScheduledJobOption.cs index bc1e07b1473..dba7bd9226d 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/SetScheduledJobOption.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/SetScheduledJobOption.cs @@ -123,7 +123,7 @@ protected override void ProcessRecord() } // Update ScheduledJobDefinition with changes. - if (_jobOptions.JobDefinition != null) + if (_jobOptions.JobDefinition is not null) { _jobOptions.UpdateJobDefinition(); } diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/UnregisterJobDefinition.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/UnregisterJobDefinition.cs index c6c3885fb90..509b1681577 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/UnregisterJobDefinition.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/UnregisterJobDefinition.cs @@ -111,7 +111,7 @@ protected override void ProcessRecord() break; } - if (definitions != null) + if (definitions is not null) { foreach (ScheduledJobDefinition definition in definitions) { @@ -136,7 +136,7 @@ protected override void ProcessRecord() } // Check for unknown definition names. - if ((_names != null && _names.Length > 0) && + if ((_names is not null && _names.Length > 0) && (_definitions == null || _definitions.Length < _names.Length)) { // Make sure there is no PowerShell task in Task Scheduler with removed names. diff --git a/src/Microsoft.PowerShell.Security/security/AclCommands.cs b/src/Microsoft.PowerShell.Security/security/AclCommands.cs index df839b708e9..e5f58f634f5 100644 --- a/src/Microsoft.PowerShell.Security/security/AclCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/AclCommands.cs @@ -296,14 +296,14 @@ public static AuthorizationRuleCollection GetAccess(PSObject instance) // Get DACL AuthorizationRuleCollection dacl; CommonObjectSecurity cos = sd as CommonObjectSecurity; - if (cos != null) + if (cos is not null) { dacl = cos.GetAccessRules(true, true, typeof(NTAccount)); } else { DirectoryObjectSecurity dos = sd as DirectoryObjectSecurity; - Dbg.Diagnostics.Assert(dos != null, "Acl should be of type CommonObjectSecurity or DirectoryObjectSecurity"); + Dbg.Diagnostics.Assert(dos is not null, "Acl should be of type CommonObjectSecurity or DirectoryObjectSecurity"); dacl = dos.GetAccessRules(true, true, typeof(NTAccount)); } @@ -334,14 +334,14 @@ public static AuthorizationRuleCollection GetAudit(PSObject instance) AuthorizationRuleCollection sacl; CommonObjectSecurity cos = sd as CommonObjectSecurity; - if (cos != null) + if (cos is not null) { sacl = cos.GetAuditRules(true, true, typeof(NTAccount)); } else { DirectoryObjectSecurity dos = sd as DirectoryObjectSecurity; - Dbg.Diagnostics.Assert(dos != null, "Acl should be of type CommonObjectSecurity or DirectoryObjectSecurity"); + Dbg.Diagnostics.Assert(dos is not null, "Acl should be of type CommonObjectSecurity or DirectoryObjectSecurity"); sacl = dos.GetAuditRules(true, true, typeof(NTAccount)); } @@ -771,11 +771,11 @@ protected override void ProcessRecord() sections |= AccessControlSections.Audit; } - if (_inputObject != null) + if (_inputObject is not null) { PSMethodInfo methodInfo = _inputObject.Methods["GetSecurityDescriptor"]; - if (methodInfo != null) + if (methodInfo is not null) { object customDescriptor = null; @@ -859,7 +859,7 @@ protected override void ProcessRecord() InvokeProvider.SecurityDescriptor.Get(rp, sections, context); sd = context.GetAccumulatedObjects(); - if (sd != null) + if (sd is not null) { AddBrokeredProperties( sd, @@ -1334,20 +1334,20 @@ protected override void ProcessRecord() { ObjectSecurity aclObjectSecurity = _securityDescriptor as ObjectSecurity; - if (_inputObject != null) + if (_inputObject is not null) { PSMethodInfo methodInfo = _inputObject.Methods["SetSecurityDescriptor"]; - if (methodInfo != null) + if (methodInfo is not null) { CommonSecurityDescriptor aclCommonSD = _securityDescriptor as CommonSecurityDescriptor; string sddl; - if (aclObjectSecurity != null) + if (aclObjectSecurity is not null) { sddl = aclObjectSecurity.GetSecurityDescriptorSddlForm(AccessControlSections.All); } - else if (aclCommonSD != null) + else if (aclCommonSD is not null) { sddl = aclCommonSD.GetSddlForm(AccessControlSections.All); } @@ -1414,7 +1414,7 @@ protected override void ProcessRecord() return; } - if (CentralAccessPolicy != null || ClearCentralAccessPolicy) + if (CentralAccessPolicy is not null || ClearCentralAccessPolicy) { if (!DownLevelHelper.IsWin8AndAbove()) { @@ -1428,7 +1428,7 @@ protected override void ProcessRecord() } } - if (CentralAccessPolicy != null && ClearCentralAccessPolicy) + if (CentralAccessPolicy is not null && ClearCentralAccessPolicy) { Exception e = new ArgumentException(UtilsStrings.InvalidCentralAccessPolicyParameters); ErrorRecord er = @@ -1445,7 +1445,7 @@ protected override void ProcessRecord() NativeMethods.TOKEN_PRIVILEGE previousState = new NativeMethods.TOKEN_PRIVILEGE(); try { - if (CentralAccessPolicy != null) + if (CentralAccessPolicy is not null) { pSacl = GetSaclWithCapId(CentralAccessPolicy); if (pSacl == IntPtr.Zero) @@ -1503,7 +1503,7 @@ protected override void ProcessRecord() aclObjectSecurity, context); - if (CentralAccessPolicy != null || ClearCentralAccessPolicy) + if (CentralAccessPolicy is not null || ClearCentralAccessPolicy) { if (!pathInfo.Provider.NameEquals(Context.ProviderNames.FileSystem)) { diff --git a/src/Microsoft.PowerShell.Security/security/CatalogCommands.cs b/src/Microsoft.PowerShell.Security/security/CatalogCommands.cs index 5d094413904..461cd02d918 100644 --- a/src/Microsoft.PowerShell.Security/security/CatalogCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/CatalogCommands.cs @@ -87,12 +87,12 @@ protected override void ProcessRecord() // this cannot happen as we have specified the Path // property to be mandatory parameter // - Dbg.Assert((CatalogFilePath != null) && (CatalogFilePath.Length > 0), + Dbg.Assert((CatalogFilePath is not null) && (CatalogFilePath.Length > 0), "CatalogCommands: Param binder did not bind catalogFilePath"); Collection paths = new Collection(); - if (Path != null) + if (Path is not null) { foreach (string p in Path) { @@ -203,7 +203,7 @@ protected override void PerformAction(Collection path, string catalogFil FileInfo catalogFile = CatalogHelper.GenerateCatalog(this, path, catalogFilePath, catalogVersion); - if (catalogFile != null) + if (catalogFile is not null) { WriteObject(catalogFile); } diff --git a/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs b/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs index 4c9a518f66b..19a4fdc0a4c 100644 --- a/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs @@ -101,7 +101,7 @@ protected override void ProcessRecord() // this cannot happen as we have specified the Path // property to be a mandatory parameter // - Dbg.Assert((FilePath != null) && (FilePath.Length > 0), + Dbg.Assert((FilePath is not null) && (FilePath.Length > 0), "GetCertificateCommand: Param binder did not bind path"); X509Certificate2 cert = null; diff --git a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs index 173f6c2f423..5dfc9981301 100644 --- a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs +++ b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs @@ -162,7 +162,7 @@ public bool Equals(DnsNameRepresentation dnsName) { bool match = false; - if (_unicodeName != null && dnsName._unicodeName != null) + if (_unicodeName is not null && dnsName._unicodeName is not null) { if (string.Equals( _unicodeName, @@ -307,7 +307,7 @@ public X509NativeStore(X509StoreLocation StoreLocation, string StoreName) public void Open(bool includeArchivedCerts) { - if (_storeHandle != null && _archivedCerts != includeArchivedCerts) + if (_storeHandle is not null && _archivedCerts != includeArchivedCerts) { _storeHandle = null; // release the old handle } @@ -727,11 +727,11 @@ protected override void RemoveItem( ThrowInvalidOperation(errorId, message); } - if (DynamicParameters != null) + if (DynamicParameters is not null) { ProviderRemoveItemDynamicParameters dp = DynamicParameters as ProviderRemoveItemDynamicParameters; - if (dp != null) + if (dp is not null) { if (dp.DeleteKey) { @@ -885,7 +885,7 @@ protected override void MoveItem( } } - if (cert != null) // we get cert + if (cert is not null) // we get cert { // get destination store bool isDestContainer = false; @@ -894,7 +894,7 @@ protected override void MoveItem( X509Certificate2 certificate = cert as X509Certificate2; X509NativeStore certstore = store as X509NativeStore; - if (certstore != null) + if (certstore is not null) { certstore.Open(true); @@ -1073,17 +1073,17 @@ protected override bool HasChildItems(string path) object item = GetItemAtPath(path, false, out isContainer); - if ((item != null) && isContainer) + if ((item is not null) && isContainer) { X509StoreLocation storeLocation = item as X509StoreLocation; - if (storeLocation != null) + if (storeLocation is not null) { result = storeLocation.StoreNames.Count > 0; } else { X509NativeStore store = item as X509NativeStore; - if (store != null) + if (store is not null) { store.Open(IncludeArchivedCerts()); IntPtr certContext = store.GetFirstCert(); @@ -1236,7 +1236,7 @@ protected override void GetItem(string path) object item = GetItemAtPath(path, false, out isContainer); CertificateFilterInfo filter = GetFilter(); - if (item != null) + if (item is not null) { if (!isContainer) // certificate { @@ -1250,7 +1250,7 @@ protected override void GetItem(string path) // The filter is non null. If the certificate // satisfies the filter, output it. Otherwise, don't. X509Certificate2 cert = item as X509Certificate2; - Dbg.Diagnostics.Assert(cert != null, "item should be a certificate"); + Dbg.Diagnostics.Assert(cert is not null, "item should be a certificate"); if (MatchesFilter(cert, filter)) { @@ -1261,20 +1261,20 @@ protected override void GetItem(string path) else // container { // The item is a container. If the filter is non null, we don't output it. - if (filter != null) + if (filter is not null) { return; } X509StoreLocation storeLocation = item as X509StoreLocation; - if (storeLocation != null) // store location + if (storeLocation is not null) // store location { WriteItemObject(item, path, isContainer); } else // store { X509NativeStore store = item as X509NativeStore; - if (store != null) + if (store is not null) { // create X509Store X509Store outStore = new X509Store( @@ -1318,7 +1318,7 @@ protected override string GetParentPath(string path, string root) protected override string GetChildName(string path) { // Path for root is empty string - if (path != null && path.Length == 0) + if (path is not null && path.Length == 0) { return path; } @@ -1814,7 +1814,7 @@ private void RemoveCertStore(string storeName, bool fDeleteKey, string sourcePat /// No return. private void RemoveCertItem(X509Certificate2 cert, bool fDeleteKey, bool fMachine, string sourcePath) { - if (cert != null) + if (cert is not null) { string action = null; if (fDeleteKey) @@ -2138,7 +2138,7 @@ private object GetItemAtPath(string path, bool test, out bool isContainer) } } - if ((item != null) && test) + if ((item is not null) && test) { item = true; } @@ -2548,7 +2548,7 @@ private X509NativeStore GetStore(string storePath, ThrowItemNotFound(storePath, CertificateProviderItem.Store); } - if (s_storeCache != null) + if (s_storeCache is not null) { if (s_storeCache.Location != storeLocation || !string.Equals( @@ -2663,11 +2663,11 @@ private CertificateFilterInfo GetFilter() { CertificateFilterInfo filter = null; - if (DynamicParameters != null) + if (DynamicParameters is not null) { CertificateProviderDynamicParameters dp = DynamicParameters as CertificateProviderDynamicParameters; - if (dp != null) + if (dp is not null) { if (dp.CodeSigningCert) { @@ -2681,13 +2681,13 @@ private CertificateFilterInfo GetFilter() filter.Purpose = CertificatePurpose.DocumentEncryption; } - if (dp.DnsName != null) + if (dp.DnsName is not null) { filter = filter ?? new CertificateFilterInfo(); filter.DnsName = new WildcardPattern(dp.DnsName, WildcardOptions.IgnoreCase); } - if (dp.Eku != null) + if (dp.Eku is not null) { filter = filter ?? new CertificateFilterInfo(); filter.Eku = new List(); @@ -2739,12 +2739,12 @@ private static bool MatchesFilter(X509Certificate2 cert, CertificateFilterInfo f return false; } - if (filter.DnsName != null && !CertContainsName(cert, filter.DnsName)) + if (filter.DnsName is not null && !CertContainsName(cert, filter.DnsName)) { return false; } - if (filter.Eku != null && !CertContainsEku(cert, filter.Eku)) + if (filter.Eku is not null && !CertContainsEku(cert, filter.Eku)) { return false; } @@ -2865,7 +2865,7 @@ private static object GetCachedItem(string path) if (s_pathCache.ContainsKey(path)) { item = s_pathCache[path]; - Dbg.Diagnostics.Assert(item != null, "GetCachedItem"); + Dbg.Diagnostics.Assert(item is not null, "GetCachedItem"); } } @@ -2876,7 +2876,7 @@ private static void AddItemToCache(string path, object item) { lock (s_staticLock) { - if ((item != null) && (!s_pathCache.ContainsKey(path))) + if ((item is not null) && (!s_pathCache.ContainsKey(path))) { s_pathCache.Add(path, item); } @@ -2956,7 +2956,7 @@ string ICmdletProviderSupportsHelp.GetHelpMaml(string helpItemName, string path) // Execute the XPath query and return its MAML snippet XmlNode result = document.SelectSingleNode(xpathQuery, nsMgr); - if (result != null) + if (result is not null) { return result.OuterXml; } @@ -3101,7 +3101,7 @@ public bool Equals(EnhancedKeyUsageRepresentation keyUsage) { bool match = false; - if (_oid != null && keyUsage._oid != null) + if (_oid is not null && keyUsage._oid is not null) { // OID strings only contain numbers and periods @@ -3211,7 +3211,7 @@ public static void WriteSendAsTrustedIssuerProperty(X509Certificate2 cert, strin try { - if (certPath != null) + if (certPath is not null) { // try to open the store and get the cert out // in case the store handle is already released @@ -3252,7 +3252,7 @@ public static void WriteSendAsTrustedIssuerProperty(X509Certificate2 cert, strin // set property if (!Security.NativeMethods.CertSetCertificateContextProperty( - certFromStore != null ? certFromStore.Handle : cert.Handle, + certFromStore is not null ? certFromStore.Handle : cert.Handle, Security.NativeMethods.CertPropertyId.CERT_SEND_AS_TRUSTED_ISSUER_PROP_ID, 0, propertyPtr)) @@ -3338,7 +3338,7 @@ public EnhancedKeyUsageProperty(X509Certificate2 cert) if (extension.Oid.Value == "2.5.29.37") { X509EnhancedKeyUsageExtension ext = extension as X509EnhancedKeyUsageExtension; - if (ext != null) + if (ext is not null) { OidCollection oids = ext.EnhancedKeyUsages; foreach (Oid oid in oids) diff --git a/src/Microsoft.PowerShell.Security/security/CmsCommands.cs b/src/Microsoft.PowerShell.Security/security/CmsCommands.cs index c755e94a260..471c61986da 100644 --- a/src/Microsoft.PowerShell.Security/security/CmsCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/CmsCommands.cs @@ -168,7 +168,7 @@ protected override void EndProcessing() ErrorRecord terminatingError = null; string encodedContent = CmsUtils.Encrypt(contentBytes, To, this.SessionState, out terminatingError); - if (terminatingError != null) + if (terminatingError is not null) { ThrowTerminatingError(terminatingError); } @@ -539,14 +539,14 @@ private string Decrypt(string actualContent) EnvelopedCms cms = new EnvelopedCms(); X509Certificate2Collection certificates = new X509Certificate2Collection(); - if ((To != null) && (To.Length > 0)) + if ((To is not null) && (To.Length > 0)) { ErrorRecord error = null; foreach (CmsMessageRecipient recipient in To) { recipient.Resolve(this.SessionState, ResolutionPurpose.Decryption, out error); - if (error != null) + if (error is not null) { ThrowTerminatingError(error); return null; @@ -560,7 +560,7 @@ private string Decrypt(string actualContent) } string resultString = actualContent; - if (messageBytes != null) + if (messageBytes is not null) { cms.Decode(messageBytes); cms.Decrypt(certificates); @@ -570,12 +570,12 @@ private string Decrypt(string actualContent) if (IncludeContext) { - if (preContext != null) + if (preContext is not null) { resultString = preContext + resultString; } - if (postContext != null) + if (postContext is not null) { resultString = resultString + postContext; } diff --git a/src/Microsoft.PowerShell.Security/security/CredentialCommands.cs b/src/Microsoft.PowerShell.Security/security/CredentialCommands.cs index dddb9ee5302..80ed7c04597 100644 --- a/src/Microsoft.PowerShell.Security/security/CredentialCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/CredentialCommands.cs @@ -98,7 +98,7 @@ public GetCredentialCommand() : base() /// protected override void BeginProcessing() { - if (Credential != null) + if (Credential is not null) { WriteObject(Credential); return; @@ -121,7 +121,7 @@ protected override void BeginProcessing() WriteError(errorRecord); } - if (Credential != null) + if (Credential is not null) { WriteObject(Credential); } diff --git a/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs b/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs index 5ab15f08909..25ac6ee3684 100644 --- a/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs @@ -162,12 +162,12 @@ protected override void ProcessRecord() throw PSTraceSource.NewArgumentException(argumentName); } - if (SecureKey != null) + if (SecureKey is not null) { Dbg.Diagnostics.Assert(Key is null, "Only one encryption key should be specified"); encryptionResult = SecureStringHelper.Encrypt(SecureString, SecureKey); } - else if (Key != null) + else if (Key is not null) { encryptionResult = SecureStringHelper.Encrypt(SecureString, Key); } @@ -189,7 +189,7 @@ protected override void ProcessRecord() exportedString = SecureStringHelper.Protect(SecureString); } - if (encryptionResult != null) + if (encryptionResult is not null) { // The formatted string is Algorithm Version, // Initialization Vector, Encrypted Data @@ -211,7 +211,7 @@ protected override void ProcessRecord() string encodedString = Convert.ToBase64String(outputBytes); WriteObject(SecureStringHelper.SecureStringExportHeader + encodedString); } - else if (exportedString != null) + else if (exportedString is not null) { WriteObject(exportedString); } @@ -346,12 +346,12 @@ protected override void ProcessRecord() } } - if (SecureKey != null) + if (SecureKey is not null) { Dbg.Diagnostics.Assert(Key is null, "Only one encryption key should be specified"); importedString = SecureStringHelper.Decrypt(encryptedContent, SecureKey, iv); } - else if (Key != null) + else if (Key is not null) { importedString = SecureStringHelper.Decrypt(encryptedContent, Key, iv); } @@ -384,7 +384,7 @@ protected override void ProcessRecord() WriteError(er); } - if (importedString != null) + if (importedString is not null) { WriteObject(importedString); } diff --git a/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs b/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs index 1240ca95aea..2ce459c7e1d 100644 --- a/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs @@ -157,7 +157,7 @@ protected override void ProcessRecord() // this cannot happen as we have specified the Path // property to be mandatory parameter // - Dbg.Assert((FilePath != null) && (FilePath.Length > 0), + Dbg.Assert((FilePath is not null) && (FilePath.Length > 0), "GetSignatureCommand: Param binder did not bind path"); foreach (string p in FilePath) @@ -209,7 +209,7 @@ protected override void ProcessRecord() } else { - if ((Signature = PerformAction(resolvedFilePath)) != null) + if ((Signature = PerformAction(resolvedFilePath)) is not null) { WriteObject(Signature); } @@ -229,7 +229,7 @@ protected override void ProcessRecord() { foreach (string sourcePathOrExtension in SourcePathOrExtension) { - if ((Signature = PerformAction(sourcePathOrExtension, Content)) != null) + if ((Signature = PerformAction(sourcePathOrExtension, Content)) is not null) { WriteObject(Signature); } @@ -472,7 +472,7 @@ protected override Signature PerformAction(string filePath) { // remove readonly attributes on the file FileInfo fInfo = new FileInfo(filePath); - if (fInfo != null) + if (fInfo is not null) { // Save some disk write time by checking whether file is readonly.. if ((fInfo.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) @@ -575,7 +575,7 @@ protected override Signature PerformAction(string filePath) finally { // reset the read-only attribute - if (readOnlyFileInfo != null) + if (readOnlyFileInfo is not null) { readOnlyFileInfo.Attributes |= FileAttributes.ReadOnly; } diff --git a/src/Microsoft.WSMan.Management/ConfigProvider.cs b/src/Microsoft.WSMan.Management/ConfigProvider.cs index 44819207469..6e8ea7182d5 100644 --- a/src/Microsoft.WSMan.Management/ConfigProvider.cs +++ b/src/Microsoft.WSMan.Management/ConfigProvider.cs @@ -87,7 +87,7 @@ string ICmdletProviderSupportsHelp.GetHelpMaml(string helpItemName, string path) // Load the help file from the current UI culture subfolder of the module's root folder XmlDocument document = new XmlDocument(); CultureInfo culture = Host.CurrentUICulture; - string providerBase = this.ProviderInfo.PSSnapIn != null ? this.ProviderInfo.PSSnapIn.ApplicationBase : this.ProviderInfo.Module.ModuleBase; // "\windows\system32\WindowsPowerShell\v1.0" + string providerBase = this.ProviderInfo.PSSnapIn is not null ? this.ProviderInfo.PSSnapIn.ApplicationBase : this.ProviderInfo.Module.ModuleBase; // "\windows\system32\WindowsPowerShell\v1.0" string helpFile = null; do @@ -171,7 +171,7 @@ string ICmdletProviderSupportsHelp.GetHelpMaml(string helpItemName, string path) return string.Empty; } - if (result != null) + if (result is not null) { return result.ParentNode.OuterXml; } @@ -410,7 +410,7 @@ WsMan Config Can be divided in to Four Fixed Regions to Check Whether it has Chi if (WsManURI.Contains(WSManStringLiterals.containerListener)) { XmlDocument xmlListeners = EnumerateResourceValue(sessionobj, WsManURI); - if (xmlListeners != null) + if (xmlListeners is not null) { Hashtable KeyCache, ListenerObjCache; ProcessListenerObjects(xmlListeners, out ListenerObjCache, out KeyCache); @@ -459,7 +459,7 @@ WsMan Config Can be divided in to Four Fixed Regions to Check Whether it has Chi strPathCheck = strPathCheck + WSManStringLiterals.DefaultPathSeparator + currentpluginname; if (path.EndsWith(strPathCheck, StringComparison.OrdinalIgnoreCase)) { - if (objPluginNames != null) + if (objPluginNames is not null) { if (objPluginNames.Properties.Match(currentpluginname).Count > 0) { @@ -480,7 +480,7 @@ WsMan Config Can be divided in to Four Fixed Regions to Check Whether it has Chi strPathCheck = strPathCheck + WSManStringLiterals.DefaultPathSeparator; if (path.EndsWith(strPathCheck + WSManStringLiterals.containerResources, StringComparison.OrdinalIgnoreCase)) { - if (arrResources != null && arrResources.Count > 0) + if (arrResources is not null && arrResources.Count > 0) { return true; } @@ -488,7 +488,7 @@ WsMan Config Can be divided in to Four Fixed Regions to Check Whether it has Chi if (path.EndsWith(strPathCheck + WSManStringLiterals.containerInitParameters, StringComparison.OrdinalIgnoreCase)) { - if (arrInitParams != null && arrInitParams.Count > 0) + if (arrInitParams is not null && arrInitParams.Count > 0) { return true; } @@ -506,7 +506,7 @@ WsMan Config Can be divided in to Four Fixed Regions to Check Whether it has Chi return false; } - if (arrResources != null) + if (arrResources is not null) { foreach (PSObject objresource in arrResources) { @@ -524,7 +524,7 @@ WsMan Config Can be divided in to Four Fixed Regions to Check Whether it has Chi { if (path.EndsWith(strPathCheck + WSManStringLiterals.containerSecurity, StringComparison.OrdinalIgnoreCase)) { - if (arrSecurities != null && arrSecurities.Count > 0) + if (arrSecurities is not null && arrSecurities.Count > 0) { return true; } @@ -557,7 +557,7 @@ WsMan Config Can be divided in to Four Fixed Regions to Check Whether it has Chi XmlDocument xmlResourceValues = new XmlDocument(); xmlResourceValues.LoadXml(getXml.ToLowerInvariant()); XmlNodeList nodes = SearchXml(xmlResourceValues, childname, WsManURI, path, host); - if (nodes != null) + if (nodes is not null) { return IsItemContainer(nodes); } @@ -769,7 +769,7 @@ protected override void GetItem(string path) } else if (path.EndsWith(host + WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerPlugin + WSManStringLiterals.DefaultPathSeparator + currentpluginname + WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerInitParameters, StringComparison.OrdinalIgnoreCase)) { - if (arrInitParams != null) + if (arrInitParams is not null) { foreach (PSObject p in arrInitParams) { @@ -835,7 +835,7 @@ protected override void GetItem(string path) mshObject = BuildHostLevelPSObjectArrayList(sessionobj, uri, false); } - if (mshObject != null) + if (mshObject is not null) { if (mshObject.Properties[childname].Value.ToString().Equals(WSManStringLiterals.ContainerChildValue)) { @@ -1025,7 +1025,7 @@ protected override void SetItem(string path, object value) { PSCredential runAsCredentials = value as PSCredential; - if (runAsCredentials != null) + if (runAsCredentials is not null) { // UserName value = runAsCredentials.UserName; @@ -1176,7 +1176,7 @@ protected override void SetItem(string path, object value) { foreach (PSObject p in arrInitParams) { - if (p.Properties[ChildName] != null) + if (p.Properties[ChildName] is not null) { string xpathToUse = string.Format( CultureInfo.InvariantCulture, @@ -1302,7 +1302,7 @@ protected override void SetItem(string path, object value) } WSManProviderSetItemDynamicParameters dynParams = DynamicParameters as WSManProviderSetItemDynamicParameters; - if (dynParams != null) + if (dynParams is not null) { if (dynParams.Concatenate) { @@ -1481,7 +1481,7 @@ WsMan Config Can be divided in to Four Fixed Regions to Check Whether Item is Co XmlDocument xmlListeners = EnumerateResourceValue(sessionobj, WsManURI); - if (xmlListeners != null) + if (xmlListeners is not null) { Hashtable KeyCache, ListenerObjCache; ProcessListenerObjects(xmlListeners, out ListenerObjCache, out KeyCache); @@ -1501,7 +1501,7 @@ WsMan Config Can be divided in to Four Fixed Regions to Check Whether Item is Co } XmlDocument xmlCertificates = EnumerateResourceValue(sessionobj, WsManURI); - if (xmlCertificates != null) + if (xmlCertificates is not null) { Hashtable KeyCache, CertificatesObjCache; ProcessCertMappingObjects(xmlCertificates, out CertificatesObjCache, out KeyCache); @@ -1855,12 +1855,12 @@ protected override void NewItem(string path, string itemTypeName, object newItem listenerparams.Add("Address", niParams.Address); listenerparams.Add("Transport", niParams.Transport); listenerparams.Add("Enabled", niParams.Enabled); - if (niParams.HostName != null) + if (niParams.HostName is not null) { listenerparams.Add("Hostname", niParams.HostName); } - if (niParams.URLPrefix != null) + if (niParams.URLPrefix is not null) { listenerparams.Add("URLPrefix", niParams.URLPrefix); } @@ -1870,7 +1870,7 @@ protected override void NewItem(string path, string itemTypeName, object newItem listenerparams.Add("Port", niParams.Port); } - if (niParams.CertificateThumbPrint != null) + if (niParams.CertificateThumbPrint is not null) { listenerparams.Add("CertificateThumbPrint", niParams.CertificateThumbPrint); } @@ -1885,7 +1885,7 @@ protected override void NewItem(string path, string itemTypeName, object newItem Certparams.Add("Issuer", dynParams.Issuer); Certparams.Add("Subject", dynParams.Subject); Certparams.Add("Uri", dynParams.URI); - if (this.Credential.UserName != null) + if (this.Credential.UserName is not null) { System.Net.NetworkCredential nwCredentials = this.Credential.GetNetworkCredential(); Certparams.Add("UserName", nwCredentials.UserName); @@ -1967,15 +1967,15 @@ private void NewItemCreateComputerConnection(string Name) helper = new WSManHelper(this); WSManProviderNewItemComputerParameters dynParams = DynamicParameters as WSManProviderNewItemComputerParameters; string parametersetName = "ComputerName"; - if (dynParams != null) + if (dynParams is not null) { - if (dynParams.ConnectionURI != null) + if (dynParams.ConnectionURI is not null) { parametersetName = "URI"; } helper.CreateWsManConnection(parametersetName, dynParams.ConnectionURI, dynParams.Port, Name, dynParams.ApplicationName, dynParams.UseSSL, dynParams.Authentication, dynParams.SessionOption, this.Credential, dynParams.CertificateThumbprint); - if (dynParams.ConnectionURI != null) + if (dynParams.ConnectionURI is not null) { string[] constrsplit = dynParams.ConnectionURI.OriginalString.Split(":" + dynParams.Port + "/" + dynParams.ApplicationName, StringSplitOptions.None); string[] constrsplit1 = constrsplit[0].Split("//", StringSplitOptions.None); @@ -2028,7 +2028,7 @@ private void NewItemContainerListenerOrCertMapping(object sessionobj, string pat ProcessListenerObjects(xmlResource, out CCache, out kCache); } - if (CCache != null && CCache.Count > 0) + if (CCache is not null && CCache.Count > 0) { foreach (DictionaryEntry resource in CCache) { @@ -2065,7 +2065,7 @@ private void NewItemPluginOrPluginChild(object sessionobj, string path, string h if (path.EndsWith(strPathChk, StringComparison.OrdinalIgnoreCase)) { WSManProviderNewItemPluginParameters niParams = DynamicParameters as WSManProviderNewItemPluginParameters; - if (niParams != null) + if (niParams is not null) { if (string.IsNullOrEmpty(niParams.File)) { @@ -2075,7 +2075,7 @@ private void NewItemPluginOrPluginChild(object sessionobj, string path, string h mshObj.Properties.Add(new PSNoteProperty("SDKVersion", niParams.SDKVersion)); mshObj.Properties.Add(new PSNoteProperty("Capability", niParams.Capability)); - if (niParams.RunAsCredential != null) + if (niParams.RunAsCredential is not null) { mshObj.Properties.Add(new PSNoteProperty(WSManStringLiterals.ConfigRunAsUserName, niParams.RunAsCredential.UserName)); mshObj.Properties.Add(new PSNoteProperty(WSManStringLiterals.ConfigRunAsPasswordName, niParams.RunAsCredential.Password)); @@ -2096,7 +2096,7 @@ private void NewItemPluginOrPluginChild(object sessionobj, string path, string h mshObj.Properties.Add(new PSNoteProperty(WSManStringLiterals.ConfigUseSharedProcess, niParams.UseSharedProcess)); } - if (niParams.XMLRenderingType != null) + if (niParams.XMLRenderingType is not null) { mshObj.Properties.Add(new PSNoteProperty("XmlRenderingType", niParams.XMLRenderingType)); } @@ -2156,7 +2156,7 @@ private void NewItemPluginOrPluginChild(object sessionobj, string path, string h if (path.EndsWith(strPathChk, StringComparison.OrdinalIgnoreCase)) { WSManProviderNewItemResourceParameters niParams = DynamicParameters as WSManProviderNewItemResourceParameters; - if (niParams != null) + if (niParams is not null) { mshObj.Properties.Add(new PSNoteProperty("Resource", niParams.ResourceUri)); mshObj.Properties.Add(new PSNoteProperty("Capability", niParams.Capability)); @@ -2171,7 +2171,7 @@ private void NewItemPluginOrPluginChild(object sessionobj, string path, string h NewItem = ((PSObject)NewResource[0]).Properties["ResourceDir"].Value.ToString(); Keys = new string[] { "Uri=" + ((PSObject)NewResource[0]).Properties["ResourceURI"].Value.ToString() }; - if (ResourceArray != null) + if (ResourceArray is not null) { ResourceArray.Add(NewResource[0]); } @@ -2226,7 +2226,7 @@ private void NewItemPluginOrPluginChild(object sessionobj, string path, string h NewItem = ((PSObject)newSecurity[0]).Properties["SecurityDIR"].Value.ToString(); Keys = new string[] { "Uri=" + ((PSObject)newSecurity[0]).Properties["Uri"].Value.ToString() }; - if (SecurityArray != null) + if (SecurityArray is not null) { SecurityArray.Add(newSecurity[0]); } @@ -2246,7 +2246,7 @@ private void NewItemPluginOrPluginChild(object sessionobj, string path, string h xdoc.LoadXml(inputStr); ArrayList newInitParam = ProcessPluginInitParamLevel(xdoc); NewItem = niParams.ParamName; - if (InitParamArray != null) + if (InitParamArray is not null) { InitParamArray.Add(newInitParam[0]); } @@ -2309,10 +2309,10 @@ private PSObject GetItemPSObjectWithTypeName(string Name, string TypeNameOfEleme { object source = null; - if (input != null) + if (input is not null) { string sourceProp = Name + WSManStringLiterals.HiddenSuffixForSourceOfValue; - if (input.Properties[sourceProp] != null) + if (input.Properties[sourceProp] is not null) { source = input.Properties[sourceProp].Value; } @@ -2325,7 +2325,7 @@ private PSObject GetItemPSObjectWithTypeName(string Name, string TypeNameOfEleme if (!string.IsNullOrEmpty(ExtendedTypeName)) { StringBuilder types = new StringBuilder(string.Empty); - if (mshObject != null) + if (mshObject is not null) { types.Append(mshObject.ImmediateBaseObject.GetType().FullName); types.Append("#"); @@ -2650,7 +2650,7 @@ private void PutResourceValue(object sessionobj, string ResourceURI, Hashtable v try { inputxml = GetResourceValue(sessionobj, ResourceURI, value); - if (inputxml != null) + if (inputxml is not null) { bool Itemfound = false; XmlNamespaceManager nsmgr = new XmlNamespaceManager(inputxml.NameTable); @@ -2658,7 +2658,7 @@ private void PutResourceValue(object sessionobj, string ResourceURI, Hashtable v nsmgr.AddNamespace("cfg", uri_schema); string xpath = SetXPathString(ResourceURI); XmlNodeList nodelist = inputxml.SelectNodes(xpath, nsmgr); - if (nodelist != null && nodelist.Count == 1) + if (nodelist is not null && nodelist.Count == 1) { XmlNode node = (XmlNode)nodelist.Item(0); if (node.HasChildNodes) @@ -2807,7 +2807,7 @@ private void DeleteResourceValue(object sessionobj, string ResourceURI, Hashtabl // Support only for Listener,plugin and ClientCertificate. if (ResourceURI.Contains(WSManStringLiterals.containerPlugin) || ResourceURI.Contains(WSManStringLiterals.containerListener) || ResourceURI.Contains(WSManStringLiterals.containerCertMapping)) { - if (cmdlinevalues != null) + if (cmdlinevalues is not null) { ResourceURI = GetURIWithFilter(ResourceURI, cmdlinevalues); } @@ -2938,7 +2938,7 @@ private bool ContainResourceValue(object sessionobj, string ResourceURI, string private string GetURIWithFilter(string uri, Hashtable cmdlinevalues) { StringBuilder sburi = new StringBuilder(uri); - if (cmdlinevalues != null) + if (cmdlinevalues is not null) { if (uri.Contains("Config/Listener")) { @@ -3001,7 +3001,7 @@ private bool IsPKey(string value, string ResourceURI) private bool CheckPkeysArray(Hashtable values, string value, string[] pkeys) { bool result = false; - if (values != null) + if (values is not null) foreach (string key in pkeys) { if (values.Contains(key)) @@ -3075,7 +3075,7 @@ private void WritePSObjectPropertiesAsWSManElementObjects(PSObject psobject, str { string sourceProp = prop.Name + WSManStringLiterals.HiddenSuffixForSourceOfValue; object source = null; - if (psobject.Properties[sourceProp] != null) + if (psobject.Properties[sourceProp] is not null) { source = psobject.Properties[sourceProp].Value; } @@ -3090,7 +3090,7 @@ private void WritePSObjectPropertiesAsWSManElementObjects(PSObject psobject, str element = new WSManConfigLeafElement(prop.Name, null, prop.Value.ToString()); } - if (element != null) + if (element is not null) { mshObject = new PSObject(element); } @@ -3099,7 +3099,7 @@ private void WritePSObjectPropertiesAsWSManElementObjects(PSObject psobject, str if (!string.IsNullOrEmpty(ExtendedTypeName)) { StringBuilder types = new StringBuilder(string.Empty); - if (mshObject != null) + if (mshObject is not null) { types.Append(mshObject.ImmediateBaseObject.GetType().FullName); types.Append("#"); @@ -3157,7 +3157,7 @@ private string SplitAndUpdateStringUsingDelimiter(object sessionobj, string uri, string existingvalue = string.Empty; try { - if (mshObject != null) + if (mshObject is not null) { existingvalue = mshObject.Properties[childname].Value.ToString(); } @@ -3208,7 +3208,7 @@ private PSObject BuildHostLevelPSObjectArrayList(object objSessionObject, string } else { - if (objSessionObject != null) + if (objSessionObject is not null) { XmlDocument ConfigXml = GetResourceValue(objSessionObject, uri, null); // Moving in to @@ -3259,7 +3259,7 @@ private PSObject ConvertToPSObject(XmlNode xmlnode) mshObject.Properties.Add(new PSNoteProperty(node.LocalName, node.InnerText)); - if (attrSource != null) + if (attrSource is not null) { string propName = node.LocalName + WSManStringLiterals.HiddenSuffixForSourceOfValue; mshObject.Properties.Remove(propName); @@ -3571,7 +3571,7 @@ private string GetCorrectCaseOfPath(string path) private string GetCorrectCaseOfName(string ChildName, string hostname, string path) { string result = ChildName; - if (ChildName != null) + if (ChildName is not null) { if (!ChildName.Contains("_")) { @@ -3630,7 +3630,7 @@ private string GetCorrectCaseOfName(string ChildName, string hostname, string pa object sessionobj; SessionObjCache.TryGetValue(hostname, out sessionobj); XmlDocument outxml = FindResourceValue(sessionobj, uri, null); - if (outxml != null) + if (outxml is not null) { string currentPluginName = string.Empty; GetPluginNames(outxml, out objPluginNames, out currentPluginName, path); @@ -3662,7 +3662,7 @@ private string GetCorrectCaseOfName(string ChildName, string hostname, string pa private ArrayList RemoveItemfromResourceArray(ArrayList resourceArray, string ChildName, string type, string property) { - if (resourceArray != null) + if (resourceArray is not null) { bool itemfound = false; int index = 0; @@ -3820,7 +3820,7 @@ private void RemoveListenerOrCertMapping(object sessionobj, string WsManUri, str { XmlDocument xmlresources = EnumerateResourceValue(sessionobj, WsManUri); - if (xmlresources != null) + if (xmlresources is not null) { Hashtable KeysCache, ResourcesCache; if (!IsListener) @@ -3953,7 +3953,7 @@ private bool CheckValidContainerOrPath(string path) return true; } - if (arrResources != null) + if (arrResources is not null) { strpathChk = strpathChk + WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerResources; foreach (PSObject objresource in arrResources) @@ -4015,7 +4015,7 @@ private bool CheckValidContainerOrPath(string path) } else { - if (arrInitParams != null) + if (arrInitParams is not null) { foreach (PSObject obj in arrInitParams) { @@ -4344,7 +4344,7 @@ private void GetChildItemsOrNames(string path, ProviderMethods methodname, bool strPathchk = strPathchk + currentpluginname + WSManStringLiterals.DefaultPathSeparator; if (path.EndsWith(strPathchk + WSManStringLiterals.containerResources, StringComparison.OrdinalIgnoreCase)) { - if (arrResources != null) + if (arrResources is not null) { foreach (PSObject p in arrResources) { @@ -4414,7 +4414,7 @@ private void GetChildItemsOrNames(string path, ProviderMethods methodname, bool strPathchk = strPathchk + sResourceDirName + WSManStringLiterals.DefaultPathSeparator; if (path.EndsWith(strPathchk + WSManStringLiterals.containerSecurity, StringComparison.OrdinalIgnoreCase) || path.Contains(WSManStringLiterals.DefaultPathSeparator + WSManStringLiterals.containerSecurity + "_")) { - if (arrSecurity != null) + if (arrSecurity is not null) { foreach (PSObject objsecurity in arrSecurity) { @@ -4840,7 +4840,7 @@ private PSObject ProcessPluginConfigurationLevel(XmlDocument xmldoc, bool setRun { PSObject objConfiglvl = null; - if (xmldoc != null) + if (xmldoc is not null) { XmlNodeList nodelistPlugin = xmldoc.GetElementsByTagName("PlugInConfiguration"); if (nodelistPlugin.Count > 0) @@ -4849,7 +4849,7 @@ private PSObject ProcessPluginConfigurationLevel(XmlDocument xmldoc, bool setRun XmlAttributeCollection attributecol = nodelistPlugin.Item(0).Attributes; XmlNode runAsUserNode = attributecol.GetNamedItem(WSManStringLiterals.ConfigRunAsUserName); - bool runAsUserPresent = runAsUserNode != null && !string.IsNullOrEmpty(runAsUserNode.Value); + bool runAsUserPresent = runAsUserNode is not null && !string.IsNullOrEmpty(runAsUserNode.Value); for (int i = 0; i <= attributecol.Count - 1; i++) { @@ -4866,7 +4866,7 @@ private PSObject ProcessPluginConfigurationLevel(XmlDocument xmldoc, bool setRun } } // Containers in Plugin Level Configs - if (objConfiglvl != null) + if (objConfiglvl is not null) { objConfiglvl.Properties.Add(new PSNoteProperty("InitializationParameters", WSManStringLiterals.ContainerChildValue)); objConfiglvl.Properties.Add(new PSNoteProperty("Resources", WSManStringLiterals.ContainerChildValue)); @@ -4881,7 +4881,7 @@ private ArrayList ProcessPluginResourceLevel(XmlDocument xmldoc, out ArrayList a { ArrayList Resources = null; ArrayList nSecurity = null; - if (xmldoc != null) + if (xmldoc is not null) { XmlNodeList xmlpluginResource = xmldoc.GetElementsByTagName("Resource"); if (xmlpluginResource.Count > 0) @@ -4966,7 +4966,7 @@ private ArrayList ProcessPluginResourceLevel(XmlDocument xmldoc, out ArrayList a private ArrayList ProcessPluginInitParamLevel(XmlDocument xmldoc) { ArrayList InitParamLvl = null; - if (xmldoc != null) + if (xmldoc is not null) { XmlNodeList nodelistInitParam = xmldoc.GetElementsByTagName("Param"); if (nodelistInitParam.Count > 0) @@ -5004,7 +5004,7 @@ private ArrayList ProcessPluginInitParamLevel(XmlDocument xmldoc) private ArrayList ProcessPluginSecurityLevel(ArrayList arrSecurity, XmlDocument xmlSecurity, string UniqueResourceID, string ParentResourceUri) { // ArrayList SecurityLvl = null; - if (xmlSecurity != null) + if (xmlSecurity is not null) { XmlNodeList nodelistSecurity = xmlSecurity.GetElementsByTagName(WSManStringLiterals.containerSecurity); if (nodelistSecurity.Count > 0) @@ -5074,7 +5074,7 @@ private string ConstructPluginXml(PSObject objinputparam, string ResourceURI, st @"http://schemas.microsoft.com/wbem/wsman/1/config/PluginConfiguration", WSManStringLiterals.EnclosingDoubleQuotes)); - if (objinputparam != null) + if (objinputparam is not null) { foreach (PSPropertyInfo prop in objinputparam.Properties) { @@ -5106,16 +5106,16 @@ private string ConstructPluginXml(PSObject objinputparam, string ResourceURI, st sbvalues.Append(WSManStringLiterals.GreaterThan); if (Operation.Equals("New")) { - if (objinputparam != null) + if (objinputparam is not null) sbvalues.Append(ConstructResourceXml(objinputparam, null, null)); else sbvalues.Append(ConstructResourceXml(null, resources, null)); } else if (Operation.Equals("Set")) { - if (initParams != null) + if (initParams is not null) sbvalues.Append(ConstructInitParamsXml(null, initParams)); - if (resources != null) + if (resources is not null) sbvalues.Append(ConstructResourceXml(null, resources, securities)); } @@ -5146,7 +5146,7 @@ private object ValidateAndGetUserObject(string configurationName, object value) if (configurationName.Equals(WSManStringLiterals.ConfigRunAsPasswordName, StringComparison.OrdinalIgnoreCase)) { - if (basePsObject != null && basePsObject.BaseObject is SecureString) + if (basePsObject is not null && basePsObject.BaseObject is SecureString) { return basePsObject.BaseObject as SecureString; } @@ -5163,11 +5163,11 @@ private object ValidateAndGetUserObject(string configurationName, object value) } else if (configurationName.Equals(WSManStringLiterals.ConfigRunAsUserName, StringComparison.OrdinalIgnoreCase)) { - if (basePsObject != null && basePsObject.BaseObject is PSCredential) + if (basePsObject is not null && basePsObject.BaseObject is PSCredential) { return basePsObject.BaseObject as PSCredential; } - else if (psCredential != null) + else if (psCredential is not null) { return psCredential; } @@ -5196,7 +5196,7 @@ private string GetStringFromSecureString(object propertyValue) SecureString value = propertyValue as SecureString; string passwordValueToAdd = string.Empty; - if (value != null) + if (value is not null) { IntPtr ptr = Marshal.SecureStringToBSTR(value); passwordValueToAdd = Marshal.PtrToStringAuto(ptr); @@ -5216,7 +5216,7 @@ private string ConstructResourceXml(PSObject objinputparams, ArrayList resources object[] capability = null; sbvalues.Append(""); - if (objinputparams != null) + if (objinputparams is not null) { sbvalues.Append(""); @@ -5282,7 +5282,7 @@ private string ConstructResourceXml(PSObject objinputparams, ArrayList resources } sbvalues.Append(WSManStringLiterals.GreaterThan); - if (securities != null) + if (securities is not null) sbvalues.Append(ConstructSecurityXml(null, securities, p.Properties["ResourceDir"].Value.ToString())); sbvalues.Append(ConstructCapabilityXml(capability)); sbvalues.Append(""); @@ -5302,7 +5302,7 @@ private string ConstructSecurityXml(PSObject objinputparams, ArrayList securitie return sbvalues.ToString(); } - if (objinputparams != null) + if (objinputparams is not null) { AddSecurityProperties(objinputparams.Properties, sbvalues); } @@ -5357,7 +5357,7 @@ private string ConstructInitParamsXml(PSObject objinputparams, ArrayList initpar } sbvalues.Append(""); - if (objinputparams != null) + if (objinputparams is not null) { foreach (PSPropertyInfo prop in objinputparams.Properties) { diff --git a/src/Microsoft.WSMan.Management/CredSSP.cs b/src/Microsoft.WSMan.Management/CredSSP.cs index a2fc021934c..6d8e9ece619 100644 --- a/src/Microsoft.WSMan.Management/CredSSP.cs +++ b/src/Microsoft.WSMan.Management/CredSSP.cs @@ -171,7 +171,7 @@ private void DisableClientSideSettings() helper.AssertError(m_SessionObj.Error, true, null); } - if (m_SessionObj != null) + if (m_SessionObj is not null) Dispose(m_SessionObj); } } @@ -220,7 +220,7 @@ private void DisableServerSideSettings() helper.AssertError(m_SessionObj.Error, true, null); } - if (m_SessionObj != null) + if (m_SessionObj is not null) { Dispose(m_SessionObj); } @@ -258,7 +258,7 @@ private void DeleteDelegateSettings(string applicationname, RegistryKey rootKey, { string Registry_Path_Credentials_Delegation = Registry_Path + @"\CredentialsDelegation"; RegistryKey Allow_Fresh_Credential_Key = rootKey.OpenSubKey(Registry_Path_Credentials_Delegation + @"\" + helper.Key_Allow_Fresh_Credentials, true); - if (Allow_Fresh_Credential_Key != null) + if (Allow_Fresh_Credential_Key is not null) { string[] valuenames = Allow_Fresh_Credential_Key.GetValueNames(); if (valuenames.Length > 0) @@ -267,7 +267,7 @@ private void DeleteDelegateSettings(string applicationname, RegistryKey rootKey, foreach (string value in valuenames) { object keyvalue = Allow_Fresh_Credential_Key.GetValue(value); - if (keyvalue != null) + if (keyvalue is not null) { if (!keyvalue.ToString().StartsWith(applicationname, StringComparison.OrdinalIgnoreCase)) { @@ -290,21 +290,21 @@ private void DeleteDelegateSettings(string applicationname, RegistryKey rootKey, if (!otherkeys) { rKey = rootKey.OpenSubKey(Registry_Path_Credentials_Delegation, true); - if (rKey != null) + if (rKey is not null) { object regval1 = rKey.GetValue(helper.Key_Allow_Fresh_Credentials); - if (regval1 != null) + if (regval1 is not null) { rKey.DeleteValue(helper.Key_Allow_Fresh_Credentials, false); } object regval2 = rKey.GetValue(helper.Key_Concatenate_Defaults_AllowFresh); - if (regval2 != null) + if (regval2 is not null) { rKey.DeleteValue(helper.Key_Concatenate_Defaults_AllowFresh, false); } - if (rKey.OpenSubKey(helper.Key_Allow_Fresh_Credentials) != null) + if (rKey.OpenSubKey(helper.Key_Allow_Fresh_Credentials) is not null) { rKey.DeleteSubKeyTree(helper.Key_Allow_Fresh_Credentials); } @@ -447,7 +447,7 @@ protected override void BeginProcessing() helper = new WSManHelper(this); // DelegateComputer cannot be specified when Role is other than client - if ((delegatecomputer != null) && !Role.Equals(Client, StringComparison.OrdinalIgnoreCase)) + if ((delegatecomputer is not null) && !Role.Equals(Client, StringComparison.OrdinalIgnoreCase)) { string message = helper.FormatResourceMsgFromResourcetext("CredSSPRoleAndDelegateCannotBeSpecified", "DelegateComputer", @@ -557,7 +557,7 @@ private void EnableClientSideSettings() helper.AssertError(m_SessionObj.Error, true, delegatecomputer); } - if (m_SessionObj != null) + if (m_SessionObj is not null) { Dispose(m_SessionObj); } @@ -617,7 +617,7 @@ private void EnableServerSideSettings() helper.AssertError(m_SessionObj.Error, true, delegatecomputer); } - if (m_SessionObj != null) + if (m_SessionObj is not null) { Dispose(m_SessionObj); } @@ -672,7 +672,7 @@ private void UpdateGPORegistrySettings(string applicationname, string[] delegate // add the delegate value Allow_Fresh_Credential_Key = rootKey.OpenSubKey(Registry_Path_Credentials_Delegation + @"\" + helper.Key_Allow_Fresh_Credentials, true) ?? rootKey.CreateSubKey(Registry_Path_Credentials_Delegation + @"\" + helper.Key_Allow_Fresh_Credentials, RegistryKeyPermissionCheck.ReadWriteSubTree); - if (Allow_Fresh_Credential_Key != null) + if (Allow_Fresh_Credential_Key is not null) { i = Allow_Fresh_Credential_Key.ValueCount; foreach (string del in delegatestring) @@ -760,10 +760,10 @@ private string GetDelegateSettings(string applicationname) { string Reg_key = helper.Registry_Path_Credentials_Delegation + @"\CredentialsDelegation"; rKey = rootKey.OpenSubKey(Reg_key); - if (rKey != null) + if (rKey is not null) { rKey = rKey.OpenSubKey(helper.Key_Allow_Fresh_Credentials); - if (rKey != null) + if (rKey is not null) { valuenames = rKey.GetValueNames(); if (valuenames.Length > 0) @@ -772,7 +772,7 @@ private string GetDelegateSettings(string applicationname) foreach (string value in valuenames) { object keyvalue = rKey.GetValue(value); - if (keyvalue != null) + if (keyvalue is not null) { if (keyvalue.ToString().StartsWith(applicationname, StringComparison.OrdinalIgnoreCase)) { @@ -892,7 +892,7 @@ protected override void BeginProcessing() helper.AssertError(m_SessionObj.Error, true, null); } - if (m_SessionObj != null) + if (m_SessionObj is not null) { Dispose(m_SessionObj); } diff --git a/src/Microsoft.WSMan.Management/CurrentConfigurations.cs b/src/Microsoft.WSMan.Management/CurrentConfigurations.cs index 9f8830b8009..26baa971392 100644 --- a/src/Microsoft.WSMan.Management/CurrentConfigurations.cs +++ b/src/Microsoft.WSMan.Management/CurrentConfigurations.cs @@ -127,7 +127,7 @@ public void RemoveOneConfiguration(string pathToNodeFromRoot) pathToNodeFromRoot, this.nameSpaceManger); - if (nodeToRemove != null) + if (nodeToRemove is not null) { if (nodeToRemove is XmlAttribute) { @@ -170,7 +170,7 @@ public void UpdateOneConfiguration(string pathToNodeFromRoot, string configurati pathToNodeFromRoot, this.nameSpaceManger); - if (nodeToUpdate != null) + if (nodeToUpdate is not null) { foreach (XmlAttribute attribute in nodeToUpdate.Attributes) { @@ -205,7 +205,7 @@ public string GetOneConfiguration(string pathFromRoot) pathFromRoot, this.nameSpaceManger); - if (requiredNode != null) + if (requiredNode is not null) { return requiredNode.Value; } diff --git a/src/Microsoft.WSMan.Management/InvokeWSManAction.cs b/src/Microsoft.WSMan.Management/InvokeWSManAction.cs index 71f8ae4c84d..f809186f464 100644 --- a/src/Microsoft.WSMan.Management/InvokeWSManAction.cs +++ b/src/Microsoft.WSMan.Management/InvokeWSManAction.cs @@ -295,7 +295,7 @@ protected override void ProcessRecord() helper.AssertError(m_session.Error, true, resourceuri); } - if (m_session != null) + if (m_session is not null) Dispose(m_session); } } diff --git a/src/Microsoft.WSMan.Management/NewWSManSession.cs b/src/Microsoft.WSMan.Management/NewWSManSession.cs index 56d69ade76f..5899785b8ad 100644 --- a/src/Microsoft.WSMan.Management/NewWSManSession.cs +++ b/src/Microsoft.WSMan.Management/NewWSManSession.cs @@ -244,7 +244,7 @@ protected override void BeginProcessing() } } - if ((_proxycredential != null) && (proxyauthentication == 0)) + if ((_proxycredential is not null) && (proxyauthentication == 0)) { InvalidOperationException ex = new InvalidOperationException(helper.GetResourceMsgFromResourcetext("NewWSManSessionOptionAuth")); ErrorRecord er = new ErrorRecord(ex, "InvalidOperationException", ErrorCategory.InvalidOperation, null); @@ -270,7 +270,7 @@ protected override void BeginProcessing() objSessionOption.UseEncryption = false; } - if (_proxycredential != null) + if (_proxycredential is not null) { NetworkCredential nwCredentials = _proxycredential.GetNetworkCredential(); objSessionOption.ProxyCredential = nwCredentials; diff --git a/src/Microsoft.WSMan.Management/PingWSMan.cs b/src/Microsoft.WSMan.Management/PingWSMan.cs index 9581eaabc33..4115cfaf154 100644 --- a/src/Microsoft.WSMan.Management/PingWSMan.cs +++ b/src/Microsoft.WSMan.Management/PingWSMan.cs @@ -168,7 +168,7 @@ protected override void ProcessRecord() } finally { - if (m_SessionObj != null) + if (m_SessionObj is not null) Dispose(m_SessionObj); } } diff --git a/src/Microsoft.WSMan.Management/Set-QuickConfig.cs b/src/Microsoft.WSMan.Management/Set-QuickConfig.cs index c318ea76477..86fd139326d 100644 --- a/src/Microsoft.WSMan.Management/Set-QuickConfig.cs +++ b/src/Microsoft.WSMan.Management/Set-QuickConfig.cs @@ -158,7 +158,7 @@ private void QuickConfigRemoting(bool serviceonly) string enabled = resultopxml.SelectSingleNode(xpathEnabled, nsmgr).InnerText; XmlNode sourceAttribute = resultopxml.SelectSingleNode(xpathEnabled, nsmgr).Attributes.GetNamedItem("Source"); string source = null; - if (sourceAttribute != null) + if (sourceAttribute is not null) { source = sourceAttribute.Value; } @@ -191,7 +191,7 @@ private void QuickConfigRemoting(bool serviceonly) } string resultAction = resultopxml.SelectSingleNode(xpathText, nsmgr).InnerText; - if (source != null && source.Equals("GPO")) + if (source is not null && source.Equals("GPO")) { string Info_Msg = WSManResourceLoader.GetResourceString("L_QuickConfig_RemotingDisabledbyGP_00_ErrorMessage"); Info_Msg += " " + resultAction; @@ -258,7 +258,7 @@ private void QuickConfigRemoting(bool serviceonly) helper.AssertError(m_SessionObj.Error, true, null); } - if (m_SessionObj != null) + if (m_SessionObj is not null) Dispose(m_SessionObj); } } diff --git a/src/Microsoft.WSMan.Management/WSManConnections.cs b/src/Microsoft.WSMan.Management/WSManConnections.cs index 36aa9ab0dea..3e84e210f17 100644 --- a/src/Microsoft.WSMan.Management/WSManConnections.cs +++ b/src/Microsoft.WSMan.Management/WSManConnections.cs @@ -254,7 +254,7 @@ public SwitchParameter UseSSL protected override void BeginProcessing() { WSManHelper helper = new WSManHelper(this); - if (connectionuri != null) + if (connectionuri is not null) { try { @@ -362,7 +362,7 @@ protected override void BeginProcessing() } object _ws = helper.RemoveFromDictionary(computername); - if (_ws != null) + if (_ws is not null) { Dispose(_ws); } diff --git a/src/Microsoft.WSMan.Management/WSManInstance.cs b/src/Microsoft.WSMan.Management/WSManInstance.cs index 5a3d6b74f7f..d7e991d8b35 100644 --- a/src/Microsoft.WSMan.Management/WSManInstance.cs +++ b/src/Microsoft.WSMan.Management/WSManInstance.cs @@ -429,7 +429,7 @@ private void ReturnEnumeration(IWSManEx wsmanObject, IWSManResourceLocator wsman { int flags = 0; IWSManEnumerator obj; - if (returntype != null) + if (returntype is not null) { if (returntype.Equals("object", StringComparison.OrdinalIgnoreCase)) { @@ -458,7 +458,7 @@ private void ReturnEnumeration(IWSManEx wsmanObject, IWSManResourceLocator wsman flags |= wsmanObject.EnumerationFlagHierarchyDeep(); } - if (dialect != null && filter != null) + if (dialect is not null && filter is not null) { if (dialect.ToString().Equals(helper.ALIAS_WQL, StringComparison.OrdinalIgnoreCase) || dialect.ToString().Equals(helper.URI_WQL_DIALECT, StringComparison.OrdinalIgnoreCase)) { @@ -488,7 +488,7 @@ private void ReturnEnumeration(IWSManEx wsmanObject, IWSManResourceLocator wsman obj = (IWSManEnumerator)wsmanSession.Enumerate(wsmanResourceLocator, filter, dialect.ToString(), flags); } - else if (filter != null) + else if (filter is not null) { fragment = helper.URI_WQL_DIALECT; dialect = new Uri(fragment); @@ -524,7 +524,7 @@ protected override void ProcessRecord() helper.WSManOp = "Get"; string connectionStr = null; connectionStr = helper.CreateConnectionString(connectionuri, port, computername, applicationname); - if (connectionuri != null) + if (connectionuri is not null) { try { @@ -589,7 +589,7 @@ protected override void ProcessRecord() helper.AssertError(m_session.Error, true, resourceuri); } - if (m_session != null) + if (m_session is not null) Dispose(m_session); } } @@ -890,7 +890,7 @@ protected override void ProcessRecord() helper.WSManOp = "set"; IWSManSession m_session = null; - if (dialect != null) + if (dialect is not null) { if (dialect.ToString().Equals(helper.ALIAS_WQL, StringComparison.OrdinalIgnoreCase)) dialect = new Uri(helper.URI_WQL_DIALECT); @@ -904,7 +904,7 @@ protected override void ProcessRecord() { string connectionStr = string.Empty; connectionStr = helper.CreateConnectionString(connectionuri, port, computername, applicationname); - if (connectionuri != null) + if (connectionuri is not null) { try { @@ -960,7 +960,7 @@ protected override void ProcessRecord() helper.AssertError(m_session.Error, true, resourceuri); } - if (m_session != null) + if (m_session is not null) Dispose(m_session); } } @@ -1198,7 +1198,7 @@ protected override void ProcessRecord() { string connectionStr = string.Empty; connectionStr = helper.CreateConnectionString(connectionuri, port, computername, applicationname); - if (connectionuri != null) + if (connectionuri is not null) { try { @@ -1237,7 +1237,7 @@ protected override void ProcessRecord() helper.AssertError(m_wsmanObject.Error, true, resourceuri); } - if (m_session != null) + if (m_session is not null) Dispose(m_session); } } @@ -1487,7 +1487,7 @@ protected override void BeginProcessing() helper = new WSManHelper(this); helper.WSManOp = "new"; connectionStr = helper.CreateConnectionString(connectionuri, port, computername, applicationname); - if (connectionuri != null) + if (connectionuri is not null) { try { @@ -1540,7 +1540,7 @@ protected override void ProcessRecord() helper.AssertError(m_session.Error, true, resourceuri); } - if (m_session != null) + if (m_session is not null) { Dispose(m_session); } diff --git a/src/Microsoft.WSMan.Management/WsManHelper.cs b/src/Microsoft.WSMan.Management/WsManHelper.cs index eaadfb706be..5d63bc804c8 100644 --- a/src/Microsoft.WSMan.Management/WsManHelper.cs +++ b/src/Microsoft.WSMan.Management/WsManHelper.cs @@ -191,7 +191,7 @@ private static string FormatResourceMsgFromResourcetextS( string template = resourceManager.GetString(resourceName); string result = null; - if (template != null) + if (template is not null) { result = string.Format(CultureInfo.CurrentCulture, template, args); @@ -291,7 +291,7 @@ internal static Dictionary GetSessionObjCache() internal string GetRootNodeName(string operation, string resourceUri, string actionStr) { string resultStr = null, sfx = null; - if (resourceUri != null) + if (resourceUri is not null) { resultStr = resourceUri; resultStr = StripParams(resultStr); @@ -370,13 +370,13 @@ internal string ReadFile(string path) } finally { - if (_sr != null) + if (_sr is not null) { // _sr.Close(); _sr.Dispose(); } - if (_fs != null) + if (_fs is not null) { // _fs.Close(); _fs.Dispose(); @@ -411,7 +411,7 @@ internal string ProcessInput(IWSManEx wsman, string filepath, string operation, string xmlns = GetXmlNs(resourceUri.ResourceUri); // if valueset is given, i.e hashtable - if (valueset != null) + if (valueset is not null) { foreach (DictionaryEntry entry in valueset) { @@ -436,7 +436,7 @@ internal string ProcessInput(IWSManEx wsman, string filepath, string operation, xmlfile.LoadXml(getResult); string xpathString = null; - if (valueset != null) + if (valueset is not null) { foreach (DictionaryEntry entry in valueset) { @@ -523,13 +523,13 @@ internal XmlNode GetXmlNode(string xmlString, string xpathpattern, string xmlnam internal string CreateConnectionString(Uri ConnUri, int port, string computername, string applicationname) { string ConnectionString = null; - if (ConnUri != null) + if (ConnUri is not null) { ConnectionString = ConnUri.OriginalString; } else { - if (computername is null && (port != 0 || applicationname != null)) + if (computername is null && (port != 0 || applicationname is not null)) { // the user didn't give us a computer name but he gave a port and/or application name; // in this case we need to have a computer name, to form the connection string; @@ -543,7 +543,7 @@ internal string CreateConnectionString(Uri ConnUri, int port, string computernam ConnectionString = ConnectionString + ":" + port; } - if (applicationname != null) + if (applicationname is not null) { ConnectionString = ConnectionString + "/" + applicationname; } @@ -555,12 +555,12 @@ internal string CreateConnectionString(Uri ConnUri, int port, string computernam internal IWSManResourceLocator InitializeResourceLocator(Hashtable optionset, Hashtable selectorset, string fragment, Uri dialect, IWSManEx wsmanObj, Uri resourceuri) { string resource = null; - if (resourceuri != null) + if (resourceuri is not null) { resource = resourceuri.ToString(); } - if (selectorset != null) + if (selectorset is not null) { resource = resource + "?"; int i = 0; @@ -578,7 +578,7 @@ internal IWSManResourceLocator InitializeResourceLocator(Hashtable optionset, Ha { m_resource = (IWSManResourceLocator)wsmanObj.CreateResourceLocator(resource); - if (optionset != null) + if (optionset is not null) { foreach (DictionaryEntry entry in optionset) { @@ -598,7 +598,7 @@ internal IWSManResourceLocator InitializeResourceLocator(Hashtable optionset, Ha m_resource.FragmentPath = fragment; } - if (dialect != null) + if (dialect is not null) { m_resource.FragmentDialect = dialect.ToString(); } @@ -624,7 +624,7 @@ internal IWSManResourceLocator InitializeResourceLocator(Hashtable optionset, Ha /// internal static void ValidateSpecifiedAuthentication(AuthenticationMechanism authentication, PSCredential credential, string certificateThumbprint) { - if ((credential != null) && (certificateThumbprint != null)) + if ((credential is not null) && (certificateThumbprint is not null)) { string message = FormatResourceMsgFromResourcetextS( "AmbiguosAuthentication", @@ -635,7 +635,7 @@ internal static void ValidateSpecifiedAuthentication(AuthenticationMechanism aut if ((authentication != AuthenticationMechanism.Default) && (authentication != AuthenticationMechanism.ClientCertificate) && - (certificateThumbprint != null)) + (certificateThumbprint is not null)) { string message = FormatResourceMsgFromResourcetextS( "AmbiguosAuthentication", @@ -652,7 +652,7 @@ internal IWSManSession CreateSessionObject(IWSManEx wsmanObject, AuthenticationM ////if authentication is given int sessionFlags = 0; - if (authentication.ToString() != null) + if (authentication.ToString() is not null) { if (authentication.Equals(AuthenticationMechanism.None)) { @@ -691,11 +691,11 @@ internal IWSManSession CreateSessionObject(IWSManEx wsmanObject, AuthenticationM } IWSManConnectionOptionsEx2 connObject = (IWSManConnectionOptionsEx2)wsmanObject.CreateConnectionOptions(); - if (credential != null) + if (credential is not null) { // connObject = (IWSManConnectionOptionsEx2)wsmanObject.CreateConnectionOptions(); System.Net.NetworkCredential nwCredential = new System.Net.NetworkCredential(); - if (credential.UserName != null) + if (credential.UserName is not null) { nwCredential = credential.GetNetworkCredential(); if (string.IsNullOrEmpty(nwCredential.Domain)) @@ -723,13 +723,13 @@ internal IWSManSession CreateSessionObject(IWSManEx wsmanObject, AuthenticationM } } - if (certificateThumbprint != null) + if (certificateThumbprint is not null) { connObject.CertificateThumbprint = certificateThumbprint; sessionFlags = sessionFlags | (int)WSManSessionFlags.WSManFlagUseClientCertificate; } - if (sessionoption != null) + if (sessionoption is not null) { if (sessionoption.ProxyAuthentication != 0) { @@ -765,7 +765,7 @@ internal IWSManSession CreateSessionObject(IWSManEx wsmanObject, AuthenticationM ProxyAuthenticationFlags = connObject.ProxyAuthenticationUseDigest(); } - if (sessionoption.ProxyCredential != null) + if (sessionoption.ProxyCredential is not null) { try { @@ -832,7 +832,7 @@ internal IWSManSession CreateSessionObject(IWSManEx wsmanObject, AuthenticationM try { m_SessionObj = (IWSManSession)wsmanObject.CreateSession(connectionString, sessionFlags, connObject); - if (sessionoption != null) + if (sessionoption is not null) { if (sessionoption.OperationTimeout > 0) { @@ -850,13 +850,13 @@ internal IWSManSession CreateSessionObject(IWSManEx wsmanObject, AuthenticationM internal void CleanUp() { - if (_sr != null) + if (_sr is not null) { _sr.Dispose(); _sr = null; } - if (_fs != null) + if (_fs is not null) { _fs.Dispose(); _fs = null; @@ -868,7 +868,7 @@ internal string GetFilterString(Hashtable seletorset) StringBuilder filter = new StringBuilder(); foreach (DictionaryEntry entry in seletorset) { - if (entry.Key != null && entry.Value != null) + if (entry.Key is not null && entry.Value is not null) { filter.Append(entry.Key.ToString()); filter.Append("="); @@ -889,7 +889,7 @@ internal void AssertError(string ErrorMessage, bool IsWSManError, object targeto ErrorDoc.LoadXml(ErrorMessage); InvalidOperationException ex = new InvalidOperationException(ErrorDoc.OuterXml); ErrorRecord er = new ErrorRecord(ex, "WsManError", ErrorCategory.InvalidOperation, targetobject); - if (cmdletname != null) + if (cmdletname is not null) { cmdletname.ThrowTerminatingError(er); } @@ -902,7 +902,7 @@ internal void AssertError(string ErrorMessage, bool IsWSManError, object targeto { InvalidOperationException ex = new InvalidOperationException(ErrorMessage); ErrorRecord er = new ErrorRecord(ex, "WsManError", ErrorCategory.InvalidOperation, targetobject); - if (cmdletname != null) + if (cmdletname is not null) { cmdletname.ThrowTerminatingError(er); } @@ -950,7 +950,7 @@ internal void CreateWsManConnection(string ParameterSetName, Uri connectionuri, try { string connectionStr = CreateConnectionString(connectionuri, port, computername, applicationname); - if (connectionuri != null) + if (connectionuri is not null) { // in the format http(s)://server[:port/applicationname] string[] constrsplit = connectionStr.Split(":" + port + "/" + applicationname, StringSplitOptions.None); @@ -1016,7 +1016,7 @@ internal bool ValidateCredSSPRegistry(bool AllowFreshCredentialsValueShouldBePre RegistryKeyPermissionCheck.ReadWriteSubTree, System.Security.AccessControl.RegistryRights.FullControl); - if (rGPOLocalMachineKey != null) + if (rGPOLocalMachineKey is not null) { rGPOLocalMachineKey = rGPOLocalMachineKey.OpenSubKey( Key_Allow_Fresh_Credentials, @@ -1038,7 +1038,7 @@ internal bool ValidateCredSSPRegistry(bool AllowFreshCredentialsValueShouldBePre { object keyvalue = rGPOLocalMachineKey.GetValue(value); - if (keyvalue != null && keyvalue.ToString().StartsWith(applicationname, StringComparison.OrdinalIgnoreCase)) + if (keyvalue is not null && keyvalue.ToString().StartsWith(applicationname, StringComparison.OrdinalIgnoreCase)) { if (!AllowFreshCredentialsValueShouldBePresent) { diff --git a/src/ResGen/Program.cs b/src/ResGen/Program.cs index 3359226a99e..bf28b94d177 100644 --- a/src/ResGen/Program.cs +++ b/src/ResGen/Program.cs @@ -90,7 +90,7 @@ private static string GetStronglyTypeCsFileForResx(string xmlPath, string module } string bodyCode = string.Format(BODY, shortClassName, moduleName, entries.ToString(), className, accessModifier, accessModifier.Equals("public", StringComparison.InvariantCultureIgnoreCase) ? "public." : string.Empty); - if (namespaceName != null) + if (namespaceName is not null) { bodyCode = string.Format(NAMESPACE, namespaceName, bodyCode); } diff --git a/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs b/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs index b05696531fe..2452750b892 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs @@ -40,7 +40,7 @@ internal static PowerShellAssemblyLoadContext InitializeSingleton(string basePat { lock (s_syncObj) { - if (Instance != null) + if (Instance is not null) { throw new InvalidOperationException(SingletonAlreadyInitialized); } @@ -315,7 +315,7 @@ private Assembly Resolve(AssemblyLoadContext loadContext, AssemblyName assemblyN asmLoaded = asmFilePath.EndsWith(".ni.dll", StringComparison.OrdinalIgnoreCase) ? loadContext.LoadFromNativeImagePath(asmFilePath, null) : loadContext.LoadFromAssemblyPath(asmFilePath); - if (asmLoaded != null) + if (asmLoaded is not null) { // Add the loaded assembly to the cache s_assemblyCache.TryAdd(assemblyName.Name, asmLoaded); @@ -464,7 +464,7 @@ private bool IsAssemblyMatching(AssemblyName requestedAssembly, AssemblyName loa // // Version of the requested assembly should be the same or before the version of loaded assembly - if (requestedAssembly.Version != null && requestedAssembly.Version.CompareTo(loadedAssembly.Version) > 0) + if (requestedAssembly.Version is not null && requestedAssembly.Version.CompareTo(loadedAssembly.Version) > 0) { return false; } @@ -480,7 +480,7 @@ private bool IsAssemblyMatching(AssemblyName requestedAssembly, AssemblyName loa byte[] requestedPublicKeyToken = requestedAssembly.GetPublicKeyToken(); byte[] loadedPublicKeyToken = loadedAssembly.GetPublicKeyToken(); - if (requestedPublicKeyToken != null && requestedPublicKeyToken.Length > 0) + if (requestedPublicKeyToken is not null && requestedPublicKeyToken.Length > 0) { if (loadedPublicKeyToken is null || requestedPublicKeyToken.Length != loadedPublicKeyToken.Length) return false; diff --git a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs index 868c00addd4..9b844fbe359 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs @@ -77,10 +77,10 @@ public static bool IsNanoServer _isNanoServer = false; using (RegistryKey regKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Server\ServerLevels")) { - if (regKey != null) + if (regKey is not null) { object value = regKey.GetValue("NanoServer"); - if (value != null && regKey.GetValueKind("NanoServer") == RegistryValueKind.DWord) + if (value is not null && regKey.GetValueKind("NanoServer") == RegistryValueKind.DWord) { _isNanoServer = (int)value == 1; } @@ -107,10 +107,10 @@ public static bool IsIoT _isIoT = false; using (RegistryKey regKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion")) { - if (regKey != null) + if (regKey is not null) { object value = regKey.GetValue("ProductName"); - if (value != null && regKey.GetValueKind("ProductName") == RegistryValueKind.String) + if (value is not null && regKey.GetValueKind("ProductName") == RegistryValueKind.String) { _isIoT = string.Equals("IoTUAP", (string)value, StringComparison.OrdinalIgnoreCase); } @@ -210,7 +210,7 @@ internal static void RemoveTemporaryDirectory() /// internal static string GetTemporaryDirectory() { - if (_tempDirectory != null) + if (_tempDirectory is not null) { return _tempDirectory; } diff --git a/src/System.Management.Automation/DscSupport/CimDSCParser.cs b/src/System.Management.Automation/DscSupport/CimDSCParser.cs index 9a984d6dba7..09a45da31da 100644 --- a/src/System.Management.Automation/DscSupport/CimDSCParser.cs +++ b/src/System.Management.Automation/DscSupport/CimDSCParser.cs @@ -55,7 +55,7 @@ public static object ConvertCimInstanceToObject(Type targetType, CimInstance ins else { Exception innerException = null; - if (powerShell.Streams.Error != null && powerShell.Streams.Error.Count > 0) + if (powerShell.Streams.Error is not null && powerShell.Streams.Error.Count > 0) { innerException = powerShell.Streams.Error[0].Exception; } @@ -68,7 +68,7 @@ public static object ConvertCimInstanceToObject(Type targetType, CimInstance ins foreach (var property in instance.CimInstanceProperties) { - if (property.Value != null) + if (property.Value is not null) { MemberInfo[] memberInfo = targetType.GetMember(property.Name, BindingFlags.Public | BindingFlags.Instance); @@ -91,9 +91,9 @@ public static object ConvertCimInstanceToObject(Type targetType, CimInstance ins case CimType.Instance: { var cimPropertyInstance = property.Value as CimInstance; - if (cimPropertyInstance != null && - cimPropertyInstance.CimClass != null && - cimPropertyInstance.CimClass.CimSystemProperties != null && + if (cimPropertyInstance is not null && + cimPropertyInstance.CimClass is not null && + cimPropertyInstance.CimClass.CimSystemProperties is not null && string.Equals( cimPropertyInstance.CimClass.CimSystemProperties.ClassName, "MSFT_Credential", StringComparison.OrdinalIgnoreCase)) @@ -430,7 +430,7 @@ internal List ParseSchemaMof(string filePath) { string superClassName = c.CimSuperClassName; string className = c.CimSystemProperties.ClassName; - if ((superClassName != null) && (superClassName.Equals("OMI_BaseResource", StringComparison.OrdinalIgnoreCase))) + if ((superClassName is not null) && (superClassName.Equals("OMI_BaseResource", StringComparison.OrdinalIgnoreCase))) { // Get the name of the file without schema.mof extension if (!(className.Equals(fileNameDefiningClass, StringComparison.OrdinalIgnoreCase))) @@ -744,7 +744,7 @@ public static void Initialize(Collection errors, List moduleP } var programFilesDirectory = Platform.GetFolderPath(Environment.SpecialFolder.ProgramFiles); - Debug.Assert(programFilesDirectory != null, "Program Files environment variable does not exist!"); + Debug.Assert(programFilesDirectory is not null, "Program Files environment variable does not exist!"); var customResourceRoot = Path.Combine(programFilesDirectory, "WindowsPowerShell\\Configuration"); Debug.Assert(Directory.Exists(customResourceRoot), "%ProgramFiles%\\WindowsPowerShell\\Configuration Directory does not exist"); var allResourceRoots = new string[] { systemResourceRoot, customResourceRoot }; @@ -894,7 +894,7 @@ private static Tuple GetModuleInfoHelper(string moduleFolderPat PsUtils.ManifestModuleVersionPropertyName); object versionValue = dataFileSetting["ModuleVersion"]; - if (versionValue != null) + if (versionValue is not null) { Version moduleVersion; if (LanguagePrimitives.TryConvertTo(versionValue, out moduleVersion)) @@ -968,13 +968,13 @@ public static List ImportClasses(string path, Tuple m { // Ignore modules with invalid schemas. s_tracer.WriteLine("DSC ClassCache: Error importing file '{0}', with error '{1}'. Skipping file.", path, e); - if (errors != null) + if (errors is not null) { errors.Add(e); } } - if (classes != null) + if (classes is not null) { foreach (var c in classes) { @@ -998,7 +998,7 @@ public static List ImportClasses(string path, Tuple m ParserStrings.DuplicateCimClassDefinition, className, path, files); e.SetErrorId("DuplicateCimClassDefinition"); - if (errors != null) + if (errors is not null) { errors.Add(e); } @@ -1057,7 +1057,7 @@ public static string GetStringFromSecureString(SecureString value) { string passwordValueToAdd = string.Empty; - if (value != null) + if (value is not null) { IntPtr ptr = Marshal.SecureStringToCoTaskMemUnicode(value); passwordValueToAdd = Marshal.PtrToStringUni(ptr); @@ -1153,7 +1153,7 @@ public static List GetFileDefiningClass(string className) { var file = pair.Key; var classList = pair.Value; - if (classList != null && classList.Find((CimClass c) => string.Equals(c.CimSystemProperties.ClassName, className, StringComparison.OrdinalIgnoreCase)) != null) + if (classList is not null && classList.Find((CimClass c) => string.Equals(c.CimSystemProperties.ClassName, className, StringComparison.OrdinalIgnoreCase)) is not null) { files.Add(file); } @@ -1277,7 +1277,7 @@ private static string GetFriendlyName(CimClass cimClass) try { var aliasQualifier = cimClass.CimClassQualifiers["FriendlyName"]; - if (aliasQualifier != null) + if (aliasQualifier is not null) { return aliasQualifier.Value as string; } @@ -1304,7 +1304,7 @@ public static Collection GetCachedKeywords() string moduleVersion = splittedName[IndexModuleVersion]; var keyword = CreateKeywordFromCimClass(moduleName, Version.Parse(moduleVersion), cachedClass.Value.CimClassInstance, null, cachedClass.Value.DscResRunAsCred); - if (keyword != null) + if (keyword is not null) { keywords.Add(keyword); } @@ -1345,7 +1345,7 @@ private static void CreateAndRegisterKeywordFromCimClass(string moduleName, Vers DynamicKeyword.AddKeyword(keyword); // And now define the driver functions in the current scope... - if (functionsToDefine != null) + if (functionsToDefine is not null) { functionsToDefine[moduleName + "\\" + keyword.Keyword] = CimKeywordImplementationFunction; } @@ -1417,7 +1417,7 @@ private static DynamicKeyword CreateKeywordFromCimClass(string moduleName, Versi try { // If the property has the Read qualifier, also skip it. - if (prop.Qualifiers["Read"] != null) + if (prop.Qualifiers["Read"] is not null) { continue; } @@ -1507,7 +1507,7 @@ private static DynamicKeyword CreateKeywordFromCimClass(string moduleName, Versi } } - if (valueMap != null && keyProp.Values.Count > 0) + if (valueMap is not null && keyProp.Values.Count > 0) { if (valueMap.Length != keyProp.Values.Count) { @@ -1559,17 +1559,17 @@ private static void UpdateKnownRestriction(DynamicKeyword keyword) string.Equals(keyword.ResourceName, "MSFT_DSCMetaConfiguration", StringComparison.OrdinalIgnoreCase)) { - if (keyword.Properties["RefreshFrequencyMins"] != null) + if (keyword.Properties["RefreshFrequencyMins"] is not null) { keyword.Properties["RefreshFrequencyMins"].Range = new Tuple(30, 44640); } - if (keyword.Properties["ConfigurationModeFrequencyMins"] != null) + if (keyword.Properties["ConfigurationModeFrequencyMins"] is not null) { keyword.Properties["ConfigurationModeFrequencyMins"].Range = new Tuple(15, 44640); } - if (keyword.Properties["DebugMode"] != null) + if (keyword.Properties["DebugMode"] is not null) { keyword.Properties["DebugMode"].Values.Remove("ResourceScriptBreakAll"); keyword.Properties["DebugMode"].ValueMap.Remove("ResourceScriptBreakAll"); @@ -1754,13 +1754,13 @@ 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 is not null && moduleNameBindingResult is 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 // we do not want to do this twice. since we are giving same error ImportDscResourceNeedParams in both cases // once we have different error messages for 2 scenarios we can remove this check - if (resourceNameBindingResult != null) + if (resourceNameBindingResult is not null) { errorList.Add(new ParseError(kwAst.Extent, "ImportDscResourceNeedModuleNameWithModuleVersion", @@ -1769,7 +1769,7 @@ private static ParseError[] ImportResourcePostParse(DynamicKeywordStatementAst k } string[] resourceNames = null; - if (resourceNameBindingResult != null) + if (resourceNameBindingResult is not null) { object resourceName = null; if (!IsConstantValueVisitor.IsConstant(resourceNameBindingResult.Value, out resourceName, true, true) || @@ -1782,7 +1782,7 @@ private static ParseError[] ImportResourcePostParse(DynamicKeywordStatementAst k } System.Version moduleVersion = null; - if (moduleVersionBindingResult != null) + if (moduleVersionBindingResult is not null) { object moduleVer = null; if (!IsConstantValueVisitor.IsConstant(moduleVersionBindingResult.Value, out moduleVer, true, true)) @@ -1809,7 +1809,7 @@ private static ParseError[] ImportResourcePostParse(DynamicKeywordStatementAst k } ModuleSpecification[] moduleSpecifications = null; - if (moduleNameBindingResult != null) + if (moduleNameBindingResult is not null) { object moduleName = null; if (!IsConstantValueVisitor.IsConstant(moduleNameBindingResult.Value, out moduleName, true, true)) @@ -1822,7 +1822,7 @@ private static ParseError[] ImportResourcePostParse(DynamicKeywordStatementAst k if (LanguagePrimitives.TryConvertTo(moduleName, out moduleSpecifications)) { // if resourceNames are specified then we can not specify multiple modules name - if (moduleSpecifications != null && moduleSpecifications.Length > 1 && resourceNames != null) + if (moduleSpecifications is not null && moduleSpecifications.Length > 1 && resourceNames is not null) { errorList.Add(new ParseError(moduleNameBindingResult.Value.Extent, "ImportDscResourceMultipleModulesNotSupportedWithName", @@ -1830,7 +1830,7 @@ private static ParseError[] ImportResourcePostParse(DynamicKeywordStatementAst k } // if moduleversion is specified then we can not specify multiple modules name - if (moduleSpecifications != null && moduleSpecifications.Length > 1 && moduleVersion != null) + if (moduleSpecifications is not null && moduleSpecifications.Length > 1 && moduleVersion is not null) { errorList.Add(new ParseError(moduleNameBindingResult.Value.Extent, "ImportDscResourceMultipleModulesNotSupportedWithVersion", @@ -1838,7 +1838,7 @@ private static ParseError[] ImportResourcePostParse(DynamicKeywordStatementAst k } // if moduleversion is specified then we can not specify another version in modulespecification object of ModuleName - if (moduleSpecifications != null && (moduleSpecifications[0].Version != null || moduleSpecifications[0].MaximumVersion != null) && moduleVersion != null) + if (moduleSpecifications is not null && (moduleSpecifications[0].Version is not null || moduleSpecifications[0].MaximumVersion is not null) && moduleVersion is not null) { errorList.Add(new ParseError(moduleNameBindingResult.Value.Extent, "ImportDscResourceMultipleModuleVersionsNotSupported", @@ -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 is not null && moduleSpecifications[0].Version is null && moduleSpecifications[0].MaximumVersion is null && moduleVersion is not null) { moduleSpecifications[0].Version = moduleVersion; } @@ -1875,7 +1875,7 @@ private static ParseError[] ImportResourceCheckSemantics(DynamicKeywordStatement List errorList = null; var keywordAst = Ast.GetAncestorAst(kwAst.Parent); - while (keywordAst != null) + while (keywordAst is not null) { if (keywordAst.Keyword.Keyword.Equals("Node")) { @@ -1893,7 +1893,7 @@ private static ParseError[] ImportResourceCheckSemantics(DynamicKeywordStatement keywordAst = Ast.GetAncestorAst(keywordAst.Parent); } - if (errorList != null) + if (errorList is not null) { return errorList.ToArray(); } @@ -1922,7 +1922,7 @@ private static ParseError[] CheckMandatoryPropertiesPresent(DynamicKeywordStatem foreach (var ast in kwAst.CommandElements) { hashtableAst = ast as HashtableAst; - if (hashtableAst != null) + if (hashtableAst is not null) { break; } @@ -1940,7 +1940,7 @@ private static ParseError[] CheckMandatoryPropertiesPresent(DynamicKeywordStatem if (IsConstantValueVisitor.IsConstant(pair.Item1, out evalResultObject, forAttribute: false, forRequires: false)) { var presentName = evalResultObject as string; - if (presentName != null) + if (presentName is not null) { if (mandatoryPropertiesNames.Remove(presentName) && mandatoryPropertiesNames.Count == 0) { @@ -1985,19 +1985,19 @@ public static void LoadResourcesFromModule(IScriptExtent scriptExtent, { // get all required modules var modules = new Collection(); - if (moduleSpecifications != null) + if (moduleSpecifications is not null) { foreach (var moduleToImport in moduleSpecifications) { bool foundModule = false; var moduleInfos = ModuleCmdletBase.GetModuleIfAvailable(moduleToImport); - if (moduleInfos.Count >= 1 && (moduleToImport.Version != null || moduleToImport.Guid != null)) + if (moduleInfos.Count >= 1 && (moduleToImport.Version is not null || moduleToImport.Guid is not null)) { foreach (var psModuleInfo in moduleInfos) { if ((moduleToImport.Guid.HasValue && moduleToImport.Guid.Equals(psModuleInfo.Guid)) || - (moduleToImport.Version != null && + (moduleToImport.Version is not null && moduleToImport.Version.Equals(psModuleInfo.Version))) { modules.Add(psModuleInfo); @@ -2036,7 +2036,7 @@ public static void LoadResourcesFromModule(IScriptExtent scriptExtent, } } } - else if (resourceNames != null) + else if (resourceNames is not null) { // Lookup the required resources under available PowerShell modules when modulename is not specified using (var powerShell = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace)) @@ -2197,13 +2197,13 @@ private static void LoadPowerShellClassResourcesFromModule(PSModuleInfo primaryM { AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += reh; var assembly = moduleInfo.ImplementingAssembly; - if (assembly is null && moduleInfo.Path != null) + if (assembly is null && moduleInfo.Path is not null) { try { var path = moduleInfo.Path; - if (moduleInfo.RootModule != null && !Path.GetExtension(moduleInfo.Path).Equals(".dll", StringComparison.OrdinalIgnoreCase)) + if (moduleInfo.RootModule is not null && !Path.GetExtension(moduleInfo.Path).Equals(".dll", StringComparison.OrdinalIgnoreCase)) { path = moduleInfo.ModuleBase + "\\" + moduleInfo.RootModule; } @@ -2214,7 +2214,7 @@ private static void LoadPowerShellClassResourcesFromModule(PSModuleInfo primaryM } // Ignore the module if we can't find the assembly. - if (assembly != null) + if (assembly is not null) { ImportKeywordsFromAssembly(moduleInfo, resourcesToImport, resourcesFound, functionsToDefine, assembly); } @@ -2229,11 +2229,11 @@ private static void LoadPowerShellClassResourcesFromModule(PSModuleInfo primaryM { string scriptPath = null; // handle RootModule and nestedModule together - if (moduleInfo.RootModule != null) + if (moduleInfo.RootModule is not null) { scriptPath = Path.Combine(moduleInfo.ModuleBase, moduleInfo.RootModule); } - else if (moduleInfo.Path != null) + else if (moduleInfo.Path is not null) { scriptPath = moduleInfo.Path; } @@ -2241,7 +2241,7 @@ private static void LoadPowerShellClassResourcesFromModule(PSModuleInfo primaryM ImportKeywordsFromScriptFile(scriptPath, primaryModuleInfo, resourcesToImport, resourcesFound, functionsToDefine, errorList, extent); } - if (moduleInfo.NestedModules != null && recurse) + if (moduleInfo.NestedModules is not null && recurse) { foreach (var nestedModule in moduleInfo.NestedModules) { @@ -2255,7 +2255,7 @@ private static Assembly CurrentDomain_ReflectionOnlyAssemblyResolve(object sende { AssemblyName name = new AssemblyName(args.Name); - if (moduleInfo != null && !string.IsNullOrEmpty(moduleInfo.Path)) + if (moduleInfo is not null && !string.IsNullOrEmpty(moduleInfo.Path)) { string asmToCheck = Path.GetDirectoryName(moduleInfo.Path) + "\\" + name.Name + ".dll"; if (File.Exists(asmToCheck)) @@ -2304,7 +2304,7 @@ internal static string MapTypeNameToMofType(ITypeName typeName, string memberNam { TypeName propTypeName; var arrayTypeName = typeName as ArrayTypeName; - if (arrayTypeName != null) + if (arrayTypeName is not null) { isArrayType = true; propTypeName = arrayTypeName.ElementType as TypeName; @@ -2369,13 +2369,13 @@ private static void GenerateMofForAst(TypeDefinitionAst typeAst, StringBuilder s var b = bases.Dequeue(); var tc = b as TypeConstraintAst; - if (tc != null) + if (tc is not null) { b = tc.TypeName.GetReflectionType(); if (b is null) { var td = tc.TypeName as TypeName; - if (td != null && td._typeDefinitionAst != null) + if (td is not null && td._typeDefinitionAst is not null) { ProcessMembers(sb, embeddedInstanceTypes, td._typeDefinitionAst, className); foreach (var b1 in td._typeDefinitionAst.BaseTypes) @@ -2389,11 +2389,11 @@ private static void GenerateMofForAst(TypeDefinitionAst typeAst, StringBuilder s } var type = b as Type; - if (type != null) + if (type is not null) { ProcessMembers(type, sb, embeddedInstanceTypes, className); var t = type.BaseType; - if (t != null) + if (t is not null) { bases.Enqueue(t); } @@ -2418,7 +2418,7 @@ private static bool GetResourceMethodsLineNumber(TypeDefinitionAst typeDefinitio foreach (var member in typeDefinitionAst.Members) { var functionMemberAst = member as FunctionMemberAst; - if (functionMemberAst != null) + if (functionMemberAst is not null) { if (functionMemberAst.Name.Equals(getMethodName, StringComparison.OrdinalIgnoreCase)) { @@ -2457,12 +2457,12 @@ public static bool GetResourceMethodsLinePosition(PSModuleInfo moduleInfo, strin IEnumerable resourceDefinitions; List moduleFiles = new List(); - if (moduleInfo.RootModule != null) + if (moduleInfo.RootModule is not null) { moduleFiles.Add(moduleInfo.Path); } - if (moduleInfo.NestedModules != null) + if (moduleInfo.NestedModules is not null) { foreach (var nestedModule in moduleInfo.NestedModules.Where(m => !string.IsNullOrEmpty(m.Path))) { @@ -2521,7 +2521,7 @@ private static void ProcessMembers(StringBuilder sb, List embeddedInstan string embeddedInstanceType; string[] enumNames = null; - if (memberType != null) + if (memberType is not null) { // TODO - validate type and name mofType = MapTypeToMofType(memberType, member.Name, className, out isArrayType, @@ -2586,9 +2586,9 @@ private static bool GetResourceDefinitionsFromModule(string fileName, out IEnume ParseError[] errors; var ast = Parser.ParseFile(fileName, out tokens, out errors); - if (errors != null && errors.Length > 0) + if (errors is not null && errors.Length > 0) { - if (errorList != null && extent != null) + if (errorList is not null && extent is not null) { List errorMessages = new List(); foreach (var error in errors) @@ -2606,7 +2606,7 @@ private static bool GetResourceDefinitionsFromModule(string fileName, out IEnume resourceDefinitions = ast.FindAll(n => { var typeAst = n as TypeDefinitionAst; - if (typeAst != null) + if (typeAst is not null) { for (int i = 0; i < typeAst.Attributes.Count; i++) { @@ -2678,7 +2678,7 @@ private static bool ImportKeywordsFromScriptFile(string fileName, PSModuleInfo m if (na.ArgumentName.Equals("RunAsCredential", StringComparison.OrdinalIgnoreCase)) { var dscResourceAttribute = attr.GetAttribute() as DscResourceAttribute; - if (dscResourceAttribute != null) + if (dscResourceAttribute is not null) { runAsBehavior = dscResourceAttribute.RunAsCredential; } @@ -2736,9 +2736,9 @@ private static bool AreQualifiersSame(CimReadOnlyKeyedCollection o return false; } - if ((qual.Value is null && newQual.Value != null) || - (qual.Value != null && newQual.Value is null) || - (qual.Value != null && newQual.Value != null && + if ((qual.Value is null && newQual.Value is not null) || + (qual.Value is not null && newQual.Value is null) || + (qual.Value is not null && newQual.Value is not null && !string.Equals(qual.Value.ToString(), newQual.Value.ToString(), StringComparison.OrdinalIgnoreCase) ) ) @@ -2784,8 +2784,8 @@ private static bool ArePropertiesSame(CimReadOnlyKeyedCollection foreach (var attr in customAttributes) { var dscProperty = attr as DscPropertyAttribute; - if (dscProperty != null) + if (dscProperty is not null) { if (dscProperty.Key) { @@ -2940,7 +2940,7 @@ private static string MapAttributesToMof(string[] enumNames, IEnumerable } var validateSet = attr as ValidateSetAttribute; - if (validateSet != null) + if (validateSet is not null) { bool valueMapComma = false; StringBuilder sbValues = new StringBuilder(", Values{"); @@ -2967,7 +2967,7 @@ private static string MapAttributesToMof(string[] enumNames, IEnumerable needComma = true; } - if (enumNames != null) + if (enumNames is not null) { sb.AppendFormat(CultureInfo.InvariantCulture, "{0}ValueMap{{", needComma ? ", " : string.Empty); needComma = false; @@ -2987,7 +2987,7 @@ private static string MapAttributesToMof(string[] enumNames, IEnumerable sb.Append("}"); } - else if (embeddedInstanceType != null) + else if (embeddedInstanceType is not null) { sb.AppendFormat(CultureInfo.InvariantCulture, "{0}EmbeddedInstance(\"{1}\")", needComma ? ", " : string.Empty, embeddedInstanceType); } @@ -3035,7 +3035,7 @@ private static void ProcessEmbeddedInstanceTypes(List embeddedInstanceTy { visitedInstances.Add(batchedTypes[i]); var type = batchedTypes[i] as Type; - if (type != null) + if (type is not null) { GenerateMofForType(type, nestedSb, embeddedInstanceTypes); } @@ -3239,7 +3239,7 @@ public static bool ImportCimKeywordsFromModule(PSModuleInfo module, string resou // configuration statement so within a single compile, things shouldn't // change. var classes = GetCachedClassByFileName(schemaFilePath) ?? ImportClasses(schemaFilePath, new Tuple(module.Name, module.Version), errors); - if (classes != null) + if (classes is not null) { foreach (var c in classes) { @@ -3267,7 +3267,7 @@ public static bool ImportCimKeywordsFromModule(PSModuleInfo module, string resou Debug.Assert(schemaFiles.Length == 1, "A valid DSCResource module can have only one schema mof file"); var tempSchemaFilepath = schemaFiles[0]; var classes = GetCachedClassByFileName(tempSchemaFilepath) ?? ImportClasses(tempSchemaFilepath, new Tuple(module.Name, module.Version), errors); - if (classes != null) + if (classes is not null) { // // search if class's friendly name is the given resourceName @@ -3683,7 +3683,7 @@ private static StringBuilder FormatCimPropertyType(DynamicKeywordProperty prop, } // Do the property values map - if (prop.ValueMap != null && prop.ValueMap.Count > 0) + if (prop.ValueMap is not null && prop.ValueMap.Count > 0) { formattedTypeString.Append(" { " + string.Join(" | ", prop.ValueMap.Keys.OrderBy(x => x)) + " }"); } diff --git a/src/System.Management.Automation/FormatAndOutput/common/BaseCommand.cs b/src/System.Management.Automation/FormatAndOutput/common/BaseCommand.cs index a653a666e01..1ef8e3a30c5 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/BaseCommand.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/BaseCommand.cs @@ -160,7 +160,7 @@ public abstract class FrontEndCommandBase : PSCmdlet, IDisposable /// protected override void BeginProcessing() { - Diagnostics.Assert(this.implementation != null, "this.implementation is null"); + Diagnostics.Assert(this.implementation is not null, "this.implementation is null"); this.implementation.OuterCmdletCall = new ImplementationCommandBase.OuterCmdletCallback(this.OuterCmdletCall); this.implementation.InputObjectCall = new ImplementationCommandBase.InputObjectCallback(this.InputObjectCall); this.implementation.WriteObjectCall = new ImplementationCommandBase.WriteObjectCallback(this.WriteObjectCall); @@ -308,7 +308,7 @@ internal virtual void StopProcessing() internal virtual PSObject ReadObject() { // delegate to the front end object - System.Diagnostics.Debug.Assert(this.InputObjectCall != null, "this.InputObjectCall is null"); + System.Diagnostics.Debug.Assert(this.InputObjectCall is not null, "this.InputObjectCall is null"); return this.InputObjectCall(); } @@ -319,7 +319,7 @@ internal virtual PSObject ReadObject() internal virtual void WriteObject(object o) { // delegate to the front end object - System.Diagnostics.Debug.Assert(this.WriteObjectCall != null, "this.WriteObjectCall is null"); + System.Diagnostics.Debug.Assert(this.WriteObjectCall is not null, "this.WriteObjectCall is null"); this.WriteObjectCall(o); } @@ -331,7 +331,7 @@ internal virtual void WriteObject(object o) internal virtual PSCmdlet OuterCmdlet() { // delegate to the front end object - System.Diagnostics.Debug.Assert(this.OuterCmdletCall != null, "this.OuterCmdletCall is null"); + System.Diagnostics.Debug.Assert(this.OuterCmdletCall is not null, "this.OuterCmdletCall is null"); return this.OuterCmdletCall(); } diff --git a/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommand.cs b/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommand.cs index c2169059821..c07233d5520 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommand.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommand.cs @@ -57,7 +57,7 @@ internal static int FormatEnumerationLimit() try { // Win8: 192504 - if (LocalPipeline.GetExecutionContextFromTLS() != null) + if (LocalPipeline.GetExecutionContextFromTLS() is not null) { enumLimitVal = LocalPipeline.GetExecutionContextFromTLS() .SessionState.PSVariable @@ -145,7 +145,7 @@ internal override void ProcessRecord() private EnumerableExpansion GetExpansionState(PSObject so) { // if the command line swtich has been specified, use this as an override - if (_parameters != null && _parameters.expansion.HasValue) + if (_parameters is not null && _parameters.expansion.HasValue) { return _parameters.expansion.Value; } @@ -194,7 +194,7 @@ private void ProcessCoreOutOfBand(PSObject so, int count) private void SendCommentOutOfBand(string msg) { FormatEntryData fed = OutOfBandFormatViewManager.GenerateOutOfBandObjectAsToString(PSObjectHelper.AsPSObject(msg)); - if (fed != null) + if (fed is not null) { this.WriteObject(fed); } @@ -323,7 +323,7 @@ private bool ProcessOutOfBandObjectOutsideDocumentSequence(PSObject so) _typeInfoDataBase, so, _enumerationLimit, false, out errors); WriteErrorRecords(errors); - if (fed != null) + if (fed is not null) { this.WriteObject(fed); return true; @@ -356,7 +356,7 @@ private bool ProcessOutOfBand(PSObject so, bool isProcessingError) if (!isProcessingError) WriteErrorRecords(errors); - if (fed != null) + if (fed is not null) { this.WriteObject(fed); return true; @@ -433,7 +433,7 @@ internal override void EndProcessing() internal void SetCommandLineParameters(FormattingCommandLineParameters commandLineParameters) { - Diagnostics.Assert(commandLineParameters != null, "the caller has to pass a valid instance"); + Diagnostics.Assert(commandLineParameters is not null, "the caller has to pass a valid instance"); _parameters = commandLineParameters; } @@ -481,7 +481,7 @@ private void WriteFormatStartData(PSObject so) /// Object to process. private void WritePayloadObject(PSObject so) { - Diagnostics.Assert(so != null, "object so cannot be null"); + Diagnostics.Assert(so is not null, "object so cannot be null"); FormatEntryData fed = _viewManager.ViewGenerator.GeneratePayload(so, _enumerationLimit); fed.writeStream = so.WriteStream; this.WriteObject(fed); @@ -649,7 +649,7 @@ public SwitchParameter Force internal MshParameter ProcessGroupByParameter() { - if (GroupBy != null) + if (GroupBy is not null) { TerminatingErrorContext invocationContext = new TerminatingErrorContext(this); @@ -745,7 +745,7 @@ internal override FormattingCommandLineParameters GetCommandLineParameters() internal void GetCommandLineProperties(FormattingCommandLineParameters parameters, bool isTable) { - if (Property != null) + if (Property is not null) { CommandParameterDefinition def; diff --git a/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommandParameters.cs b/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommandParameters.cs index 79375b70ef9..7277143b981 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommandParameters.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommandParameters.cs @@ -155,10 +155,10 @@ internal override Hashtable CreateHashtableFromSingleType (object val) string nameVal = UnpackString (s, out width, out align); hash.Add (FormatParameterDefinitionKeys.NameEntryKey, nameVal); - if (width != null) + if (width is not null) hash.Add (FormatParameterDefinitionKeys.WidthEntryKey, width); - if (align != null) + if (align is not null) hash.Add (FormatParameterDefinitionKeys.AlignmentEntryKey, align); return hash; @@ -177,14 +177,14 @@ internal override object Verify(object val, // need to check the type: // it can be a string or a script block ScriptBlock sb = val as ScriptBlock; - if (sb != null) + if (sb is not null) { PSPropertyExpression ex = new PSPropertyExpression(sb); return ex; } string s = val as string; - if (s != null) + if (s is not null) { if (string.IsNullOrEmpty(s)) { diff --git a/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs b/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs index 2b3716eb7a3..77657442247 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs @@ -56,7 +56,7 @@ internal override void ProcessRecord() // send to the formatter for preprocessing Array results = ApplyFormatting(so); - if (results != null) + if (results is not null) { foreach (object r in results) { @@ -72,12 +72,12 @@ internal override void ProcessRecord() internal override void EndProcessing() { base.EndProcessing(); - if (_command != null) + if (_command is not null) { // shut down the command processor, if we ever used it Array results = _command.ShutDown(); - if (results != null) + if (results is not null) { foreach (object o in results) { @@ -103,12 +103,12 @@ internal override void EndProcessing() private void DrainCache() { - if (_cache != null) + if (_cache is not null) { // drain the cache, since we are shutting down List unprocessedObjects = _cache.Drain(); - if (unprocessedObjects != null) + if (unprocessedObjects is not null) { foreach (object obj in unprocessedObjects) { @@ -137,11 +137,11 @@ private bool ProcessObject(PSObject so) // no need for formatting, just process the object FormatStartData formatStart = o as FormatStartData; - if (formatStart != null) + if (formatStart is not null) { // get autosize flag from object // turn on group caching - if (formatStart.autosizeInfo != null) + if (formatStart.autosizeInfo is not null) { FormattedObjectsCache.ProcessCachedGroupNotification callBack = new FormattedObjectsCache.ProcessCachedGroupNotification(ProcessCachedGroup); _cache.EnableGroupCaching(callBack, formatStart.autosizeInfo.objectCount); @@ -150,7 +150,7 @@ private bool ProcessObject(PSObject so) { // If the format info doesn't define column widths, then auto-size based on the first ten elements TableHeaderInfo headerInfo = formatStart.shapeInfo as TableHeaderInfo; - if ((headerInfo != null) && + if ((headerInfo is not null) && (headerInfo.tableColumnInfoList.Count > 0) && (headerInfo.tableColumnInfoList[0].width == 0)) { @@ -163,7 +163,7 @@ private bool ProcessObject(PSObject so) // Console.WriteLine("OutCommandInner.Execute() calling ctxManager.Process({0})",o.ToString()); List info = _cache.Add((PacketInfoData)o); - if (info != null) + if (info is not null) { for (int k = 0; k < info.Count; k++) _ctxManager.Process(info[k]); @@ -206,7 +206,7 @@ private FormatShape ActiveFormattingShape protected override void InternalDispose() { base.InternalDispose(); - if (_command != null) + if (_command is not null) { _command.Dispose(); _command = null; @@ -263,7 +263,7 @@ private enum PreprocessingState { raw, processed, error } private bool NeedsPreprocessing(object o) { FormatEntryData fed = o as FormatEntryData; - if (fed != null) + if (fed is not null) { // we got an already pre-processed object if (!fed.outOfBand) @@ -327,7 +327,7 @@ private void ValidateCurrentFormattingState(FormattingState expectedFormattingSt string violatingCommand = "format-*"; StartData sdObj = obj as StartData; - if (sdObj != null) + if (sdObj is not null) { if (sdObj.shapeInfo is WideViewHeaderInfo) { @@ -389,7 +389,7 @@ private FormatMessagesContextManager.OutputContext CreateOutputContext( { FormatStartData formatStartData = formatInfoData as FormatStartData; // initialize the format context - if (formatStartData != null) + if (formatStartData is not null) { FormatOutputContext foc = new FormatOutputContext(parentContext, formatStartData); @@ -398,7 +398,7 @@ private FormatMessagesContextManager.OutputContext CreateOutputContext( GroupStartData gsd = formatInfoData as GroupStartData; // we are starting a group, initialize the group context - if (gsd != null) + if (gsd is not null) { GroupOutputContext goc = null; @@ -474,7 +474,7 @@ private void ProcessGroupStart(FormatMessagesContextManager.OutputContext c) // Console.WriteLine("ProcessGroupStart"); GroupOutputContext goc = (GroupOutputContext)c; - if (goc.Data.groupingEntry != null) + if (goc.Data.groupingEntry is not null) { ComplexWriter writer = new ComplexWriter(); writer.Initialize(_lo, _lo.ColumnNumber); @@ -542,7 +542,7 @@ private void ProcessOutOfBandPayload(FormatEntryData fed) { // try if it is raw text RawTextFormatEntry rte = fed.formatEntryInfo as RawTextFormatEntry; - if (rte != null) + if (rte is not null) { if (fed.isHelpObject) { @@ -561,7 +561,7 @@ private void ProcessOutOfBandPayload(FormatEntryData fed) // try if it is a complex entry ComplexViewEntry cve = fed.formatEntryInfo as ComplexViewEntry; - if (cve != null && cve.formatValueList != null) + if (cve is not null && cve.formatValueList is not null) { ComplexWriter complexWriter = new ComplexWriter(); @@ -572,7 +572,7 @@ private void ProcessOutOfBandPayload(FormatEntryData fed) } // try if it is a list view ListViewEntry lve = fed.formatEntryInfo as ListViewEntry; - if (lve != null && lve.listViewFieldList != null) + if (lve is not null && lve.listViewFieldList is not null) { ListWriter listWriter = new ListWriter(); @@ -622,11 +622,11 @@ private FormatOutputContext FormatContext { get { - for (FormatMessagesContextManager.OutputContext oc = _ctxManager.ActiveOutputContext; oc != null; oc = oc.ParentContext) + for (FormatMessagesContextManager.OutputContext oc = _ctxManager.ActiveOutputContext; oc is not null; oc = oc.ParentContext) { FormatOutputContext foc = oc as FormatOutputContext; - if (foc != null) + if (foc is not null) return foc; } @@ -653,7 +653,7 @@ private void ProcessCachedGroup(FormatStartData formatStartData, List 0) + if (hint is not null && hint.maxWidth > 0) { itemsPerRow = TableWriter.ComputeWideViewBestItemsPerRowFit(hint.maxWidth, columnsOnTheScreen); } diff --git a/src/System.Management.Automation/FormatAndOutput/common/ComplexWriter.cs b/src/System.Management.Automation/FormatAndOutput/common/ComplexWriter.cs index 10891fb400c..c18f33e15f5 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/ComplexWriter.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/ComplexWriter.cs @@ -69,11 +69,11 @@ private void GenerateFormatEntryDisplay(FormatEntry fe, int currentDepth) foreach (object obj in fe.formatValueList) { FormatEntry feChild = obj as FormatEntry; - if (feChild != null) + if (feChild is not null) { if (currentDepth < maxRecursionDepth) { - if (feChild.frameInfo != null) + if (feChild.frameInfo is not null) { // if we have frame information, we need to push it on the // indentation stack @@ -99,14 +99,14 @@ private void GenerateFormatEntryDisplay(FormatEntry fe, int currentDepth) } FormatTextField ftf = obj as FormatTextField; - if (ftf != null) + if (ftf is not null) { this.AddToBuffer(ftf.text); continue; } FormatPropertyField fpf = obj as FormatPropertyField; - if (fpf != null) + if (fpf is not null) { this.AddToBuffer(fpf.propertyValue); } @@ -237,7 +237,7 @@ internal IndentationStackFrame(IndentationManager mgr) public void Dispose() { - if (_mgr != null) + if (_mgr is not null) { _mgr.RemoveStackFrame(); } diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/FormatTable.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/FormatTable.cs index 00c8089a825..a592ab8baf3 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/FormatTable.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/FormatTable.cs @@ -119,7 +119,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont base.GetObjectData(info, context); // If there are simple fields, serialize them with info.AddValue - if (_errors != null) + if (_errors is not null) { int errorCount = _errors.Count; info.AddValue("ErrorCount", errorCount); diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs index 02d60731e43..8b68dc9552f 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs @@ -190,7 +190,7 @@ internal XmlLoaderStackFrame(XmlLoaderBase loader, XmlNode n, int index) /// public void Dispose() { - if (_loader != null) + if (_loader is not null) { _loader.RemoveStackFrame(); _loader = null; @@ -229,7 +229,7 @@ protected virtual void Dispose(bool disposing) { if (disposing) { - if (_logger != null) + if (_logger is not null) { _logger.Dispose(); _logger = null; @@ -387,7 +387,7 @@ private bool MatchNodeNameHelper(XmlNode n, string s, bool allowAttributes) if (match && !allowAttributes) { XmlElement e = n as XmlElement; - if (e != null && e.Attributes.Count > 0) + if (e is not null && e.Attributes.Count > 0) { // Error at XPath {0} in file {1}: The XML Element {2} does not allow attributes. ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.AttributesNotAllowed, ComputeCurrentXPath(), FilePath, n.Name)); @@ -626,7 +626,7 @@ protected XmlDocument LoadXmlDocumentFromFileLoadingInfo(AuthorizationManager au isFullyTrusted = true; } - if (authorizationManager != null) + if (authorizationManager is not null) { try { diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData.cs index 348aa30bba5..4e8954b6b96 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData.cs @@ -87,7 +87,7 @@ internal T Value */ get { - if (_value != null) + if (_value is not null) return this._value.Value; return _default; } @@ -767,14 +767,14 @@ internal bool IsSafeForExport() internal static PSControlGroupBy Get(GroupBy groupBy) { - if (groupBy != null) + if (groupBy is not null) { // TODO - groupBy.startGroup.control var expressionToken = groupBy.startGroup.expression; return new PSControlGroupBy { Expression = new DisplayEntry(expressionToken), - Label = (groupBy.startGroup.labelTextToken != null) ? groupBy.startGroup.labelTextToken.text : null + Label = (groupBy.startGroup.labelTextToken is not null) ? groupBy.startGroup.labelTextToken.text : null }; } @@ -851,18 +851,18 @@ public sealed class EntrySelectedBy internal static EntrySelectedBy Get(IEnumerable entrySelectedByType, IEnumerable entrySelectedByCondition) { EntrySelectedBy result = null; - if (entrySelectedByType != null || entrySelectedByCondition != null) + if (entrySelectedByType is not null || entrySelectedByCondition is not null) { result = new EntrySelectedBy(); bool isEmpty = true; - if (entrySelectedByType != null) + if (entrySelectedByType is not null) { result.TypeNames = new List(entrySelectedByType); if (result.TypeNames.Count > 0) isEmpty = false; } - if (entrySelectedByCondition != null) + if (entrySelectedByCondition is not null) { result.SelectionCondition = new List(entrySelectedByCondition); if (result.SelectionCondition.Count > 0) @@ -879,12 +879,12 @@ internal static EntrySelectedBy Get(IEnumerable entrySelectedByType, IEn internal static EntrySelectedBy Get(List references) { EntrySelectedBy result = null; - if (references != null && references.Count > 0) + if (references is not null && references.Count > 0) { result = new EntrySelectedBy(); foreach (TypeOrGroupReference tr in references) { - if (tr.conditionToken != null) + if (tr.conditionToken is not null) { if (result.SelectionCondition is null) result.SelectionCondition = new List(); 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..bf133903485 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Complex.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Complex.cs @@ -72,7 +72,7 @@ internal CustomControl() internal CustomControl(ComplexControlBody body, ViewDefinition viewDefinition) { // viewDefinition can be null for nested controls - if (viewDefinition != null) + if (viewDefinition is not null) { OutOfBand = viewDefinition.outOfBand; GroupBy = PSControlGroupBy.Get(viewDefinition.groupBy); @@ -134,7 +134,7 @@ internal CustomControlEntry() internal CustomControlEntry(ComplexControlEntryDefinition entry) { - if (entry.appliesTo != null) + if (entry.appliesTo is not null) { SelectedBy = EntrySelectedBy.Get(entry.appliesTo.referenceList); } @@ -180,13 +180,13 @@ internal static CustomItemBase Create(FormatToken token) } var textToken = token as TextToken; - if (textToken != null) + if (textToken is not null) { return new CustomItemText { Text = textToken.text }; } var frameToken = token as FrameToken; - if (frameToken != null) + if (frameToken is not null) { var frame = new CustomItemFrame { @@ -212,21 +212,21 @@ internal static CustomItemBase Create(FormatToken token) } var cpt = token as CompoundPropertyToken; - if (cpt != null) + if (cpt is not null) { var cie = new CustomItemExpression { EnumerateCollection = cpt.enumerateCollection }; - if (cpt.conditionToken != null) + if (cpt.conditionToken is not null) { cie.ItemSelectionCondition = new DisplayEntry(cpt.conditionToken); } - if (cpt.expression.expressionValue != null) + if (cpt.expression.expressionValue is not null) { cie.Expression = new DisplayEntry(cpt.expression); } - if (cpt.control != null) + if (cpt.control is not null) { cie.CustomControl = new CustomControl((ComplexControlBody)cpt.control, null); } @@ -235,7 +235,7 @@ internal static CustomItemBase Create(FormatToken token) } var fpt = token as FieldPropertyToken; - if (fpt != null) + if (fpt is not null) { } @@ -358,9 +358,9 @@ private void AddDisplayExpressionBinding( { _entryStack.Peek().Add(new CustomItemExpression() { - ItemSelectionCondition = selectedByScript != null + ItemSelectionCondition = selectedByScript is not null ? new DisplayEntry(selectedByScript, DisplayEntryValueType.ScriptBlock) - : selectedByType != null + : selectedByType is not null ? new DisplayEntry(selectedByType, DisplayEntryValueType.Property) : null, EnumerateCollection = enumerateCollection, @@ -402,9 +402,9 @@ public CustomEntryBuilder AddCustomControlExpressionBinding( { _entryStack.Peek().Add(new CustomItemExpression() { - ItemSelectionCondition = selectedByScript != null + ItemSelectionCondition = selectedByScript is not null ? new DisplayEntry(selectedByScript, DisplayEntryValueType.ScriptBlock) - : selectedByType != null + : selectedByType is not null ? new DisplayEntry(selectedByType, DisplayEntryValueType.Property) : null, EnumerateCollection = enumerateCollection, 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..44894cc10a0 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_List.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_List.cs @@ -32,7 +32,7 @@ internal override ControlBase Copy() { ListControlBody result = new ListControlBody(); result.autosize = this.autosize; - if (defaultEntryDefinition != null) + if (defaultEntryDefinition is not null) { result.defaultEntryDefinition = this.defaultEntryDefinition.Copy(); } @@ -226,7 +226,7 @@ public ListControlEntry() internal ListControlEntry(ListControlEntryDefinition entrydefn) : this() { - if (entrydefn.appliesTo != null) + if (entrydefn.appliesTo is not null) { EntrySelectedBy = EntrySelectedBy.Get(entrydefn.appliesTo.referenceList); } @@ -314,21 +314,21 @@ internal ListControlEntryItem() internal ListControlEntryItem(ListControlItemDefinition definition) { - if (definition.label != null) + if (definition.label is not null) { Label = definition.label.text; } FieldPropertyToken fpt = definition.formatTokenList[0] as FieldPropertyToken; - if (fpt != null) + if (fpt is not null) { - if (fpt.fieldFormattingDirective.formatString != null) + if (fpt.fieldFormattingDirective.formatString is not null) { FormatString = fpt.fieldFormattingDirective.formatString; } DisplayEntry = new DisplayEntry(fpt.expression); - if (definition.conditionToken != null) + if (definition.conditionToken is not null) { ItemSelectionCondition = new DisplayEntry(definition.conditionToken); } 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..f97470f58da 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Table.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Table.cs @@ -53,7 +53,7 @@ internal override ControlBase Copy() autosize = this.autosize, header = this.header.Copy() }; - if (defaultDefinition != null) + if (defaultDefinition is not null) { result.defaultDefinition = this.defaultDefinition.Copy(); } @@ -332,7 +332,7 @@ public sealed class TableControlColumnHeader internal TableControlColumnHeader(TableColumnHeaderDefinition colheaderdefinition) { - if (colheaderdefinition.label != null) + if (colheaderdefinition.label is not null) { Label = colheaderdefinition.label.text; } @@ -439,7 +439,7 @@ public TableControlRow() internal TableControlRow(TableRowDefinition rowdefinition) : this() { Wrap = rowdefinition.multiLine; - if (rowdefinition.appliesTo != null) + if (rowdefinition.appliesTo is not null) { SelectedBy = EntrySelectedBy.Get(rowdefinition.appliesTo.referenceList); } @@ -449,7 +449,7 @@ internal TableControlRow(TableRowDefinition rowdefinition) : this() FieldPropertyToken fpt = itemdef.formatTokenList[0] as FieldPropertyToken; TableControlColumn column; - if (fpt != null) + if (fpt is not null) { column = new TableControlColumn(fpt.expression.expressionValue, itemdef.alignment, fpt.expression.isScriptBlock, fpt.fieldFormattingDirective.formatString); @@ -482,7 +482,7 @@ internal bool SafeForExport() return false; } - return SelectedBy != null && SelectedBy.SafeForExport(); + return SelectedBy is not null && SelectedBy.SafeForExport(); } internal bool CompatibleWithOldPowerShell() @@ -588,15 +588,15 @@ public TableControlBuilder AddHeader(Alignment alignment = Alignment.Undefined, public TableRowDefinitionBuilder StartRowDefinition(bool wrap = false, IEnumerable entrySelectedByType = null, IEnumerable entrySelectedByCondition = null) { var row = new TableControlRow { Wrap = wrap }; - if (entrySelectedByType != null || entrySelectedByCondition != null) + if (entrySelectedByType is not null || entrySelectedByCondition is not null) { row.SelectedBy = new EntrySelectedBy(); - if (entrySelectedByType != null) + if (entrySelectedByType is not null) { row.SelectedBy.TypeNames = new List(entrySelectedByType); } - if (entrySelectedByCondition != null) + if (entrySelectedByCondition is not null) { row.SelectedBy.SelectionCondition = new List(entrySelectedByCondition); } 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..7e5f5b1569e 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Wide.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Wide.cs @@ -206,13 +206,13 @@ internal WideControlEntryItem() internal WideControlEntryItem(WideControlEntryDefinition definition) : this() { FieldPropertyToken fpt = definition.formatTokenList[0] as FieldPropertyToken; - if (fpt != null) + if (fpt is not null) { DisplayEntry = new DisplayEntry(fpt.expression); FormatString = fpt.fieldFormattingDirective.formatString; } - if (definition.appliesTo != null) + if (definition.appliesTo is not null) { EntrySelectedBy = EntrySelectedBy.Get(definition.appliesTo.referenceList); } diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs index 5e316c0a2df..4857ec7096c 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs @@ -17,10 +17,10 @@ internal enum AssemblyBindingStatus { NotFound, FoundInGac, FoundInPath }; internal string GetTextTokenString(TextToken tt) { - if (tt.resource != null) + if (tt.resource is not null) { string resString = this.GetString(tt.resource); - if (resString != null) + if (resString is not null) return resString; } @@ -170,7 +170,7 @@ internal Assembly ResolveAssemblyName(string assemblyName) // NOTE: we cache the result (both for success and failure) // Porting note: this won't be hit in normal usage, but can be hit with bad build setup - Diagnostics.Assert(retVal != null, "AssemblyName resolution failed, a resource file might be broken"); + Diagnostics.Assert(retVal is not null, "AssemblyName resolution failed, a resource file might be broken"); _assemblyReferences.Add(assemblyName, retVal); return retVal; @@ -188,7 +188,7 @@ private Assembly ResolveAssemblyNameInLoadedAssemblies(string assemblyName, bool ExecutionContext context = System.Management.Automation.Runspaces.LocalPipeline.GetExecutionContextFromTLS(); - if (context != null) + if (context is not null) { context.AssemblyCache.GetAtKey(assemblyName, out result); } diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs index 38f297c6717..a1f9cdd8925 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs @@ -403,7 +403,7 @@ private static TypeInfoDataBase LoadFromFileHelper( foreach (PSSnapInTypeAndFormatErrors file in files) { // Loads formatting data from ExtendedTypeDefinition instance - if (file.FormatData != null) + if (file.FormatData is not null) { LoadFormatDataHelper(file.FormatData, expressionFactory, logEntries, ref success, file, db, isBuiltInFormatData: false, isForHelp: false); continue; diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs index 59b17ec30eb..b147d0f6bd6 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs @@ -19,7 +19,7 @@ internal static bool Evaluate(PSObject obj, PSPropertyExpression ex, out PSPrope List res = ex.GetValues(obj); if (res.Count == 0) return false; - if (res[0].Exception != null) + if (res[0].Exception is not null) { expressionResult = res[0]; return false; @@ -137,7 +137,7 @@ private int ComputeBestMatch(AppliesTo appliesTo, PSObject currentObject) foreach (TypeOrGroupReference r in appliesTo.referenceList) { PSPropertyExpression ex = null; - if (r.conditionToken != null) + if (r.conditionToken is not null) { ex = _expressionFactory.CreateFromExpressionToken(r.conditionToken); } @@ -145,7 +145,7 @@ private int ComputeBestMatch(AppliesTo appliesTo, PSObject currentObject) int currentMatch = BestMatchIndexUndefined; TypeReference tr = r as TypeReference; - if (tr != null) + if (tr is not null) { // we have a type currentMatch = MatchTypeIndex(tr.name, currentObject, ex); @@ -158,7 +158,7 @@ private int ComputeBestMatch(AppliesTo appliesTo, PSObject currentObject) // find the type group definition the reference points to TypeGroupDefinition tgd = DisplayDataQuery.FindGroupDefinition(_db, tgr.name); - if (tgd != null) + if (tgd is not null) { // we found the group, see if the group has the type currentMatch = ComputeBestMatchInGroup(tgd, currentObject, ex); @@ -282,14 +282,14 @@ internal static EnumerableExpansion GetEnumerableExpansionFromType(PSPropertyExp } } - if (match.BestMatch != null) + if (match.BestMatch is not null) { return ((EnumerableExpansionDirective)(match.BestMatch)).enumerableExpansion; } else { Collection typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames); - if (typesWithoutPrefix != null) + if (typesWithoutPrefix is not null) { EnumerableExpansion result = GetEnumerableExpansionFromType(expressionFactory, db, typesWithoutPrefix); return result; @@ -313,14 +313,14 @@ internal static FormatShape GetShapeFromType(PSPropertyExpressionFactory express } } - if (match.BestMatch != null) + if (match.BestMatch is not null) { return ((FormatShapeSelectionOnType)(match.BestMatch)).formatShape; } else { Collection typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames); - if (typesWithoutPrefix != null) + if (typesWithoutPrefix is not null) { FormatShape result = GetShapeFromType(expressionFactory, db, typesWithoutPrefix); return result; @@ -395,7 +395,7 @@ internal static ViewDefinition GetOutOfBandView(PSPropertyExpressionFactory expr if (result is null) { Collection typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames); - if (typesWithoutPrefix != null) + if (typesWithoutPrefix is not null) { result = GetOutOfBandView(expressionFactory, db, typesWithoutPrefix); } @@ -413,7 +413,7 @@ private static ViewDefinition GetView(PSPropertyExpressionFactory expressionFact { ActiveTracer.WriteLine( "NOT MATCH {0} NAME: {1}", - ControlBase.GetControlShapeName(vd.mainControl), (vd != null ? vd.name : string.Empty)); + ControlBase.GetControlShapeName(vd.mainControl), (vd is not null ? vd.name : string.Empty)); continue; } @@ -434,7 +434,7 @@ private static ViewDefinition GetView(PSPropertyExpressionFactory expressionFact } // first make sure we match on name: // if not, we do not try a match at all - if (viewName != null && !string.Equals(vd.name, viewName, StringComparison.OrdinalIgnoreCase)) + if (viewName is not null && !string.Equals(vd.name, viewName, StringComparison.OrdinalIgnoreCase)) { ActiveTracer.WriteLine( "NOT MATCH {0} NAME: {1}", @@ -470,7 +470,7 @@ private static ViewDefinition GetView(PSPropertyExpressionFactory expressionFact if (result is null) { Collection typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames); - if (typesWithoutPrefix != null) + if (typesWithoutPrefix is not null) { result = GetView(expressionFactory, db, mainControlType, typesWithoutPrefix, viewName); } @@ -488,7 +488,7 @@ private static void TraceHelper(ViewDefinition vd, bool isMatched) StringBuilder sb = new StringBuilder(); TypeReference tr = togr as TypeReference; sb.Append(isMatched ? "MATCH FOUND" : "NOT MATCH"); - if (tr != null) + if (tr is not null) { sb.AppendFormat(CultureInfo.InvariantCulture, " {0} NAME: {1} TYPE: {2}", ControlBase.GetControlShapeName(vd.mainControl), vd.name, tr.name); @@ -508,7 +508,7 @@ private static void TraceHelper(ViewDefinition vd, bool isMatched) private static ViewDefinition GetBestMatch(TypeMatch match) { ViewDefinition bestMatchedVD = match.BestMatch as ViewDefinition; - if (bestMatchedVD != null) + if (bestMatchedVD is not null) { TraceHelper(bestMatchedVD, true); } @@ -565,7 +565,7 @@ private static ViewDefinition GetDefaultView(PSPropertyExpressionFactory express if (result is null) { Collection typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames); - if (typesWithoutPrefix != null) + if (typesWithoutPrefix is not null) { result = GetDefaultView(expressionFactory, db, typesWithoutPrefix); } @@ -594,7 +594,7 @@ internal static AppliesTo GetAllApplicableTypes(TypeInfoDataBase db, AppliesTo a { // if it is a type reference, just add the type name TypeReference tr = r as TypeReference; - if (tr != null) + if (tr is not null) { if (!allTypes.Contains(tr.name)) allTypes.Add(tr.name); @@ -648,7 +648,7 @@ internal static ControlBody ResolveControlReference(TypeInfoDataBase db, List typeNames, FormatVie view.outOfBand = control.OutOfBand; - if (control.GroupBy != null) + if (control.GroupBy is not null) { view.groupBy = new GroupBy { @@ -511,12 +511,12 @@ private ViewDefinition LoadViewFromObjectModel(List typeNames, FormatVie expression = LoadExpressionFromObjectModel(control.GroupBy.Expression, viewIndex, firstTypeName) } }; - if (control.GroupBy.Label != null) + if (control.GroupBy.Label is not null) { view.groupBy.startGroup.labelTextToken = new TextToken { text = control.GroupBy.Label }; } - if (control.GroupBy.CustomControl != null) + if (control.GroupBy.CustomControl is not null) { view.groupBy.startGroup.control = LoadCustomControlFromObjectModel(control.GroupBy.CustomControl, viewIndex, firstTypeName); } @@ -636,7 +636,7 @@ private void LoadRowEntriesSectionFromObjectModel(TableControlBody tableBody, Li } } - if (row.SelectedBy != null) + if (row.SelectedBy is not null) { trd.appliesTo = LoadAppliesToSectionFromObjectModel(row.SelectedBy.TypeNames, row.SelectedBy.SelectionCondition); tableBody.optionalDefinitionList.Add(trd); @@ -672,7 +672,7 @@ private void LoadColumnEntriesFromObjectModel(TableRowDefinition trd, List selectedBy, L { AppliesTo appliesTo = new AppliesTo(); - if (selectedBy != null) + if (selectedBy is not null) { foreach (string type in selectedBy) { @@ -761,7 +761,7 @@ private AppliesTo LoadAppliesToSectionFromObjectModel(List selectedBy, L } } - if (condition != null) + if (condition is not null) { foreach (var cond in condition) { @@ -853,7 +853,7 @@ private ListControlEntryDefinition LoadListControlEntryDefinitionFromObjectModel // Contains: // SelectedBy --- EntrySelectedBy(TypeName) cardinality 0..1 // Items --- ListItems cardinality 1 - if (listEntry.EntrySelectedBy != null) + if (listEntry.EntrySelectedBy is not null) { lved.appliesTo = LoadAppliesToSectionFromObjectModel(listEntry.EntrySelectedBy.TypeNames, listEntry.EntrySelectedBy.SelectionCondition); } @@ -883,7 +883,7 @@ private void LoadListControlItemDefinitionsFromObjectModel(ListControlEntryDefin // Contains: // DisplayEntry --- Expression cardinality 0..1 // Label --- Label cardinality 0..1 - if (listItem.DisplayEntry != null) + if (listItem.DisplayEntry is not null) { ExpressionToken expression = LoadExpressionFromObjectModel(listItem.DisplayEntry, viewIndex, typeName); if (expression is null) @@ -1016,7 +1016,7 @@ private WideControlEntryDefinition LoadWideControlEntryFromObjectModel(WideContr // SelectedBy --- EntrySelectedBy (TypeName) cardinality 0..1 // DisplayEntry --- WideItem (Expression) cardinality 1 // process selectedBy property - if (wideItem.EntrySelectedBy != null) + if (wideItem.EntrySelectedBy is not null) { wved.appliesTo = LoadAppliesToSectionFromObjectModel(wideItem.EntrySelectedBy.TypeNames, wideItem.EntrySelectedBy.SelectionCondition); } @@ -1042,7 +1042,7 @@ private WideControlEntryDefinition LoadWideControlEntryFromObjectModel(WideContr private ComplexControlBody LoadCustomControlFromObjectModel(CustomControl custom, int viewIndex, string typeName) { - if (custom._cachedBody != null) + if (custom._cachedBody is not null) return custom._cachedBody; var ccb = new ComplexControlBody(); @@ -1067,7 +1067,7 @@ private ComplexControlBody LoadCustomControlFromObjectModel(CustomControl custom private ComplexControlEntryDefinition LoadComplexControlEntryDefinitionFromObjectModel(CustomControlEntry entry, int viewIndex, string typeName) { var cced = new ComplexControlEntryDefinition(); - if (entry.SelectedBy != null) + if (entry.SelectedBy is not null) { cced.appliesTo = LoadAppliesToSectionFromObjectModel(entry.SelectedBy.TypeNames, entry.SelectedBy.SelectionCondition); } @@ -1083,33 +1083,33 @@ private ComplexControlEntryDefinition LoadComplexControlEntryDefinitionFromObjec private FormatToken LoadFormatTokenFromObjectModel(CustomItemBase item, int viewIndex, string typeName) { var newline = item as CustomItemNewline; - if (newline != null) + if (newline is not null) { return new NewLineToken { count = newline.Count }; } var text = item as CustomItemText; - if (text != null) + if (text is not null) { return new TextToken { text = text.Text }; } var expr = item as CustomItemExpression; - if (expr != null) + if (expr is not null) { var cpt = new CompoundPropertyToken { enumerateCollection = expr.EnumerateCollection }; - if (expr.ItemSelectionCondition != null) + if (expr.ItemSelectionCondition is not null) { cpt.conditionToken = LoadExpressionFromObjectModel(expr.ItemSelectionCondition, viewIndex, typeName); } - if (expr.Expression != null) + if (expr.Expression is not null) { cpt.expression = LoadExpressionFromObjectModel(expr.Expression, viewIndex, typeName); } - if (expr.CustomControl != null) + if (expr.CustomControl is not null) { cpt.control = LoadCustomControlFromObjectModel(expr.CustomControl, viewIndex, typeName); } @@ -1430,7 +1430,7 @@ private AppliesTo LoadAppliesToSection(XmlNode appliesToNode, bool allowSelectio if (MatchNodeName(n, XmlTags.SelectionSetNameNode)) { TypeGroupReference tgr = LoadTypeGroupReference(n); - if (tgr != null) + if (tgr is not null) { appliesTo.referenceList.Add(tgr); } @@ -1442,7 +1442,7 @@ private AppliesTo LoadAppliesToSection(XmlNode appliesToNode, bool allowSelectio else if (MatchNodeName(n, XmlTags.TypeNameNode)) { TypeReference tr = LoadTypeReference(n); - if (tr != null) + if (tr is not null) { appliesTo.referenceList.Add(tr); } @@ -1454,7 +1454,7 @@ private AppliesTo LoadAppliesToSection(XmlNode appliesToNode, bool allowSelectio else if (allowSelectionCondition && MatchNodeName(n, XmlTags.SelectionConditionNode)) { TypeOrGroupReference tgr = LoadSelectionConditionNode(n); - if (tgr != null) + if (tgr is not null) { appliesTo.referenceList.Add(tgr); } @@ -1486,7 +1486,7 @@ private TypeReference LoadTypeReference(XmlNode n) { string val = GetMandatoryInnerText(n); - if (val != null) + if (val is not null) { TypeReference tr = new TypeReference(); tr.name = val; @@ -1500,7 +1500,7 @@ private TypeGroupReference LoadTypeGroupReference(XmlNode n) { string val = GetMandatoryInnerText(n); - if (val != null) + if (val is not null) { TypeGroupReference tgr = new TypeGroupReference(); tgr.name = val; @@ -1536,7 +1536,7 @@ private TypeOrGroupReference LoadSelectionConditionNode(XmlNode selectionConditi typeGroupFound = true; TypeGroupReference tgr = LoadTypeGroupReference(n); - if (tgr != null) + if (tgr is not null) { retVal = tgr; } @@ -1555,7 +1555,7 @@ private TypeOrGroupReference LoadSelectionConditionNode(XmlNode selectionConditi typeFound = true; TypeReference tr = LoadTypeReference(n); - if (tr != null) + if (tr is not null) { retVal = tr; } @@ -1744,7 +1744,7 @@ private TextToken LoadTextToken(XmlNode n) return null; } - if (tt.resource != null) + if (tt.resource is not null) { // inner text is optional tt.text = n.InnerText; @@ -1782,7 +1782,7 @@ private bool LoadStringResourceReference(XmlNode n, out StringResourceReference resource = LoadResourceAttributes(e.Attributes); // we committed to having resources, if not obtained, it's an error - return resource != null; + return resource is not null; } private StringResourceReference LoadResourceAttributes(XmlAttributeCollection attributes) @@ -1960,7 +1960,7 @@ internal bool ProcessNode(XmlNode n) { if (_loader.MatchNodeName(n, XmlTags.PropertyNameNode)) { - if (_token != null) + if (_token is not null) { if (_token.isScriptBlock) _loader.ProcessDuplicateAlternateNode(n, XmlTags.PropertyNameNode, XmlTags.ScriptBlockNode); @@ -1983,7 +1983,7 @@ internal bool ProcessNode(XmlNode n) } else if (_loader.MatchNodeName(n, XmlTags.ScriptBlockNode)) { - if (_token != null) + if (_token is not null) { if (!_token.isScriptBlock) _loader.ProcessDuplicateAlternateNode(n, XmlTags.PropertyNameNode, XmlTags.ScriptBlockNode); 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..11016eaab27 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_List.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_List.cs @@ -265,7 +265,7 @@ private ListControlItemDefinition LoadListControlItemDefinition(XmlNode property lvid.conditionToken = condition; // add either the text token or the PSPropertyExpression with optional format string - if (match.TextToken != null) + if (match.TextToken is not null) { lvid.formatTokenList.Add(match.TextToken); } 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..225ce809240 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Table.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Table.cs @@ -157,7 +157,7 @@ private void LoadHeadersSection(TableControlBody tableBody, XmlNode headersNode) { TableColumnHeaderDefinition chd = LoadColumnHeaderDefinition(n, columnIndex++); - if (chd != null) + if (chd is not null) tableBody.header.columnHeaderDefinitionList.Add(chd); else { @@ -420,7 +420,7 @@ private void LoadColumnEntries(XmlNode columnEntriesNode, TableRowDefinition trd if (MatchNodeName(n, XmlTags.TableColumnItemNode)) { TableRowItemDefinition rid = LoadColumnEntry(n, columnEntryIndex++); - if (rid != null) + if (rid is not null) { trd.rowItemDefinitionList.Add(rid); } @@ -480,11 +480,11 @@ private TableRowItemDefinition LoadColumnEntry(XmlNode columnEntryNode, int inde // finally build the item to return // add either the text token or the PSPropertyExpression with optional format string - if (match.TextToken != null) + if (match.TextToken is not null) { rid.formatTokenList.Add(match.TextToken); } - else if (match.Expression != null) + else if (match.Expression is not null) { FieldPropertyToken fpt = new FieldPropertyToken(); fpt.expression = match.Expression; 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..3e3432122a9 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Views.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Views.cs @@ -25,7 +25,7 @@ private void LoadViewDefinitions(TypeInfoDataBase db, XmlNode viewDefinitionsNod if (MatchNodeName(n, XmlTags.ViewNode)) { ViewDefinition view = LoadView(n, index++); - if (view != null) + if (view is not null) { ReportTrace(string.Format(CultureInfo.InvariantCulture, "{0} view {1} is loaded from file {2}", @@ -137,7 +137,7 @@ private ViewDefinition LoadView(XmlNode viewNode, int index) return null; // fatal } - if (view.outOfBand && (view.groupBy != null)) + if (view.outOfBand && (view.groupBy is not null)) { // we cannot have grouping and out of band at the same time // Error at XPath {0} in file {1}: An Out Of Band view cannot have GroupBy. @@ -295,7 +295,7 @@ private void LoadControlDefinitions(XmlNode definitionsNode, List LoadPropertyEntry(XmlNode propertyEntryNode) List formatTokenList = new List(); // add either the text token or the PSPropertyExpression with optional format string - if (match.TextToken != null) + if (match.TextToken is not null) { formatTokenList.Add(match.TextToken); } diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatGroupManager.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatGroupManager.cs index 67f1a96c7a9..d07cff615af 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatGroupManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatGroupManager.cs @@ -35,7 +35,7 @@ internal string GroupingKeyDisplayName { get { - if (_label != null) + if (_label is not null) return _label; return _groupingKeyDisplayName; } diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatMsgCtxManager.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatMsgCtxManager.cs index 0aaf16a9a28..524918c591d 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatMsgCtxManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatMsgCtxManager.cs @@ -64,7 +64,7 @@ internal void Process(object o) { PacketInfoData formatData = o as PacketInfoData; FormatEntryData fed = formatData as FormatEntryData; - if (fed != null) + if (fed is not null) { OutputContext ctx = null; @@ -104,15 +104,15 @@ internal void Process(object o) { GroupEndData ged = formatData as GroupEndData; FormatEndData fEndd = formatData as FormatEndData; - if (ged != null || fEndd != null) + if (ged is not null || fEndd is not null) { OutputContext oc = _stack.Peek(); - if (fEndd != null) + if (fEndd is not null) { // notify for Fe, passing the Fe info, before a Pop() this.fe(fEndd, oc); } - else if (ged != null) + else if (ged is not null) { // notify for Fe, passing the Fe info, before a Pop() this.ge(ged, oc); diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator.cs index e39fd46466a..1dc75f31594 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator.cs @@ -19,9 +19,9 @@ internal virtual void Initialize(TerminatingErrorContext terminatingErrorContext ViewDefinition view, FormattingCommandLineParameters formatParameters) { - Diagnostics.Assert(mshExpressionFactory != null, "mshExpressionFactory cannot be null"); - Diagnostics.Assert(db != null, "db cannot be null"); - Diagnostics.Assert(view != null, "view cannot be null"); + Diagnostics.Assert(mshExpressionFactory is not null, "mshExpressionFactory cannot be null"); + Diagnostics.Assert(db is not null, "db cannot be null"); + Diagnostics.Assert(view is not null, "view cannot be null"); errorContext = terminatingErrorContext; expressionFactory = mshExpressionFactory; @@ -69,7 +69,7 @@ private void InitializeHelper() private void InitializeFormatErrorManager() { FormatErrorPolicy formatErrorPolicy = new FormatErrorPolicy(); - if (parameters != null && parameters.showErrorsAsMessages.HasValue) + if (parameters is not null && parameters.showErrorsAsMessages.HasValue) { formatErrorPolicy.ShowErrorsAsMessages = parameters.showErrorsAsMessages.Value; } @@ -78,7 +78,7 @@ private void InitializeFormatErrorManager() formatErrorPolicy.ShowErrorsAsMessages = this.dataBaseInfo.db.defaultSettingsSection.formatErrorPolicy.ShowErrorsAsMessages; } - if (parameters != null && parameters.showErrorsInFormattedOutput.HasValue) + if (parameters is not null && parameters.showErrorsInFormattedOutput.HasValue) { formatErrorPolicy.ShowErrorsInFormattedOutput = parameters.showErrorsInFormattedOutput.Value; } @@ -93,7 +93,7 @@ private void InitializeFormatErrorManager() private void InitializeGroupBy() { // first check if there is an override from the command line - if (parameters != null && parameters.groupByParameter != null) + if (parameters is not null && parameters.groupByParameter is not null) { // get the expression to use PSPropertyExpression groupingKeyExpression = parameters.groupByParameter.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as PSPropertyExpression; @@ -112,7 +112,7 @@ private void InitializeGroupBy() } // check if we have a view to initialize from - if (this.dataBaseInfo.view != null) + if (this.dataBaseInfo.view is not null) { GroupBy gb = this.dataBaseInfo.view.groupBy; if (gb is null) @@ -135,16 +135,16 @@ private void InitializeGroupBy() private void InitializeAutoSize() { // check the autosize flag first - if (parameters != null && parameters.autosize.HasValue) + if (parameters is not null && parameters.autosize.HasValue) { _autosize = parameters.autosize.Value; return; } // check if we have a view with autosize checked - if (this.dataBaseInfo.view != null && this.dataBaseInfo.view.mainControl != null) + if (this.dataBaseInfo.view is not null && this.dataBaseInfo.view.mainControl is not null) { ControlBody controlBody = this.dataBaseInfo.view.mainControl as ControlBody; - if (controlBody != null && controlBody.autosize.HasValue) + if (controlBody is not null && controlBody.autosize.HasValue) { _autosize = controlBody.autosize.Value; } @@ -153,7 +153,7 @@ private void InitializeAutoSize() private void InitializeRepeatHeader() { - if (parameters != null) + if (parameters is not null) { _repeatHeader = parameters.repeatHeader; } @@ -189,9 +189,9 @@ internal GroupStartData GenerateGroupStartData(PSObject firstObjectInGroup, int // we need to determine how to display the group header ControlBase control = null; TextToken labelTextToken = null; - if (this.dataBaseInfo.view != null && this.dataBaseInfo.view.groupBy != null) + if (this.dataBaseInfo.view is not null && this.dataBaseInfo.view.groupBy is not null) { - if (this.dataBaseInfo.view.groupBy.startGroup != null) + if (this.dataBaseInfo.view.groupBy.startGroup is not null) { // NOTE: from the database constraints, only one of the // two will be non null @@ -217,7 +217,7 @@ internal GroupStartData GenerateGroupStartData(PSObject firstObjectInGroup, int string currentGroupingValueDisplay = PSObjectHelper.SmartToString(so, this.expressionFactory, enumerationLimit, formatErrorObject); - if (formatErrorObject != null && formatErrorObject.exception != null) + if (formatErrorObject is not null && formatErrorObject.exception is not null) { // if we did no thave any errors in the expression evaluation // we might have errors in the formatting, if present @@ -237,7 +237,7 @@ internal GroupStartData GenerateGroupStartData(PSObject firstObjectInGroup, int // database, let's use it, else fall back to the string provided // by the grouping manager string label; - if (labelTextToken != null) + if (labelTextToken is not null) label = this.dataBaseInfo.db.displayResourceManagerCache.GetTextTokenString(labelTextToken); else label = _groupingManager.GroupingKeyDisplayName; @@ -302,7 +302,7 @@ internal bool IsObjectApplicable(Collection typeNames) return true; } - bool result = match.BestMatch != null; + bool result = match.BestMatch is not null; // we were unable to find a best match so far..try // to get rid of Deserialization prefix and see if a @@ -310,7 +310,7 @@ internal bool IsObjectApplicable(Collection typeNames) if (false == result) { Collection typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames); - if (typesWithoutPrefix != null) + if (typesWithoutPrefix is not null) { result = IsObjectApplicable(typesWithoutPrefix); } @@ -374,10 +374,10 @@ protected string GetExpressionDisplayValue(PSObject so, int enumerationLimit, PS string retVal = PSObjectHelper.GetExpressionDisplayValue(so, enumerationLimit, ex, directive, formatErrorObject, expressionFactory, out expressionResult); - if (expressionResult != null) + if (expressionResult is not null) { // we obtained a result, check if there is an error - if (expressionResult.Exception != null) + if (expressionResult.Exception is not null) { _errorManager.LogPSPropertyExpressionFailedResult(expressionResult, so); if (_errorManager.DisplayErrorStrings) @@ -385,7 +385,7 @@ protected string GetExpressionDisplayValue(PSObject so, int enumerationLimit, PS retVal = _errorManager.ErrorString; } } - else if (formatErrorObject != null && formatErrorObject.exception != null) + else if (formatErrorObject is not null && formatErrorObject.exception is not null) { // if we did no thave any errors in the expression evaluation // we might have errors in the formatting, if present @@ -409,7 +409,7 @@ protected bool EvaluateDisplayCondition(PSObject so, ExpressionToken conditionTo PSPropertyExpressionResult expressionResult; bool retVal = DisplayCondition.Evaluate(so, ex, out expressionResult); - if (expressionResult != null && expressionResult.Exception != null) + if (expressionResult is not null && expressionResult.Exception is not null) { _errorManager.LogPSPropertyExpressionFailedResult(expressionResult, so); } @@ -440,7 +440,7 @@ protected FormatPropertyField GenerateFormatPropertyField(List form { FormatToken token = formatTokenList[0]; FieldPropertyToken fpt = token as FieldPropertyToken; - if (fpt != null) + if (fpt is not null) { PSPropertyExpression ex = this.expressionFactory.CreateFromExpressionToken(fpt.expression, this.dataBaseInfo.view.loadingInfo); fpf.propertyValue = this.GetExpressionDisplayValue(so, enumerationLimit, ex, fpt.fieldFormattingDirective, out result); @@ -448,7 +448,7 @@ protected FormatPropertyField GenerateFormatPropertyField(List form else { TextToken tt = token as TextToken; - if (tt != null) + if (tt is not null) fpf.propertyValue = this.dataBaseInfo.db.displayResourceManagerCache.GetTextTokenString(tt); } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Complex.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Complex.cs index b2ca8b6b3c3..b7622f237d3 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Complex.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Complex.cs @@ -30,7 +30,7 @@ internal override FormatEntryData GeneratePayload(PSObject so, int enumerationLi { FormatEntryData fed = new FormatEntryData(); - if (this.dataBaseInfo.view != null) + if (this.dataBaseInfo.view is not null) fed.formatEntryInfo = GenerateComplexViewEntryFromDataBaseInfo(so, enumerationLimit); else fed.formatEntryInfo = GenerateComplexViewEntryFromProperties(so, enumerationLimit); @@ -108,7 +108,7 @@ private bool ExecuteFormatControl(TraversalInfo level, ControlBase control, // we might have a reference ControlReference controlReference = control as ControlReference; - if (controlReference != null && controlReference.controlType == typeof(ComplexControlBody)) + if (controlReference is not null && controlReference.controlType == typeof(ComplexControlBody)) { // retrieve the reference complexBody = DisplayDataQuery.ResolveControlReference( @@ -123,7 +123,7 @@ private bool ExecuteFormatControl(TraversalInfo level, ControlBase control, } // finally, execute the control body - if (complexBody != null) + if (complexBody is not null) { // we have an inline control, just execute it ExecuteFormatControlBody(level, so, complexBody, formatValueList); @@ -156,14 +156,14 @@ private ComplexControlEntryDefinition GetActiveComplexControlEntryDefinition(Com } } - if (match.BestMatch != null) + if (match.BestMatch is not null) { return match.BestMatch as ComplexControlEntryDefinition; } else { Collection typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames); - if (typesWithoutPrefix != null) + if (typesWithoutPrefix is not null) { match = new TypeMatch(_expressionFactory, _db, typesWithoutPrefix); foreach (ComplexControlEntryDefinition x in complexBody.optionalEntryList) @@ -174,7 +174,7 @@ private ComplexControlEntryDefinition GetActiveComplexControlEntryDefinition(Com } } - if (match.BestMatch != null) + if (match.BestMatch is not null) { return match.BestMatch as ComplexControlEntryDefinition; } @@ -206,7 +206,7 @@ private void ExecuteFormatTokenList(TraversalInfo level, foreach (FormatToken t in formatTokenList) { TextToken tt = t as TextToken; - if (tt != null) + if (tt is not null) { FormatTextField ftf = new FormatTextField(); ftf.text = _db.displayResourceManagerCache.GetTextTokenString(tt); @@ -215,7 +215,7 @@ private void ExecuteFormatTokenList(TraversalInfo level, } var newline = t as NewLineToken; - if (newline != null) + if (newline is not null) { for (int i = 0; i < newline.count; i++) { @@ -226,7 +226,7 @@ private void ExecuteFormatTokenList(TraversalInfo level, } FrameToken ft = t as FrameToken; - if (ft != null) + if (ft is not null) { // instantiate a new entry and attach a frame info object FormatEntry feFrame = new FormatEntry(); @@ -246,7 +246,7 @@ private void ExecuteFormatTokenList(TraversalInfo level, } #region CompoundPropertyToken CompoundPropertyToken cpt = t as CompoundPropertyToken; - if (cpt != null) + if (cpt is not null) { if (!EvaluateDisplayCondition(so, cpt.conditionToken)) { @@ -270,7 +270,7 @@ private void ExecuteFormatTokenList(TraversalInfo level, if (resultList.Count > 0) { val = resultList[0].Result; - if (resultList[0].Exception != null) + if (resultList[0].Exception is not null) { _errorManager.LogPSPropertyExpressionFailedResult(resultList[0], so); } @@ -290,10 +290,10 @@ private void ExecuteFormatTokenList(TraversalInfo level, FieldFormattingDirective fieldFormattingDirective = null; StringFormatError formatErrorObject = null; - if (cpt.control != null) + if (cpt.control is not null) { fieldFormattingDirective = ((FieldControlBody)cpt.control).fieldFormattingDirective; - if (fieldFormattingDirective != null && _errorManager.DisplayFormatErrorString) + if (fieldFormattingDirective is not null && _errorManager.DisplayFormatErrorString) { formatErrorObject = new StringFormatError(); } @@ -301,7 +301,7 @@ private void ExecuteFormatTokenList(TraversalInfo level, IEnumerable e = PSObjectHelper.GetEnumerable(val); FormatPropertyField fpf = new FormatPropertyField(); - if (cpt.enumerateCollection && e != null) + if (cpt.enumerateCollection && e is not null) { foreach (object x in e) { @@ -325,7 +325,7 @@ private void ExecuteFormatTokenList(TraversalInfo level, fe.formatValueList.Add(fpf); } - if (formatErrorObject != null && formatErrorObject.exception != null) + if (formatErrorObject is not null && formatErrorObject.exception is not null) { _errorManager.LogStringFormatError(formatErrorObject); fpf.propertyValue = _errorManager.FormatErrorString; @@ -340,7 +340,7 @@ private void ExecuteFormatTokenList(TraversalInfo level, } IEnumerable e = PSObjectHelper.GetEnumerable(val); - if (cpt.enumerateCollection && e != null) + if (cpt.enumerateCollection && e is not null) { foreach (object x in e) { @@ -375,7 +375,7 @@ private bool EvaluateDisplayCondition(PSObject so, ExpressionToken conditionToke PSPropertyExpressionResult expressionResult; bool retVal = DisplayCondition.Evaluate(so, ex, out expressionResult); - if (expressionResult != null && expressionResult.Exception != null) + if (expressionResult is not null && expressionResult.Exception is not null) { _errorManager.LogPSPropertyExpressionFailedResult(expressionResult, so); } @@ -460,7 +460,7 @@ internal ComplexViewEntry GenerateView(PSObject so, FormattingCommandLineParamet // check if the top level object is an enumeration IEnumerable e = PSObjectHelper.GetEnumerable(so); - if (e != null) + if (e is not null) { // let's start the traversal with an enumeration FormatEntry fe = new FormatEntry(); @@ -492,7 +492,7 @@ private void DisplayRawObject(PSObject so, List formatValueList) fpf.propertyValue = PSObjectHelper.SmartToString(so, _expressionFactory, _enumerationLimit, formatErrorObject); - if (formatErrorObject != null && formatErrorObject.exception != null) + if (formatErrorObject is not null && formatErrorObject.exception is not null) { // if we did no thave any errors in the expression evaluation // we might have errors in the formatting, if present @@ -527,7 +527,7 @@ private void DisplayObject(PSObject so, TraversalInfo currentLevel, List= 1) { PSPropertyExpressionResult result = resList[0]; - if (result.Exception != null) + if (result.Exception is not null) { _errorManager.LogPSPropertyExpressionFailedResult(result, so); if (_errorManager.DisplayErrorStrings) @@ -573,7 +573,7 @@ private void ProcessActiveAssociationList(PSObject so, // extract the optional max depth TraversalInfo level = currentLevel; - if (a.OriginatingParameter != null) + if (a.OriginatingParameter is not null) { object maxDepthKey = a.OriginatingParameter.GetEntry(FormatParameterDefinitionKeys.DepthEntryKey); if (maxDepthKey != AutomationNull.Value) @@ -584,10 +584,10 @@ private void ProcessActiveAssociationList(PSObject so, } IEnumerable e = null; - if (val != null || (level.Level >= level.MaxDepth)) + if (val is not null || (level.Level >= level.MaxDepth)) e = PSObjectHelper.GetEnumerable(val); - if (e != null) + if (e is not null) { formatValueList.Add(new FormatNewLine()); DisplayEnumeration(e, level.NextLevel, AddIndentationLevel(formatValueList)); @@ -652,7 +652,7 @@ private void DisplayEnumerationInner(IEnumerable e, TraversalInfo level, List formatValueList, string openTag, string label) { - if (label != null) + if (label is not null) { FormatTextField ftfLabel = new FormatTextField(); ftfLabel.text = label; diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_List.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_List.cs index 2c547d7470f..78c5e9ccf6f 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_List.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_List.cs @@ -16,7 +16,7 @@ internal sealed class ListViewGenerator : ViewGenerator internal override void Initialize(TerminatingErrorContext terminatingErrorContext, PSPropertyExpressionFactory mshExpressionFactory, TypeInfoDataBase db, ViewDefinition view, FormattingCommandLineParameters formatParameters) { base.Initialize(terminatingErrorContext, mshExpressionFactory, db, view, formatParameters); - if ((this.dataBaseInfo != null) && (this.dataBaseInfo.view != null)) + if ((this.dataBaseInfo is not null) && (this.dataBaseInfo.view is not null)) { _listBody = (ListControlBody)this.dataBaseInfo.view.mainControl; } @@ -26,7 +26,7 @@ internal override void Initialize(TerminatingErrorContext errorContext, PSProper PSObject so, TypeInfoDataBase db, FormattingCommandLineParameters parameters) { base.Initialize(errorContext, expressionFactory, so, db, parameters); - if ((this.dataBaseInfo != null) && (this.dataBaseInfo.view != null)) + if ((this.dataBaseInfo is not null) && (this.dataBaseInfo.view is not null)) { _listBody = (ListControlBody)this.dataBaseInfo.view.mainControl; } @@ -42,13 +42,13 @@ internal override void Initialize(TerminatingErrorContext errorContext, PSProper /// internal override void PrepareForRemoteObjects(PSObject so) { - Diagnostics.Assert(so != null, "so cannot be null"); + Diagnostics.Assert(so is not null, "so cannot be null"); // make sure computername property exists. - Diagnostics.Assert(so.Properties[RemotingConstants.ComputerNameNoteProperty] != null, + Diagnostics.Assert(so.Properties[RemotingConstants.ComputerNameNoteProperty] is not null, "PrepareForRemoteObjects cannot be called when the object does not contain ComputerName property."); - if ((dataBaseInfo != null) && (dataBaseInfo.view != null) && (dataBaseInfo.view.mainControl != null)) + if ((dataBaseInfo is not null) && (dataBaseInfo.view is not null) && (dataBaseInfo.view.mainControl is not null)) { _listBody = (ListControlBody)this.dataBaseInfo.view.mainControl.Copy(); // build up the definition for computer name. @@ -74,7 +74,7 @@ internal override FormatEntryData GeneratePayload(PSObject so, int enumerationLi { FormatEntryData fed = new FormatEntryData(); - if (this.dataBaseInfo.view != null) + if (this.dataBaseInfo.view is not null) fed.formatEntryInfo = GenerateListViewEntryFromDataBaseInfo(so, enumerationLimit); else fed.formatEntryInfo = GenerateListViewEntryFromProperties(so, enumerationLimit); @@ -98,12 +98,12 @@ private ListViewEntry GenerateListViewEntryFromDataBaseInfo(PSObject so, int enu lvf.formatPropertyField = GenerateFormatPropertyField(listItem.formatTokenList, so, enumerationLimit, out result); // we need now to provide a label - if (listItem.label != null) + if (listItem.label is not null) { // if the directive provides one, we use it lvf.label = this.dataBaseInfo.db.displayResourceManagerCache.GetTextTokenString(listItem.label); } - else if (result != null) + else if (result is not null) { // if we got a valid match from the Mshexpression, use it as a label lvf.label = result.ResolvedExpression.ToString(); @@ -115,7 +115,7 @@ private ListViewEntry GenerateListViewEntryFromDataBaseInfo(PSObject so, int enu // we try to fall back and see if we have an un-resolved PSPropertyExpression FormatToken token = listItem.formatTokenList[0]; FieldPropertyToken fpt = token as FieldPropertyToken; - if (fpt != null) + if (fpt is not null) { PSPropertyExpression ex = this.expressionFactory.CreateFromExpressionToken(fpt.expression, this.dataBaseInfo.view.loadingInfo); @@ -125,7 +125,7 @@ private ListViewEntry GenerateListViewEntryFromDataBaseInfo(PSObject so, int enu else { TextToken tt = token as TextToken; - if (tt != null) + if (tt is not null) // we had a text token, use it as a label (last resort...) lvf.label = this.dataBaseInfo.db.displayResourceManagerCache.GetTextTokenString(tt); } @@ -150,14 +150,14 @@ private ListControlEntryDefinition GetActiveListControlEntryDefinition(ListContr } } - if (match.BestMatch != null) + if (match.BestMatch is not null) { return match.BestMatch as ListControlEntryDefinition; } else { Collection typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames); - if (typesWithoutPrefix != null) + if (typesWithoutPrefix is not null) { match = new TypeMatch(expressionFactory, this.dataBaseInfo.db, typesWithoutPrefix); foreach (ListControlEntryDefinition x in listBody.optionalEntryList) @@ -168,7 +168,7 @@ private ListControlEntryDefinition GetActiveListControlEntryDefinition(ListContr } } - if (match.BestMatch != null) + if (match.BestMatch is not null) { return match.BestMatch as ListControlEntryDefinition; } @@ -194,7 +194,7 @@ private ListViewEntry GenerateListViewEntryFromProperties(PSObject so, int enume MshResolvedExpressionParameterAssociation a = this.activeAssociationList[k]; ListViewField lvf = new ListViewField(); - if (a.OriginatingParameter != null) + if (a.OriginatingParameter is not null) { object key = a.OriginatingParameter.GetEntry(FormatParameterDefinitionKeys.LabelEntryKey); @@ -213,7 +213,7 @@ private ListViewEntry GenerateListViewEntryFromProperties(PSObject so, int enume } FieldFormattingDirective directive = null; - if (a.OriginatingParameter != null) + if (a.OriginatingParameter is not null) { directive = a.OriginatingParameter.GetEntry(FormatParameterDefinitionKeys.FormatStringEntryKey) as FieldFormattingDirective; } @@ -230,7 +230,7 @@ private void SetUpActiveProperties(PSObject so) { List mshParameterList = null; - if (this.inputParameters != null) + if (this.inputParameters is not null) mshParameterList = this.inputParameters.mshParameterList; this.activeAssociationList = AssociationManager.SetupActiveProperties(mshParameterList, so, this.expressionFactory); diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs index 231e8d927de..b6cef8df63a 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs @@ -17,7 +17,7 @@ internal sealed class TableViewGenerator : ViewGenerator internal override void Initialize(TerminatingErrorContext terminatingErrorContext, PSPropertyExpressionFactory mshExpressionFactory, TypeInfoDataBase db, ViewDefinition view, FormattingCommandLineParameters formatParameters) { base.Initialize(terminatingErrorContext, mshExpressionFactory, db, view, formatParameters); - if ((this.dataBaseInfo != null) && (this.dataBaseInfo.view != null)) + if ((this.dataBaseInfo is not null) && (this.dataBaseInfo.view is not null)) { _tableBody = (TableControlBody)this.dataBaseInfo.view.mainControl; } @@ -29,18 +29,18 @@ internal override void Initialize(TerminatingErrorContext errorContext, PSProper { base.Initialize(errorContext, expressionFactory, so, db, parameters); - if ((this.dataBaseInfo != null) && (this.dataBaseInfo.view != null)) + if ((this.dataBaseInfo is not null) && (this.dataBaseInfo.view is not null)) { _tableBody = (TableControlBody)this.dataBaseInfo.view.mainControl; } List rawMshParameterList = null; - if (parameters != null) + if (parameters is not null) rawMshParameterList = parameters.mshParameterList; // check if we received properties from the command line - if (rawMshParameterList != null && rawMshParameterList.Count > 0) + if (rawMshParameterList is not null && rawMshParameterList.Count > 0) { this.activeAssociationList = AssociationManager.ExpandTableParameters(rawMshParameterList, so); return; @@ -83,13 +83,13 @@ internal override void Initialize(TerminatingErrorContext errorContext, PSProper /// internal override void PrepareForRemoteObjects(PSObject so) { - Diagnostics.Assert(so != null, "so cannot be null"); + Diagnostics.Assert(so is not null, "so cannot be null"); // make sure computername property exists. - Diagnostics.Assert(so.Properties[RemotingConstants.ComputerNameNoteProperty] != null, + Diagnostics.Assert(so.Properties[RemotingConstants.ComputerNameNoteProperty] is not null, "PrepareForRemoteObjects cannot be called when the object does not contain ComputerName property."); - if ((dataBaseInfo != null) && (dataBaseInfo.view != null) && (dataBaseInfo.view.mainControl != null)) + if ((dataBaseInfo is not null) && (dataBaseInfo.view is not null) && (dataBaseInfo.view.mainControl is not null)) { // dont change the original format definition in the database..just make a copy and work // with the copy @@ -116,7 +116,7 @@ internal override FormatStartData GenerateStartData(PSObject so) { FormatStartData startFormat = base.GenerateStartData(so); - if (this.dataBaseInfo.view != null) + if (this.dataBaseInfo.view is not null) startFormat.shapeInfo = GenerateTableHeaderInfoFromDataBaseInfo(so); else startFormat.shapeInfo = GenerateTableHeaderInfoFromProperties(so); @@ -167,11 +167,11 @@ private TableHeaderInfo GenerateTableHeaderInfoFromDataBaseInfo(PSObject so) if (_tableBody.header.columnHeaderDefinitionList.Count > 0) colHeader = _tableBody.header.columnHeaderDefinitionList[col]; - if (colHeader != null) + if (colHeader is not null) { ci.width = colHeader.width; ci.alignment = colHeader.alignment; - if (colHeader.label != null) + if (colHeader.label is not null) ci.label = this.dataBaseInfo.db.displayResourceManagerCache.GetTextTokenString(colHeader.label); } @@ -185,17 +185,17 @@ private TableHeaderInfo GenerateTableHeaderInfoFromDataBaseInfo(PSObject so) FormatToken token = null; if (rowItem.formatTokenList.Count > 0) token = rowItem.formatTokenList[0]; - if (token != null) + if (token is not null) { FieldPropertyToken fpt = token as FieldPropertyToken; - if (fpt != null) + if (fpt is not null) { ci.label = fpt.expression.expressionValue; } else { TextToken tt = token as TextToken; - if (tt != null) + if (tt is not null) { ci.label = this.dataBaseInfo.db.displayResourceManagerCache.GetTextTokenString(tt); } @@ -226,7 +226,7 @@ private TableHeaderInfo GenerateTableHeaderInfoFromProperties(PSObject so) TableColumnInfo ci = new TableColumnInfo(); // set the label of the column - if (a.OriginatingParameter != null) + if (a.OriginatingParameter is not null) { object key = a.OriginatingParameter.GetEntry(FormatParameterDefinitionKeys.LabelEntryKey); if (key != AutomationNull.Value) @@ -239,7 +239,7 @@ private TableHeaderInfo GenerateTableHeaderInfoFromProperties(PSObject so) } // set the width of the table - if (a.OriginatingParameter != null) + if (a.OriginatingParameter is not null) { object key = a.OriginatingParameter.GetEntry(FormatParameterDefinitionKeys.WidthEntryKey); @@ -256,7 +256,7 @@ private TableHeaderInfo GenerateTableHeaderInfoFromProperties(PSObject so) } // set the alignment - if (a.OriginatingParameter != null) + if (a.OriginatingParameter is not null) { object key = a.OriginatingParameter.GetEntry(FormatParameterDefinitionKeys.AlignmentEntryKey); @@ -281,16 +281,16 @@ private bool HideHeaders get { // first check command line, it takes the precedence - if (this.parameters != null && this.parameters.shapeParameters != null) + if (this.parameters is not null && this.parameters.shapeParameters is not null) { TableSpecificParameters tableSpecific = (TableSpecificParameters)this.parameters.shapeParameters; - if (tableSpecific != null && tableSpecific.hideHeaders.HasValue) + if (tableSpecific is not null && tableSpecific.hideHeaders.HasValue) { return tableSpecific.hideHeaders.Value; } } // if we have a view, get the value out of it - if (this.dataBaseInfo.view != null) + if (this.dataBaseInfo.view is not null) { return _tableBody.header.hideHeader; } @@ -303,7 +303,7 @@ private bool RepeatHeaders { get { - if (this.parameters != null) + if (this.parameters is not null) { return this.parameters.repeatHeader; } @@ -316,7 +316,7 @@ private static int ComputeDefaultAlignment(PSObject so, PSPropertyExpression ex) { List rList = ex.GetValues(so); - if ((rList.Count == 0) || (rList[0].Exception != null)) + if ((rList.Count == 0) || (rList[0].Exception is not null)) return TextAlignment.Left; object val = rList[0].Result; @@ -340,7 +340,7 @@ internal override FormatEntryData GeneratePayload(PSObject so, int enumerationLi FormatEntryData fed = new FormatEntryData(); TableRowEntry tre; - if (this.dataBaseInfo.view != null) + if (this.dataBaseInfo.view is not null) { tre = GenerateTableRowEntryFromDataBaseInfo(so, enumerationLimit); } @@ -354,10 +354,10 @@ internal override FormatEntryData GeneratePayload(PSObject so, int enumerationLi fed.formatEntryInfo = tre; // override from command line, if there - if (this.parameters != null && this.parameters.shapeParameters != null) + if (this.parameters is not null && this.parameters.shapeParameters is not null) { TableSpecificParameters tableSpecific = (TableSpecificParameters)this.parameters.shapeParameters; - if (tableSpecific != null && tableSpecific.multiLine.HasValue) + if (tableSpecific is not null && tableSpecific.multiLine.HasValue) { tre.multiLine = tableSpecific.multiLine.Value; } @@ -399,7 +399,7 @@ private List GetActiveTableRowDefinition(TableControlBod if (matchingRowDefinition is null) { Collection typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames); - if (typesWithoutPrefix != null) + if (typesWithoutPrefix is not null) { match = new TypeMatch(expressionFactory, this.dataBaseInfo.db, typesWithoutPrefix); @@ -478,7 +478,7 @@ private TableRowEntry GenerateTableRowEntryFromFromProperties(PSObject so, int e { FormatPropertyField fpf = new FormatPropertyField(); FieldFormattingDirective directive = null; - if (activeAssociationList[k].OriginatingParameter != null) + if (activeAssociationList[k].OriginatingParameter is not null) { directive = activeAssociationList[k].OriginatingParameter.GetEntry(FormatParameterDefinitionKeys.FormatStringEntryKey) as FieldFormattingDirective; } diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Wide.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Wide.cs index 2d1aa16d1ac..a670aea7d07 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Wide.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Wide.cs @@ -41,7 +41,7 @@ private int Columns get { // check command line first - if (parameters != null && parameters.shapeParameters != null) + if (parameters is not null && parameters.shapeParameters is not null) { WideSpecificParameters wp = (WideSpecificParameters)parameters.shapeParameters; if (wp.columns.HasValue) @@ -49,7 +49,7 @@ private int Columns } // check if the view has info - if (this.dataBaseInfo.view != null && this.dataBaseInfo.view.mainControl != null) + if (this.dataBaseInfo.view is not null && this.dataBaseInfo.view.mainControl is not null) { WideControlBody wideControl = (WideControlBody)this.dataBaseInfo.view.mainControl; return wideControl.columns; @@ -63,7 +63,7 @@ internal override FormatEntryData GeneratePayload(PSObject so, int enumerationLi { FormatEntryData fed = new FormatEntryData(); - if (this.dataBaseInfo.view != null) + if (this.dataBaseInfo.view is not null) fed.formatEntryInfo = GenerateWideViewEntryFromDataBaseInfo(so, enumerationLimit); else fed.formatEntryInfo = GenerateWideViewEntryFromProperties(so, enumerationLimit); @@ -99,14 +99,14 @@ private WideControlEntryDefinition GetActiveWideControlEntryDefinition(WideContr } } - if (match.BestMatch != null) + if (match.BestMatch is not null) { return match.BestMatch as WideControlEntryDefinition; } else { Collection typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames); - if (typesWithoutPrefix != null) + if (typesWithoutPrefix is not null) { match = new TypeMatch(expressionFactory, this.dataBaseInfo.db, typesWithoutPrefix); foreach (WideControlEntryDefinition x in wideBody.optionalEntryList) @@ -117,7 +117,7 @@ private WideControlEntryDefinition GetActiveWideControlEntryDefinition(WideContr } } - if (match.BestMatch != null) + if (match.BestMatch is not null) { return match.BestMatch as WideControlEntryDefinition; } @@ -145,7 +145,7 @@ private WideViewEntry GenerateWideViewEntryFromProperties(PSObject so, int enume // get the first one MshResolvedExpressionParameterAssociation a = this.activeAssociationList[0]; FieldFormattingDirective directive = null; - if (a.OriginatingParameter != null) + if (a.OriginatingParameter is not null) { directive = a.OriginatingParameter.GetEntry(FormatParameterDefinitionKeys.FormatStringEntryKey) as FieldFormattingDirective; } @@ -161,11 +161,11 @@ private void SetUpActiveProperty(PSObject so) { List rawMshParameterList = null; - if (this.inputParameters != null) + if (this.inputParameters is not null) rawMshParameterList = this.inputParameters.mshParameterList; // check if we received properties from the command line - if (rawMshParameterList != null && rawMshParameterList.Count > 0) + if (rawMshParameterList is not null && rawMshParameterList.Count > 0) { this.activeAssociationList = AssociationManager.ExpandParameters(rawMshParameterList, so); return; @@ -174,7 +174,7 @@ private void SetUpActiveProperty(PSObject so) // we did not get any properties: // try to get the display property of the object PSPropertyExpression displayNameExpression = PSObjectHelper.GetDisplayNameExpression(so, this.expressionFactory); - if (displayNameExpression != null) + if (displayNameExpression is not null) { this.activeAssociationList = new List(); this.activeAssociationList.Add(new MshResolvedExpressionParameterAssociation(null, displayNameExpression)); diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs index baa7ede8edf..5b0eb352dd9 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs @@ -76,7 +76,7 @@ internal sealed class FormatViewManager private static string PSObjectTypeName(PSObject so) { // if so is not null, its TypeNames will not be null - if (so != null) + if (so is not null) { var typeNames = so.InternalTypeNames; if (typeNames.Count > 0) @@ -114,7 +114,7 @@ internal void Initialize(TerminatingErrorContext errorContext, view = DisplayDataQuery.GetViewByShapeAndType(expressionFactory, db, shape, typeNames, null); } - if (view != null) + if (view is not null) { // we got a matching view from the database // use this and we are done @@ -140,14 +140,14 @@ internal void Initialize(TerminatingErrorContext errorContext, } // we have a predefined shape: did the user specify properties on the command line? - if (parameters != null && parameters.mshParameterList.Count > 0) + if (parameters is not null && parameters.mshParameterList.Count > 0) { _viewGenerator = SelectViewGeneratorFromProperties(shape, so, errorContext, expressionFactory, db, parameters); return; } // predefined shape: did the user specify the name of a view? - if (parameters != null && !string.IsNullOrEmpty(parameters.viewName)) + if (parameters is not null && !string.IsNullOrEmpty(parameters.viewName)) { using (s_formatViewBindingTracer.TraceScope(findViewNameType, parameters.viewName, PSObjectTypeName(so))) @@ -155,7 +155,7 @@ internal void Initialize(TerminatingErrorContext errorContext, view = DisplayDataQuery.GetViewByShapeAndType(expressionFactory, db, shape, typeNames, parameters.viewName); } - if (view != null) + if (view is not null) { _viewGenerator = SelectViewGeneratorFromViewDefinition( errorContext, @@ -178,7 +178,7 @@ internal void Initialize(TerminatingErrorContext errorContext, view = DisplayDataQuery.GetViewByShapeAndType(expressionFactory, db, shape, typeNames, null); } - if (view != null) + if (view is not null) { _viewGenerator = SelectViewGeneratorFromViewDefinition( errorContext, @@ -237,9 +237,9 @@ private static void ProcessUnknownViewName(TerminatingErrorContext errorContext, string separator = ", "; StringBuilder validViewFormats = new StringBuilder(); - if (so != null && so.BaseObject != null && - db != null && db.viewDefinitionsSection != null && - db.viewDefinitionsSection.viewDefinitionList != null && + if (so is not null && so.BaseObject is not null && + db is not null && db.viewDefinitionsSection is not null && + db.viewDefinitionsSection.viewDefinitionList is not null && db.viewDefinitionsSection.viewDefinitionList.Count > 0) { StringBuilder validViews = new StringBuilder(); @@ -267,11 +267,11 @@ private static void ProcessUnknownViewName(TerminatingErrorContext errorContext, formatTypeName = "Custom"; } - if (formatType != null) + if (formatType is not null) { foreach (ViewDefinition currentViewDefinition in db.viewDefinitionsSection.viewDefinitionList) { - if (currentViewDefinition.mainControl != null) + if (currentViewDefinition.mainControl is not null) { foreach (TypeOrGroupReference currentTypeOrGroupReference in currentViewDefinition.appliesTo.referenceList) { @@ -361,7 +361,7 @@ internal ViewGenerator ViewGenerator { get { - Diagnostics.Assert(_viewGenerator != null, "this.viewGenerator cannot be null"); + Diagnostics.Assert(_viewGenerator is not null, "this.viewGenerator cannot be null"); return _viewGenerator; } } @@ -391,7 +391,7 @@ private static ViewGenerator SelectViewGeneratorFromViewDefinition( viewGenerator = new ComplexViewGenerator(); } - Diagnostics.Assert(viewGenerator != null, "viewGenerator != null"); + Diagnostics.Assert(viewGenerator is not null, "viewGenerator is not null"); viewGenerator.Initialize(errorContext, expressionFactory, db, view, parameters); return viewGenerator; } @@ -447,7 +447,7 @@ private static ViewGenerator SelectViewGeneratorFromProperties(FormatShape shape viewGenerator = new ComplexViewGenerator(); } - Diagnostics.Assert(viewGenerator != null, "viewGenerator != null"); + Diagnostics.Assert(viewGenerator is not null, "viewGenerator is not null"); viewGenerator.Initialize(errorContext, expressionFactory, so, db, parameters); return viewGenerator; @@ -476,7 +476,7 @@ private static bool IsNotRemotingProperty(string name) private static readonly MemberNamePredicate NameIsNotRemotingProperty = IsNotRemotingProperty; - internal static bool HasNonRemotingProperties(PSObject so) => so.GetFirstPropertyOrDefault(NameIsNotRemotingProperty) != null; + internal static bool HasNonRemotingProperties(PSObject so) => so.GetFirstPropertyOrDefault(NameIsNotRemotingProperty) is not null; internal static FormatEntryData GenerateOutOfBandData(TerminatingErrorContext errorContext, PSPropertyExpressionFactory expressionFactory, TypeInfoDataBase db, PSObject so, int enumerationLimit, bool useToStringFallback, out List errors) @@ -487,7 +487,7 @@ internal static FormatEntryData GenerateOutOfBandData(TerminatingErrorContext er ViewDefinition view = DisplayDataQuery.GetOutOfBandView(expressionFactory, db, typeNames); ViewGenerator outOfBandViewGenerator; - if (view != null) + if (view is not null) { // process an out of band view retrieved from the display database if (view.mainControl is ComplexControlBody) @@ -629,7 +629,7 @@ internal List DrainFailedResultList() foreach (FormattingError error in _formattingErrorList) { ErrorRecord errorRecord = GenerateErrorRecord(error); - if (errorRecord != null) + if (errorRecord is not null) retVal.Add(errorRecord); } @@ -647,7 +647,7 @@ private static ErrorRecord GenerateErrorRecord(FormattingError error) ErrorRecord errorRecord = null; string msg = null; PSPropertyExpressionError psPropertyExpressionError = error as PSPropertyExpressionError; - if (psPropertyExpressionError != null) + if (psPropertyExpressionError is not null) { errorRecord = new ErrorRecord( psPropertyExpressionError.result.Exception, @@ -661,7 +661,7 @@ private static ErrorRecord GenerateErrorRecord(FormattingError error) } StringFormatError formattingError = error as StringFormatError; - if (formattingError != null) + if (formattingError is not null) { errorRecord = new ErrorRecord( formattingError.exception, diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatXMLWriter.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatXMLWriter.cs index bb2c8ff93e7..f964d210d36 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatXMLWriter.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatXMLWriter.cs @@ -113,7 +113,7 @@ internal void WriteToXml(IEnumerable typeDefinitions) _writer.WriteEndElement(/**/); var groupBy = formatdef.Control.GroupBy; - if (groupBy != null) + if (groupBy is not null) { _writer.WriteStartElement("GroupBy"); WriteDisplayEntry(groupBy.Expression); @@ -122,7 +122,7 @@ internal void WriteToXml(IEnumerable typeDefinitions) _writer.WriteElementString("Label", groupBy.Label); } - if (groupBy.CustomControl != null) + if (groupBy.CustomControl is not null) { WriteCustomControl(groupBy.CustomControl); } @@ -191,7 +191,7 @@ internal void WriteTableControl(TableControl tableControl) _writer.WriteEndElement(/**/); } - if (row.SelectedBy != null) + if (row.SelectedBy is not null) { WriteEntrySelectedBy(row.SelectedBy); } @@ -255,7 +255,7 @@ internal void WriteListControl(ListControl listControl) _writer.WriteElementString("FormatString", item.FormatString); } - if (item.ItemSelectionCondition != null) + if (item.ItemSelectionCondition is not null) { _writer.WriteStartElement("ItemSelectionCondition"); WriteDisplayEntry(item.ItemSelectionCondition); @@ -280,13 +280,13 @@ internal void WriteListControl(ListControl listControl) private void WriteEntrySelectedBy(EntrySelectedBy entrySelectedBy) { - if (entrySelectedBy != null && - ((entrySelectedBy.TypeNames != null && entrySelectedBy.TypeNames.Count > 0) || - (entrySelectedBy.SelectionCondition != null && entrySelectedBy.SelectionCondition.Count > 0))) + if (entrySelectedBy is not null && + ((entrySelectedBy.TypeNames is not null && entrySelectedBy.TypeNames.Count > 0) || + (entrySelectedBy.SelectionCondition is not null && entrySelectedBy.SelectionCondition.Count > 0))) { _writer.WriteStartElement("EntrySelectedBy"); - if (entrySelectedBy.TypeNames != null) + if (entrySelectedBy.TypeNames is not null) { foreach (string typename in entrySelectedBy.TypeNames) { @@ -294,7 +294,7 @@ private void WriteEntrySelectedBy(EntrySelectedBy entrySelectedBy) } } - if (entrySelectedBy.SelectionCondition != null) + if (entrySelectedBy.SelectionCondition is not null) { foreach (var condition in entrySelectedBy.SelectionCondition) { @@ -386,7 +386,7 @@ internal void WriteCustomControl(CustomControl customControl) internal void WriteCustomItem(CustomItemBase item) { var newline = item as CustomItemNewline; - if (newline != null) + if (newline is not null) { for (int i = 0; i < newline.Count; i++) { @@ -397,14 +397,14 @@ internal void WriteCustomItem(CustomItemBase item) } var text = item as CustomItemText; - if (text != null) + if (text is not null) { _writer.WriteElementString("Text", text.Text); return; } var expr = item as CustomItemExpression; - if (expr != null) + if (expr is not null) { _writer.WriteStartElement("ExpressionBinding"); if (expr.EnumerateCollection) @@ -412,19 +412,19 @@ internal void WriteCustomItem(CustomItemBase item) _writer.WriteElementString("EnumerateCollection", string.Empty); } - if (expr.ItemSelectionCondition != null) + if (expr.ItemSelectionCondition is not null) { _writer.WriteStartElement("ItemSelectionCondition"); WriteDisplayEntry(expr.ItemSelectionCondition); _writer.WriteEndElement(/**/); } - if (expr.Expression != null) + if (expr.Expression is not null) { WriteDisplayEntry(expr.Expression); } - if (expr.CustomControl != null) + if (expr.CustomControl is not null) { WriteCustomControl(expr.CustomControl); } diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs b/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs index a0c37005e2c..9141fe20ba5 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs @@ -31,7 +31,7 @@ internal FormatObjectDeserializer(TerminatingErrorContext errorContext) internal bool IsFormatInfoData(PSObject so) { var fid = PSObject.Base(so) as FormatInfoData; - if (fid != null) + if (fid is not null) { if (fid is FormatStartData || fid is FormatEndData || @@ -89,7 +89,7 @@ fid is GroupEndData || internal object Deserialize(PSObject so) { var fid = PSObject.Base(so) as FormatInfoData; - if (fid != null) + if (fid is not null) { if (fid is FormatStartData || fid is FormatEndData || @@ -242,7 +242,7 @@ private object DeserializeMemberVariable(PSObject so, string property, System.Ty if (cannotBeNull) VerifyDataNotNull(objRaw, property); - if (objRaw != null && t != objRaw.GetType()) + if (objRaw is not null && t != objRaw.GetType()) { string msg = StringUtil.Format(FormatAndOut_format_xxx.FOD_InvalidPropertyType, t.Name, property); @@ -330,14 +330,14 @@ internal FormatInfoData DeserializeObject(PSObject so) { FormatInfoData fid = FormatInfoDataClassFactory.CreateInstance(so, this); - if (fid != null) + if (fid is not null) fid.Deserialize(so, this); return fid; } internal void VerifyDataNotNull(object obj, string name) { - if (obj != null) + if (obj is not null) return; string msg = StringUtil.Format(FormatAndOut_format_xxx.FOD_NullDataMember, name); diff --git a/src/System.Management.Automation/FormatAndOutput/common/ListWriter.cs b/src/System.Management.Automation/FormatAndOutput/common/ListWriter.cs index b14cfa78e0f..b54d45c5b75 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/ListWriter.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/ListWriter.cs @@ -46,7 +46,7 @@ internal void Initialize(string[] propertyNames, int screenColumnWidth, DisplayC _disabled = false; - Debug.Assert(propertyNames != null, "propertyNames is null"); + Debug.Assert(propertyNames is not null, "propertyNames is null"); Debug.Assert(propertyNames.Length > 0, "propertyNames has zero length"); // assess the useful widths @@ -67,7 +67,7 @@ internal void Initialize(string[] propertyNames, int screenColumnWidth, DisplayC Span propertyNameCellCounts = propertyNames.Length <= OutCommandInner.StackAllocThreshold ? stackalloc int[propertyNames.Length] : new int[propertyNames.Length]; for (int k = 0; k < propertyNames.Length; k++) { - Debug.Assert(propertyNames[k] != null, "propertyNames[k] is null"); + Debug.Assert(propertyNames[k] is not null, "propertyNames[k] is null"); propertyNameCellCounts[k] = dc.Length(propertyNames[k]); if (propertyNameCellCounts[k] > _propertyLabelsDisplayLength) _propertyLabelsDisplayLength = propertyNameCellCounts[k]; @@ -147,7 +147,7 @@ internal void WriteProperties(string[] values, LineOutput lo) valuesToPrint = values; } - Debug.Assert(lo != null, "LineOutput is null"); + Debug.Assert(lo is not null, "LineOutput is null"); for (int k = 0; k < _propertyLabels.Length; k++) { diff --git a/src/System.Management.Automation/FormatAndOutput/common/OutputManager.cs b/src/System.Management.Automation/FormatAndOutput/common/OutputManager.cs index cc5be812cb8..3715409515d 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/OutputManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/OutputManager.cs @@ -92,7 +92,7 @@ internal override void ProcessRecord() internal override void EndProcessing() { // shut down only if we ever processed a pipeline object - if (_mgr != null) + if (_mgr is not null) _mgr.ShutDown(); } @@ -100,7 +100,7 @@ internal override void StopProcessing() { lock (_syncRoot) { - if (_lo != null) + if (_lo is not null) { _lo.StopProcessing(); } @@ -115,7 +115,7 @@ internal override void StopProcessing() protected override void InternalDispose() { base.InternalDispose(); - if (_mgr != null) + if (_mgr is not null) { _mgr.Dispose(); _mgr = null; @@ -259,7 +259,7 @@ internal void Process(PSObject so) // select which pipeline should handle the object CommandEntry ce = this.GetActiveCommandEntry(so); - Diagnostics.Assert(ce != null, "CommandEntry ce must not be null"); + Diagnostics.Assert(ce is not null, "CommandEntry ce must not be null"); // delegate the processing ce.command.Process(so); @@ -273,13 +273,13 @@ internal void ShutDown() // we assume that command entries are never null foreach (CommandEntry ce in _commandEntryList) { - Diagnostics.Assert(ce != null, "ce != null"); + Diagnostics.Assert(ce is not null, "ce is not null"); ce.command.ShutDown(); ce.command = null; } // we assume we always have a default command entry - Diagnostics.Assert(_defaultCommandEntry != null, "defaultCommandEntry != null"); + Diagnostics.Assert(_defaultCommandEntry is not null, "defaultCommandEntry is not null"); _defaultCommandEntry.command.ShutDown(); _defaultCommandEntry.command = null; } @@ -289,12 +289,12 @@ public void Dispose() // we assume that command entries are never null foreach (CommandEntry ce in _commandEntryList) { - Diagnostics.Assert(ce != null, "ce != null"); + Diagnostics.Assert(ce is not null, "ce is not null"); ce.Dispose(); } // we assume we always have a default command entry - Diagnostics.Assert(_defaultCommandEntry != null, "defaultCommandEntry != null"); + Diagnostics.Assert(_defaultCommandEntry is not null, "defaultCommandEntry is not null"); _defaultCommandEntry.Dispose(); } diff --git a/src/System.Management.Automation/FormatAndOutput/common/OutputQueue.cs b/src/System.Management.Automation/FormatAndOutput/common/OutputQueue.cs index d70889c3d4e..5babe2d7ec3 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/OutputQueue.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/OutputQueue.cs @@ -44,7 +44,7 @@ internal OutputGroupQueue(FormattedObjectsCache.ProcessCachedGroupNotification c internal List Add(PacketInfoData o) { FormatStartData fsd = o as FormatStartData; - if (fsd != null) + if (fsd is not null) { // just cache the reference (used during the notification call) _formatStartData = fsd; @@ -72,13 +72,13 @@ internal List Add(PacketInfoData o) if (_processingGroup && ((o is GroupEndData) || (_objectCount > 0) && (_currentObjectCount >= _objectCount)) || - ((_groupingTimer != null) && (_groupingTimer.Elapsed > _groupingDuration)) + ((_groupingTimer is not null) && (_groupingTimer.Elapsed > _groupingDuration)) ) { // reset the object count _currentObjectCount = 0; - if (_groupingTimer != null) + if (_groupingTimer is not null) { _groupingTimer.Stop(); _groupingTimer = null; @@ -140,7 +140,7 @@ private void Notify() foreach (PacketInfoData x in _queue) { FormatEntryData fed = x as FormatEntryData; - if (fed != null && fed.outOfBand) + if (fed is not null && fed.outOfBand) continue; validObjects.Add(x); @@ -232,7 +232,7 @@ internal FormattedObjectsCache(bool cacheFrontEnd) /// Max number of objects to be cached. internal void EnableGroupCaching(ProcessCachedGroupNotification callBack, int objectCount) { - if (callBack != null) + if (callBack is not null) _groupQueue = new OutputGroupQueue(callBack, objectCount); } @@ -243,7 +243,7 @@ internal void EnableGroupCaching(ProcessCachedGroupNotification callBack, int ob /// Max amount of time to cache of objects. internal void EnableGroupCaching(ProcessCachedGroupNotification callBack, TimeSpan groupingDuration) { - if (callBack != null) + if (callBack is not null) _groupQueue = new OutputGroupQueue(callBack, groupingDuration); } @@ -264,7 +264,7 @@ internal List Add(PacketInfoData o) } // if front present, add to front - if (_frontEndQueue != null) + if (_frontEndQueue is not null) { _frontEndQueue.Enqueue(o); return null; @@ -288,7 +288,7 @@ internal List Drain() List retVal = new List(); - if (_frontEndQueue != null) + if (_frontEndQueue is not null) { if (_groupQueue is null) { @@ -304,7 +304,7 @@ internal List Drain() { List groupQueueOut = _groupQueue.Add(_frontEndQueue.Dequeue()); - if (groupQueueOut != null) + if (groupQueueOut is not null) foreach (PacketInfoData x in groupQueueOut) retVal.Add(x); } diff --git a/src/System.Management.Automation/FormatAndOutput/common/TableWriter.cs b/src/System.Management.Automation/FormatAndOutput/common/TableWriter.cs index e01be6f5b8c..3fc17b33e2a 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/TableWriter.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/TableWriter.cs @@ -151,7 +151,7 @@ internal int GenerateHeader(string[] values, LineOutput lo) { return 0; } - else if (_header != null) + else if (_header is not null) { foreach (string line in _header) { diff --git a/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshObjectUtil.cs b/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshObjectUtil.cs index 8c1b2cce39f..a2e047a4b58 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshObjectUtil.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshObjectUtil.cs @@ -46,7 +46,7 @@ internal static PSPropertyExpression GetDisplayNameExpression(PSObject target, P { // first try to get the expression from the object (types.ps1xml data) PSPropertyExpression expressionFromObject = GetDefaultNameExpression(target); - if (expressionFromObject != null) + if (expressionFromObject is not null) { return expressionFromObject; } @@ -99,7 +99,7 @@ internal static PSPropertyExpressionResult GetDisplayName(PSObject target, PSPro // evaluate the expression List resList = ex.GetValues(target); - if (resList.Count == 0 || resList[0].Exception != null) + if (resList.Count == 0 || resList[0].Exception is not null) { // no results or the retrieval on the first one failed return null; @@ -115,7 +115,7 @@ internal static PSPropertyExpressionResult GetDisplayName(PSObject target, PSPro internal static IEnumerable GetEnumerable(object obj) { PSObject mshObj = obj as PSObject; - if (mshObj != null) + if (mshObj is not null) { obj = mshObj.BaseObject; } @@ -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 is not null) && (r.Exception is null)) { return PSObjectHelper.AsPSObject(r.Result).ToString(); } @@ -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 is not null) && (r.Exception is null)) { objName = PSObjectHelper.AsPSObject(r.Result).ToString(); } @@ -181,7 +181,7 @@ private static string GetObjectName(object x, PSPropertyExpressionFactory expres if (objName == string.Empty) { var baseObj = PSObject.Base(x); - if (baseObj != null) + if (baseObj is not null) { objName = baseObj.ToString(); } @@ -210,7 +210,7 @@ internal static string SmartToString(PSObject so, PSPropertyExpressionFactory ex try { IEnumerable e = PSObjectHelper.GetEnumerable(so); - if (e != null) + if (e is not null) { StringBuilder sb = new StringBuilder(); sb.Append("{"); @@ -218,10 +218,10 @@ internal static string SmartToString(PSObject so, PSPropertyExpressionFactory ex bool first = true; int enumCount = 0; IEnumerator enumerator = e.GetEnumerator(); - if (enumerator != null) + if (enumerator is not null) { IBlockingEnumerator be = enumerator as IBlockingEnumerator; - if (be != null) + if (be is not null) { while (be.MoveNext(false)) { @@ -294,7 +294,7 @@ internal static string SmartToString(PSObject so, PSPropertyExpressionFactory ex { // NOTE: we catch all the exceptions, since we do not know // what the underlying object access would throw - if (formatErrorObject != null) + if (formatErrorObject is not null) { formatErrorObject.sourceObject = so; formatErrorObject.exception = e; @@ -324,7 +324,7 @@ internal static string FormatField(FieldFormattingDirective directive, object va StringFormatError formatErrorObject, PSPropertyExpressionFactory expressionFactory) { PSObject so = PSObjectHelper.AsPSObject(val); - if (directive != null && !string.IsNullOrEmpty(directive.formatString)) + if (directive is not null && !string.IsNullOrEmpty(directive.formatString)) { // we have a formatting directive, apply it // NOTE: with a format directive, we do not make any attempt @@ -348,7 +348,7 @@ internal static string FormatField(FieldFormattingDirective directive, object va { // NOTE: we catch all the exceptions, since we do not know // what the underlying object access would throw - if (formatErrorObject != null) + if (formatErrorObject is not null) { formatErrorObject.sourceObject = so; formatErrorObject.exception = e; @@ -365,7 +365,7 @@ internal static string FormatField(FieldFormattingDirective directive, object va private static PSMemberSet MaskDeserializedAndGetStandardMembers(PSObject so) { - Diagnostics.Assert(so != null, "Shell object to process cannot be null"); + Diagnostics.Assert(so is not null, "Shell object to process cannot be null"); var typeNames = so.InternalTypeNames; Collection typeNamesWithoutDeserializedPrefix = Deserializer.MaskDeserializationPrefix(typeNames); if (typeNamesWithoutDeserializedPrefix is null) @@ -386,10 +386,10 @@ private static PSMemberSet MaskDeserializedAndGetStandardMembers(PSObject so) private static List GetDefaultPropertySet(PSMemberSet standardMembersSet) { - if (standardMembersSet != null) + if (standardMembersSet is not null) { PSPropertySet defaultDisplayPropertySet = standardMembersSet.Members[TypeTable.DefaultDisplayPropertySet] as PSPropertySet; - if (defaultDisplayPropertySet != null) + if (defaultDisplayPropertySet is not null) { List retVal = new List(); foreach (string prop in defaultDisplayPropertySet.ReferencedPropertyNames) @@ -425,10 +425,10 @@ internal static List GetDefaultPropertySet(PSObject so) private static PSPropertyExpression GetDefaultNameExpression(PSMemberSet standardMembersSet) { - if (standardMembersSet != null) + if (standardMembersSet is not null) { PSNoteProperty defaultDisplayProperty = standardMembersSet.Members[TypeTable.DefaultDisplayProperty] as PSNoteProperty; - if (defaultDisplayProperty != null) + if (defaultDisplayProperty is not null) { string expressionString = defaultDisplayProperty.Value.ToString(); if (string.IsNullOrEmpty(expressionString)) @@ -483,7 +483,7 @@ internal static string GetExpressionDisplayValue( } result = resList[0]; - if (result.Exception != null) + if (result.Exception is not null) { return string.Empty; } @@ -499,7 +499,7 @@ internal static string GetExpressionDisplayValue( internal static bool ShouldShowComputerNameProperty(PSObject so) { bool result = false; - if (so != null) + if (so is not null) { try { @@ -508,7 +508,7 @@ internal static bool ShouldShowComputerNameProperty(PSObject so) // if computer name property exists then this must be a remote object. see // if it can be displayed. - if ((computerNameProperty != null) && (showComputerNameProperty != null)) + if ((computerNameProperty is not null) && (showComputerNameProperty is not null)) { LanguagePrimitives.TryConvertTo(showComputerNameProperty.Value, out result); } @@ -581,7 +581,7 @@ internal PSPropertyExpression CreateFromExpressionToken(ExpressionToken et, Data if (et.isScriptBlock) { // we cache script blocks from expression tokens - if (_expressionCache != null) + if (_expressionCache is not null) { PSPropertyExpression value; if (_expressionCache.TryGetValue(et, out value)) @@ -597,7 +597,7 @@ internal PSPropertyExpression CreateFromExpressionToken(ExpressionToken et, Data bool isFullyTrusted = false; bool isProductCode = false; - if (loadingInfo != null) + if (loadingInfo is not null) { isFullyTrusted = loadingInfo.isFullyTrusted; isProductCode = loadingInfo.isProductCode; diff --git a/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameter.cs b/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameter.cs index f5b7a898a5f..8f90b3f6f1b 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameter.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameter.cs @@ -78,7 +78,7 @@ internal bool IsKeyMatch(string key) return true; } - if (this.SecondaryNames != null) + if (this.SecondaryNames is not null) { foreach (string secondaryKey in this.SecondaryNames) { @@ -163,7 +163,7 @@ internal HashtableEntryDefinition MatchEntry(string keyName, TerminatingErrorCon } } - if (matchingEntry != null) + if (matchingEntry is not null) { // we found an unambiguous match return matchingEntry; @@ -270,7 +270,7 @@ internal List ProcessParameters(object[] p, TerminatingErrorContex originalParameterWasHashTable = true; currParam.hash = VerifyHashTable((IDictionary)actualObject, invocationContext); } - else if ((actualObject != null) && MatchesAllowedTypes(actualObject.GetType(), _paramDef.hashEntries[0].AllowedTypes)) + else if ((actualObject is not null) && MatchesAllowedTypes(actualObject.GetType(), _paramDef.hashEntries[0].AllowedTypes)) { // a simple type was specified, build a hash with one entry currParam.hash = _paramDef.hashEntries[0].CreateHashtableFromSingleType(actualObject); @@ -381,7 +381,7 @@ private void VerifyAndNormalizeParameter(MshParameter parameter, object val = parameter.hash[_paramDef.hashEntries[k].KeyName]; object newVal = _paramDef.hashEntries[k].Verify(val, invocationContext, originalParameterWasHashTable); - if (newVal != null) + if (newVal is not null) { // if a new value is provided, we need to update the hash entry parameter.hash[_paramDef.hashEntries[k].KeyName] = newVal; @@ -413,7 +413,7 @@ private static void ProcessUnknownParameterType(TerminatingErrorContext invocati string allowedTypesList = CatenateTypeArray(allowedTypes); string msg; - if (actualObject != null) + if (actualObject is not null) { msg = StringUtil.Format(FormatAndOut_MshParameter.UnknownParameterTypeError, actualObject.GetType().FullName, allowedTypesList); diff --git a/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameterAssociation.cs b/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameterAssociation.cs index f2fe89111b4..8e895a77cf4 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameterAssociation.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameterAssociation.cs @@ -40,7 +40,7 @@ internal static List SetupActivePrope PSObject target, PSPropertyExpressionFactory expressionFactory) { // check if we received properties from the command line - if (rawMshParameterList != null && rawMshParameterList.Count > 0) + if (rawMshParameterList is not null && rawMshParameterList.Count > 0) { return AssociationManager.ExpandParameters(rawMshParameterList, target); } @@ -181,7 +181,7 @@ internal static List ExpandAll(PSObje /// internal static void HandleComputerNameProperties(PSObject so, List activeAssociationList) { - if (so.Properties[RemotingConstants.ShowComputerNameNoteProperty] != null) + if (so.Properties[RemotingConstants.ShowComputerNameNoteProperty] is not null) { // always remove PSShowComputerName for the display. This is an internal property // that should never be visible to the user. @@ -200,7 +200,7 @@ internal static void HandleComputerNameProperties(PSObject so, List In this case we want to show // PSComputerName - if ((so.Properties[RemotingConstants.ComputerNameNoteProperty] != null) && + if ((so.Properties[RemotingConstants.ComputerNameNoteProperty] is not null) && (!PSObjectHelper.ShouldShowComputerNameProperty(so))) { foreach (MshResolvedExpressionParameterAssociation cpProp in activeAssociationList) diff --git a/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs b/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs index 36363ed6381..4e69769113c 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs @@ -104,7 +104,7 @@ public PSPropertyExpression(ScriptBlock scriptBlock) /// public override string ToString() { - if (Script != null) + if (Script is not null) return Script.ToString(); return _stringValue; @@ -127,7 +127,7 @@ public bool HasWildCardCharacters { get { - if (Script != null) + if (Script is not null) return false; return WildcardPattern.ContainsWildcardCharacters(_stringValue); } @@ -148,7 +148,7 @@ public List ResolveNames(PSObject target, bool expand) return retVal; } - if (Script != null) + if (Script is not null) { // script block, just add it to the list and be done PSPropertyExpression ex = new PSPropertyExpression(Script); @@ -200,7 +200,7 @@ public List ResolveNames(PSObject target, bool expand) } List temp = new List(); - if (x != null) + if (x is not null) { temp.Add(x); } @@ -216,7 +216,7 @@ public List ResolveNames(PSObject target, bool expand) { // it can be a property set PSPropertySet propertySet = member as PSPropertySet; - if (propertySet != null) + if (propertySet is not null) { if (expand) { @@ -287,7 +287,7 @@ public List GetValues(PSObject target, bool expand, List retVal = new List(); // process the script case - if (Script != null) + if (Script is not null) { PSPropertyExpression scriptExpression = new PSPropertyExpression(Script); PSPropertyExpressionResult r = scriptExpression.GetValue(target, eatExceptions); @@ -314,7 +314,7 @@ private PSPropertyExpressionResult GetValue(PSObject target, bool eatExceptions) { object result = null; - if (Script != null) + if (Script is not null) { result = Script.DoInvokeReturnAsIs( useLocalScope: true, diff --git a/src/System.Management.Automation/FormatAndOutput/out-console/ConsoleLineOutput.cs b/src/System.Management.Automation/FormatAndOutput/out-console/ConsoleLineOutput.cs index 7866c02e512..561deabc07a 100644 --- a/src/System.Management.Automation/FormatAndOutput/out-console/ConsoleLineOutput.cs +++ b/src/System.Management.Automation/FormatAndOutput/out-console/ConsoleLineOutput.cs @@ -233,7 +233,7 @@ internal override DisplayCells DisplayCells get { CheckStopProcessing(); - if (_displayCellsPSHost != null) + if (_displayCellsPSHost is not null) { return _displayCellsPSHost; } @@ -269,7 +269,7 @@ internal ConsoleLineOutput(PSHostUserInterface hostConsole, bool paging, Termina } PSHostRawUserInterface raw = _console.RawUI; - if (raw != null) + if (raw is not null) { tracer.WriteLine("there is a valid raw interface"); #if TEST_MULTICELL_ON_SINGLE_CELL_LOCALE diff --git a/src/System.Management.Automation/FormatAndOutput/out-console/OutConsole.cs b/src/System.Management.Automation/FormatAndOutput/out-console/OutConsole.cs index e7afeda5e15..6991cd130a5 100644 --- a/src/System.Management.Automation/FormatAndOutput/out-console/OutConsole.cs +++ b/src/System.Management.Automation/FormatAndOutput/out-console/OutConsole.cs @@ -72,7 +72,7 @@ protected override void BeginProcessing() MshCommandRuntime mrt = this.CommandRuntime as MshCommandRuntime; - if (mrt != null) + if (mrt is not null) { mrt.MergeUnclaimedPreviousErrorResults = true; } @@ -86,7 +86,7 @@ protected override void BeginProcessing() // doesn't actually write pipeline objects. base.BeginProcessing(); - if (Context.CurrentCommandProcessor.CommandRuntime.OutVarList != null) + if (Context.CurrentCommandProcessor.CommandRuntime.OutVarList is not null) { _outVarResults = new List(); } @@ -104,13 +104,13 @@ protected override void ProcessRecord() // This needs to be done directly through the command runtime, as Out-Default // doesn't actually write pipeline objects. - if (_outVarResults != null) + if (_outVarResults is not null) { object inputObjectBase = PSObject.Base(InputObject); // Ignore errors and formatting records, as those can't be captured if ( - (inputObjectBase != null) && + (inputObjectBase is not null) && (!(inputObjectBase is ErrorRecord)) && (!inputObjectBase.GetType().FullName.StartsWith( "Microsoft.PowerShell.Commands.Internal.Format", StringComparison.OrdinalIgnoreCase))) @@ -129,7 +129,7 @@ protected override void EndProcessing() { // This needs to be done directly through the command runtime, as Out-Default // doesn't actually write pipeline objects. - if ((_outVarResults != null) && (_outVarResults.Count > 0)) + if ((_outVarResults is not null) && (_outVarResults.Count > 0)) { Context.CurrentCommandProcessor.CommandRuntime.OutVarList.Clear(); foreach (object item in _outVarResults) @@ -154,7 +154,7 @@ protected override void InternalDispose() } finally { - if (_transcribeOnlyCookie != null) + if (_transcribeOnlyCookie is not null) { _transcribeOnlyCookie.Dispose(); _transcribeOnlyCookie = null; diff --git a/src/System.Management.Automation/cimSupport/cmdletization/EnumWriter.cs b/src/System.Management.Automation/cimSupport/cmdletization/EnumWriter.cs index 23c7a09c4f2..673c7128e10 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/EnumWriter.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/EnumWriter.cs @@ -36,7 +36,7 @@ internal static void Compile(EnumMetadataEnum enumMetadata) string fullEnumName = GetEnumFullName(enumMetadata); Type underlyingType; - if (enumMetadata.UnderlyingType != null) + if (enumMetadata.UnderlyingType is not null) { underlyingType = (Type)LanguagePrimitives.ConvertTo(enumMetadata.UnderlyingType, typeof(Type), CultureInfo.InvariantCulture); } diff --git a/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs b/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs index 2062092b79d..a3ebccb863e 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs @@ -63,19 +63,19 @@ internal IEnumerable GetArgumentsOfType() where T : class } var objectInstance = methodParameter.Value as T; - if (objectInstance != null) + if (objectInstance is not null) { result.Add(objectInstance); continue; } var objectInstanceArray = methodParameter.Value as IEnumerable; - if (objectInstanceArray != null) + if (objectInstanceArray is not null) { foreach (object element in objectInstanceArray) { var objectInstance2 = element as T; - if (objectInstance2 != null) + if (objectInstance2 is not null) { result.Add(objectInstance2); } diff --git a/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs b/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs index d33c8223e94..6d76caa509a 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs @@ -43,14 +43,14 @@ internal void Initialize(PSCmdlet cmdlet, string className, string classVersion, _privateData = privateData; var compiledScript = this.Cmdlet as PSScriptCmdlet; - if (compiledScript != null) + if (compiledScript is not null) { compiledScript.StoppingEvent += delegate { this.StopProcessing(); }; compiledScript.DisposingEvent += delegate { var disposable = this as IDisposable; - if (disposable != null) + if (disposable is not null) { disposable.Dispose(); } diff --git a/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs b/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs index 0609e62a853..529538be178 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs @@ -87,10 +87,10 @@ internal ScriptWriter( InvocationInfo invocationInfo, GenerationOptions generationOptions) { - Dbg.Assert(cmdletizationXmlReader != null, "Caller should verify that cmdletizationXmlReader != null"); - Dbg.Assert(!string.IsNullOrEmpty(moduleName), "Caller should verify that moduleName != null"); - Dbg.Assert(invocationInfo != null, "Caller should verify that invocationInfo != null"); - Dbg.Assert(!string.IsNullOrEmpty(defaultObjectModelWrapper), "Caller should verify that defaultObjectModelWrapper != null"); + Dbg.Assert(cmdletizationXmlReader is not null, "Caller should verify that cmdletizationXmlReader is not null"); + Dbg.Assert(!string.IsNullOrEmpty(moduleName), "Caller should verify that moduleName is not null"); + Dbg.Assert(invocationInfo is not null, "Caller should verify that invocationInfo is not null"); + Dbg.Assert(!string.IsNullOrEmpty(defaultObjectModelWrapper), "Caller should verify that defaultObjectModelWrapper is not null"); XmlReader xmlReader = XmlReader.Create(cmdletizationXmlReader, ScriptWriter.s_xmlReaderSettings); try @@ -101,18 +101,18 @@ internal ScriptWriter( catch (InvalidOperationException e) { XmlSchemaException schemaException = e.InnerException as XmlSchemaException; - if (schemaException != null) + if (schemaException is not null) { throw new XmlException(schemaException.Message, schemaException, schemaException.LineNumber, schemaException.LinePosition); } XmlException xmlException = e.InnerException as XmlException; - if (xmlException != null) + if (xmlException is not null) { throw xmlException; } - if (e.InnerException != null) + if (e.InnerException is not null) { string message = string.Format( CultureInfo.CurrentCulture, @@ -189,7 +189,7 @@ private void WriteModulePreamble(TextWriter output) CodeGeneration.EscapeSingleQuotedStringContent(new Version(_cmdletizationMetadata.Class.Version).ToString()), CodeGeneration.EscapeSingleQuotedStringContent(_objectModelWrapper.FullName)); - if (_cmdletizationMetadata.Class.CmdletAdapterPrivateData != null) + if (_cmdletizationMetadata.Class.CmdletAdapterPrivateData is not null) { foreach (ClassMetadataData data in _cmdletizationMetadata.Class.CmdletAdapterPrivateData) { @@ -238,14 +238,14 @@ private string GetCmdletAttributes(CommonCmdletMetadata cmdletMetadata) { // Generate the script for the Alias and Obsolete Attribute if any is declared in CDXML StringBuilder attributes = new StringBuilder(150); - if (cmdletMetadata.Aliases != null) + if (cmdletMetadata.Aliases is not null) { attributes.Append("[Alias('" + string.Join("','", cmdletMetadata.Aliases.Select(alias => CodeGeneration.EscapeSingleQuotedStringContent(alias))) + "')]"); } - if (cmdletMetadata.Obsolete != null) + if (cmdletMetadata.Obsolete is not null) { - string obsoleteMsg = (cmdletMetadata.Obsolete.Message != null) + string obsoleteMsg = (cmdletMetadata.Obsolete.Message is not null) ? ("'" + CodeGeneration.EscapeSingleQuotedStringContent(cmdletMetadata.Obsolete.Message) + "'") : string.Empty; string newline = (attributes.Length > 0) ? Environment.NewLine : string.Empty; @@ -359,7 +359,7 @@ private static List GetCommonParameterSets(Dictionary GetMethodParameterSets(StaticCmdletMetadata staticCmdlet) private string GetMethodParameterSet(CommonMethodMetadata methodMetadata) { - Dbg.Assert(methodMetadata != null, "Caller should verify that instanceMethod != null"); + Dbg.Assert(methodMetadata is not null, "Caller should verify that instanceMethod is not null"); int uniqueId; if (!_staticMethodMetadataToUniqueId.TryGetValue(methodMetadata, out uniqueId)) @@ -417,15 +417,15 @@ private GetCmdletParameters GetGetCmdletParameters(InstanceCmdletMetadata instan { if (instanceCmdlet is null) { - if ((_cmdletizationMetadata.Class.InstanceCmdlets.GetCmdlet != null) && - (_cmdletizationMetadata.Class.InstanceCmdlets.GetCmdlet.GetCmdletParameters != null)) + if ((_cmdletizationMetadata.Class.InstanceCmdlets.GetCmdlet is not null) && + (_cmdletizationMetadata.Class.InstanceCmdlets.GetCmdlet.GetCmdletParameters is not null)) { return _cmdletizationMetadata.Class.InstanceCmdlets.GetCmdlet.GetCmdletParameters; } } else { - if (instanceCmdlet.GetCmdletParameters != null) + if (instanceCmdlet.GetCmdletParameters is not null) { return instanceCmdlet.GetCmdletParameters; } @@ -442,16 +442,16 @@ private List GetQueryParameterSets(InstanceCmdletMetadata instanceCmdlet bool anyQueryParameters = false; GetCmdletParameters getCmdletParameters = GetGetCmdletParameters(instanceCmdlet); - if (getCmdletParameters.QueryableProperties != null) + if (getCmdletParameters.QueryableProperties is not null) { foreach (PropertyMetadata property in getCmdletParameters.QueryableProperties) { - if (property.Items != null) + if (property.Items is not null) { foreach (PropertyQuery query in property.Items) { anyQueryParameters = true; - if (query.CmdletParameterMetadata != null) + if (query.CmdletParameterMetadata is not null) { parameters.Add(query.CmdletParameterMetadata); } @@ -460,14 +460,14 @@ private List GetQueryParameterSets(InstanceCmdletMetadata instanceCmdlet } } - if (getCmdletParameters.QueryableAssociations != null) + if (getCmdletParameters.QueryableAssociations is not null) { foreach (Association association in getCmdletParameters.QueryableAssociations) { - if (association.AssociatedInstance != null) + if (association.AssociatedInstance is not null) { anyQueryParameters = true; - if (association.AssociatedInstance.CmdletParameterMetadata != null) + if (association.AssociatedInstance.CmdletParameterMetadata is not null) { parameters.Add(association.AssociatedInstance.CmdletParameterMetadata); } @@ -475,12 +475,12 @@ private List GetQueryParameterSets(InstanceCmdletMetadata instanceCmdlet } } - if (getCmdletParameters.QueryOptions != null) + if (getCmdletParameters.QueryOptions is not null) { foreach (QueryOption option in getCmdletParameters.QueryOptions) { anyQueryParameters = true; - if (option.CmdletParameterMetadata != null) + if (option.CmdletParameterMetadata is not null) { parameters.Add(option.CmdletParameterMetadata); } @@ -489,7 +489,7 @@ private List GetQueryParameterSets(InstanceCmdletMetadata instanceCmdlet foreach (CmdletParameterMetadataForGetCmdletParameter parameter in parameters) { - if (parameter.CmdletParameterSets != null) + if (parameter.CmdletParameterSets is not null) { foreach (string parameterSetName in parameter.CmdletParameterSets) { @@ -504,7 +504,7 @@ private List GetQueryParameterSets(InstanceCmdletMetadata instanceCmdlet getCmdletParameters.DefaultCmdletParameterSet = ScriptWriter.SingleQueryParameterSetName; } - if (instanceCmdlet != null) + if (instanceCmdlet is not null) { parameterSetNames.Add(ScriptWriter.InputObjectQueryParameterSetName, null); } @@ -514,7 +514,7 @@ private List GetQueryParameterSets(InstanceCmdletMetadata instanceCmdlet private Type GetDotNetType(TypeMetadata typeMetadata) { - Dbg.Assert(typeMetadata != null, "Caller should verify typeMetadata != null"); + Dbg.Assert(typeMetadata is not null, "Caller should verify typeMetadata is not null"); string psTypeText; List matchingEnums = (_cmdletizationMetadata.Enums ?? Enumerable.Empty()) @@ -524,7 +524,7 @@ private Type GetDotNetType(TypeMetadata typeMetadata) RegexOptions.CultureInvariant)) .ToList(); EnumMetadataEnum matchingEnum = matchingEnums.Count == 1 ? matchingEnums[0] : null; - if (matchingEnum != null) + if (matchingEnum is not null) { psTypeText = typeMetadata.PSType.Replace(matchingEnum.EnumName, EnumWriter.GetEnumFullName(matchingEnum)); } @@ -546,7 +546,7 @@ private ParameterMetadata GetParameter( bool isValueFromPipelineByPropertyName) { string parameterName; - if ((parameterCmdletization != null) && (!string.IsNullOrEmpty(parameterCmdletization.PSName))) + if ((parameterCmdletization is not null) && (!string.IsNullOrEmpty(parameterCmdletization.PSName))) { parameterName = parameterCmdletization.PSName; } @@ -562,14 +562,14 @@ private ParameterMetadata GetParameter( parameterMetadata.Attributes.Add(new CredentialAttribute()); } - if (parameterTypeMetadata.ETSType != null) + if (parameterTypeMetadata.ETSType is not null) { parameterMetadata.Attributes.Add(new PSTypeNameAttribute(parameterTypeMetadata.ETSType)); } - if (parameterCmdletization != null) + if (parameterCmdletization is not null) { - if (parameterCmdletization.Aliases != null) + if (parameterCmdletization.Aliases is not null) { foreach (string alias in parameterCmdletization.Aliases) { @@ -580,52 +580,52 @@ private ParameterMetadata GetParameter( } } - if (parameterCmdletization.AllowEmptyCollection != null) + if (parameterCmdletization.AllowEmptyCollection is not null) { parameterMetadata.Attributes.Add(new AllowEmptyCollectionAttribute()); } - if (parameterCmdletization.AllowEmptyString != null) + if (parameterCmdletization.AllowEmptyString is not null) { parameterMetadata.Attributes.Add(new AllowEmptyStringAttribute()); } - if (parameterCmdletization.AllowNull != null) + if (parameterCmdletization.AllowNull is not null) { parameterMetadata.Attributes.Add(new AllowNullAttribute()); } - if (parameterCmdletization.ValidateCount != null) + if (parameterCmdletization.ValidateCount is not null) { int min = (int)LanguagePrimitives.ConvertTo(parameterCmdletization.ValidateCount.Min, typeof(int), CultureInfo.InvariantCulture); int max = (int)LanguagePrimitives.ConvertTo(parameterCmdletization.ValidateCount.Max, typeof(int), CultureInfo.InvariantCulture); parameterMetadata.Attributes.Add(new ValidateCountAttribute(min, max)); } - if (parameterCmdletization.ValidateLength != null) + if (parameterCmdletization.ValidateLength is not null) { int min = (int)LanguagePrimitives.ConvertTo(parameterCmdletization.ValidateLength.Min, typeof(int), CultureInfo.InvariantCulture); int max = (int)LanguagePrimitives.ConvertTo(parameterCmdletization.ValidateLength.Max, typeof(int), CultureInfo.InvariantCulture); parameterMetadata.Attributes.Add(new ValidateLengthAttribute(min, max)); } - if (parameterCmdletization.Obsolete != null) + if (parameterCmdletization.Obsolete is not null) { string obsoleteMessage = parameterCmdletization.Obsolete.Message; - parameterMetadata.Attributes.Add(obsoleteMessage != null ? new ObsoleteAttribute(obsoleteMessage) : new ObsoleteAttribute()); + parameterMetadata.Attributes.Add(obsoleteMessage is not null ? new ObsoleteAttribute(obsoleteMessage) : new ObsoleteAttribute()); } - if (parameterCmdletization.ValidateNotNull != null) + if (parameterCmdletization.ValidateNotNull is not null) { parameterMetadata.Attributes.Add(new ValidateNotNullAttribute()); } - if (parameterCmdletization.ValidateNotNullOrEmpty != null) + if (parameterCmdletization.ValidateNotNullOrEmpty is not null) { parameterMetadata.Attributes.Add(new ValidateNotNullOrEmptyAttribute()); } - if (parameterCmdletization.ValidateRange != null) + if (parameterCmdletization.ValidateRange is not null) { Type parameterType = parameterMetadata.ParameterType; Type elementType; @@ -643,7 +643,7 @@ private ParameterMetadata GetParameter( parameterMetadata.Attributes.Add(new ValidateRangeAttribute(min, max)); } - if (parameterCmdletization.ValidateSet != null) + if (parameterCmdletization.ValidateSet is not null) { List allowedValues = new List(); foreach (string allowedValue in parameterCmdletization.ValidateSet) @@ -657,7 +657,7 @@ private ParameterMetadata GetParameter( int position = int.MinValue; ParameterSetMetadata.ParameterFlags parameterFlags = 0; - if (parameterCmdletization != null) + if (parameterCmdletization is not null) { if (!string.IsNullOrEmpty(parameterCmdletization.Position)) { @@ -697,7 +697,7 @@ private ParameterMetadata GetParameter( parameterType, parameterCmdletization, false, /* isValueFromPipeline */ - parameterCmdletization != null && parameterCmdletization.ValueFromPipelineByPropertyNameSpecified && parameterCmdletization.ValueFromPipelineByPropertyName); + parameterCmdletization is not null && parameterCmdletization.ValueFromPipelineByPropertyNameSpecified && parameterCmdletization.ValueFromPipelineByPropertyName); } private ParameterMetadata GetParameter( @@ -711,12 +711,12 @@ private ParameterMetadata GetParameter( objectModelParameterName, parameterType, parameterCmdletization, - parameterCmdletization != null && parameterCmdletization.ValueFromPipelineSpecified && parameterCmdletization.ValueFromPipeline, - parameterCmdletization != null && parameterCmdletization.ValueFromPipelineByPropertyNameSpecified && parameterCmdletization.ValueFromPipelineByPropertyName); + parameterCmdletization is not null && parameterCmdletization.ValueFromPipelineSpecified && parameterCmdletization.ValueFromPipeline, + parameterCmdletization is not null && parameterCmdletization.ValueFromPipelineByPropertyNameSpecified && parameterCmdletization.ValueFromPipelineByPropertyName); ParameterSetMetadata parameterSetMetadata = result.ParameterSets[ParameterAttribute.AllParameterSets]; result.ParameterSets.Clear(); - if (parameterCmdletization != null && parameterCmdletization.CmdletParameterSets != null && parameterCmdletization.CmdletParameterSets.Length > 0) + if (parameterCmdletization is not null && parameterCmdletization.CmdletParameterSets is not null && parameterCmdletization.CmdletParameterSets.Length > 0) { queryParameterSets = parameterCmdletization.CmdletParameterSets; } @@ -745,8 +745,8 @@ private ParameterMetadata GetParameter( objectModelParameterName, parameterType, parameterCmdletization, - parameterCmdletization != null && parameterCmdletization.ValueFromPipelineSpecified && parameterCmdletization.ValueFromPipeline, - parameterCmdletization != null && parameterCmdletization.ValueFromPipelineByPropertyNameSpecified && parameterCmdletization.ValueFromPipelineByPropertyName); + parameterCmdletization is not null && parameterCmdletization.ValueFromPipelineSpecified && parameterCmdletization.ValueFromPipeline, + parameterCmdletization is not null && parameterCmdletization.ValueFromPipelineByPropertyNameSpecified && parameterCmdletization.ValueFromPipelineByPropertyName); } private void SetParameters(CommandMetadata commandMetadata, params Dictionary[] allParameters) @@ -789,7 +789,7 @@ private CommandMetadata GetCommandMetadata(CommonCmdletMetadata cmdletMetadata) { string defaultParameterSetName = null; StaticCmdletMetadataCmdletMetadata staticCmdletMetadata = cmdletMetadata as StaticCmdletMetadataCmdletMetadata; - if (staticCmdletMetadata != null) + if (staticCmdletMetadata is not null) { if (!string.IsNullOrEmpty(staticCmdletMetadata.DefaultCmdletParameterSet)) { @@ -827,7 +827,7 @@ private CommandMetadata GetCommandMetadata(CommonCmdletMetadata cmdletMetadata) private static string EscapeModuleNameForHelpComment(string name) { - Dbg.Assert(name != null, "Caller should verify name != null"); + Dbg.Assert(name is not null, "Caller should verify name is not null"); StringBuilder result = new StringBuilder(name.Length); foreach (char c in name) @@ -845,7 +845,7 @@ private static string EscapeModuleNameForHelpComment(string name) private static List> GetCombinations(params IEnumerable[] x) { - Dbg.Assert(x != null, "Caller to verify that x != null"); + Dbg.Assert(x is not null, "Caller to verify that x is not null"); Dbg.Assert(x.Length > 0, "Caller to verify that x.Length > 0"); if (x.Length == 1) @@ -981,15 +981,15 @@ private static IEnumerable MultiplyParameterSets( private static MethodParameterBindings GetMethodParameterKind(InstanceMethodParameterMetadata methodParameter) { - Dbg.Assert(methodParameter != null, "Caller should verify methodParameter != null"); + Dbg.Assert(methodParameter is not null, "Caller should verify methodParameter is not null"); MethodParameterBindings bindings = 0; - if (methodParameter.CmdletParameterMetadata != null) + if (methodParameter.CmdletParameterMetadata is not null) { bindings |= MethodParameterBindings.In; } - if (methodParameter.CmdletOutputMetadata != null) + if (methodParameter.CmdletOutputMetadata is not null) { if (methodParameter.CmdletOutputMetadata.ErrorCode is null) { @@ -1006,15 +1006,15 @@ private static MethodParameterBindings GetMethodParameterKind(InstanceMethodPara private static MethodParameterBindings GetMethodParameterKind(StaticMethodParameterMetadata methodParameter) { - Dbg.Assert(methodParameter != null, "Caller should verify methodParameter != null"); + Dbg.Assert(methodParameter is not null, "Caller should verify methodParameter is not null"); MethodParameterBindings bindings = 0; - if (methodParameter.CmdletParameterMetadata != null) + if (methodParameter.CmdletParameterMetadata is not null) { bindings |= MethodParameterBindings.In; } - if (methodParameter.CmdletOutputMetadata != null) + if (methodParameter.CmdletOutputMetadata is not null) { if (methodParameter.CmdletOutputMetadata.ErrorCode is null) { @@ -1031,10 +1031,10 @@ private static MethodParameterBindings GetMethodParameterKind(StaticMethodParame private static MethodParameterBindings GetMethodParameterKind(CommonMethodMetadataReturnValue returnValue) { - Dbg.Assert(returnValue != null, "Caller should verify returnValue != null"); + Dbg.Assert(returnValue is not null, "Caller should verify returnValue is not null"); MethodParameterBindings bindings = 0; - if (returnValue.CmdletOutputMetadata != null) + if (returnValue.CmdletOutputMetadata is not null) { if (returnValue.CmdletOutputMetadata.ErrorCode is null) { @@ -1059,13 +1059,13 @@ private static void GenerateSingleMethodParameterProcessing( string methodParameterName, MethodParameterBindings methodParameterBindings) { - Dbg.Assert(output != null, "Called should verify output != null"); - Dbg.Assert(prefix != null, "Called should verify output != null"); + Dbg.Assert(output is not null, "Called should verify output is not null"); + Dbg.Assert(prefix is not null, "Called should verify output is not null"); // cmdletParameterName can be null for 'out' parameters string cmdletParameterTypeName = (cmdletParameterType ?? typeof(object)).FullName; - Dbg.Assert(methodParameterName != null, "Caller should verify methodParameterName != null"); + Dbg.Assert(methodParameterName is not null, "Caller should verify methodParameterName is not null"); - if (cmdletParameterDefaultValue != null) + if (cmdletParameterDefaultValue is not null) { output.WriteLine( "{0}[object]$__cmdletization_defaultValue = [System.Management.Automation.LanguagePrimitives]::ConvertTo('{1}', '{2}')", @@ -1088,7 +1088,7 @@ private static void GenerateSingleMethodParameterProcessing( if (MethodParameterBindings.In == (methodParameterBindings & MethodParameterBindings.In)) { - Dbg.Assert(cmdletParameterName != null, "Called should verify cmdletParameterName!=null for 'in' parameters"); + Dbg.Assert(cmdletParameterName is not null, "Called should verify cmdletParameterName!=null for 'in' parameters"); output.WriteLine( "{0}if ($PSBoundParameters.ContainsKey('{1}')) {{", @@ -1172,12 +1172,12 @@ string parameterSetName in List typesOfOutParameters = new List(); List etsTypesOfOutParameters = new List(); - if (method.Parameters != null) + if (method.Parameters is not null) { foreach (StaticMethodParameterMetadata methodParameter in method.Parameters) { string cmdletParameterName = null; - if (methodParameter.CmdletParameterMetadata != null) + if (methodParameter.CmdletParameterMetadata is not null) { string parameterSetName = GetMethodParameterSet(method); ParameterMetadata parameterMetadata = GetParameter( @@ -1230,7 +1230,7 @@ string parameterSetName in } } - if (method.ReturnValue != null) + if (method.ReturnValue is not null) { MethodParameterBindings methodParameterBindings = GetMethodParameterKind(method.ReturnValue); Type dotNetTypeOfParameter = GetDotNetType(method.ReturnValue.Type); @@ -1322,12 +1322,12 @@ private void GenerateMethodParametersProcessing( List typesOfOutParameters = new List(); List etsTypesOfOutParameters = new List(); - if (method.Parameters != null) + if (method.Parameters is not null) { foreach (InstanceMethodParameterMetadata methodParameter in method.Parameters) { string cmdletParameterName = null; - if (methodParameter.CmdletParameterMetadata != null) + if (methodParameter.CmdletParameterMetadata is not null) { ParameterMetadata parameterMetadata = GetParameter( GetMethodParameterSet(method), @@ -1371,7 +1371,7 @@ private void GenerateMethodParametersProcessing( } } - if (method.ReturnValue != null) + if (method.ReturnValue is not null) { MethodParameterBindings methodParameterBindings = GetMethodParameterKind(method.ReturnValue); Type dotNetTypeOfParameter = GetDotNetType(method.ReturnValue.Type); @@ -1479,7 +1479,7 @@ private ParameterMetadata GenerateQueryClause( query.CmdletParameterMetadata); WildcardablePropertyQuery wildcardablePropertyQuery = query as WildcardablePropertyQuery; - if ((wildcardablePropertyQuery != null) && (!cmdletParameterMetadata.SwitchParameter)) + if ((wildcardablePropertyQuery is not null) && (!cmdletParameterMetadata.SwitchParameter)) { if (cmdletParameterMetadata.ParameterType is null) { @@ -1620,9 +1620,9 @@ private void GenerateQueryParametersProcessing( output.WriteLine(" $__cmdletization_queryBuilder = $__cmdletization_objectModelWrapper.GetQueryBuilder()"); GetCmdletParameters getCmdletParameters = GetGetCmdletParameters(instanceCmdlet); - if (getCmdletParameters.QueryableProperties != null) + if (getCmdletParameters.QueryableProperties is not null) { - foreach (PropertyMetadata property in getCmdletParameters.QueryableProperties.Where(p => p.Items != null)) + foreach (PropertyMetadata property in getCmdletParameters.QueryableProperties.Where(p => p.Items is not null)) { for (int i = 0; i < property.Items.Length; i++) { @@ -1679,9 +1679,9 @@ private void GenerateQueryParametersProcessing( } } - if (getCmdletParameters.QueryableAssociations != null) + if (getCmdletParameters.QueryableAssociations is not null) { - foreach (Association association in getCmdletParameters.QueryableAssociations.Where(a => a.AssociatedInstance != null)) + foreach (Association association in getCmdletParameters.QueryableAssociations.Where(a => a.AssociatedInstance is not null)) { ParameterMetadata parameterMetadata = GenerateAssociationClause( commonParameterSets, queryParameterSets, methodParameterSets, association, association.AssociatedInstance, output); @@ -1701,7 +1701,7 @@ private void GenerateQueryParametersProcessing( } } - if (getCmdletParameters.QueryOptions != null) + if (getCmdletParameters.QueryOptions is not null) { foreach (QueryOption queryOption in getCmdletParameters.QueryOptions) { @@ -1723,7 +1723,7 @@ private void GenerateQueryParametersProcessing( } } - if (instanceCmdlet != null) + if (instanceCmdlet is not null) { ParameterMetadata inputObjectParameter = new ParameterMetadata("InputObject", _objectInstanceType.MakeArrayType()); @@ -1878,7 +1878,7 @@ private void WriteCmdlet(TextWriter output, StaticCmdletMetadata staticCmdlet) Dictionary commonParameters = this.GetCommonParameters(); List commonParameterSets = GetCommonParameterSets(commonParameters); - Dbg.Assert(commonParameterSets != null && (commonParameterSets.Count > 0), + Dbg.Assert(commonParameterSets is not null && (commonParameterSets.Count > 0), "Verifying stuff returned by GetCommonParameterSets"); Dictionary methodParameters; @@ -1921,15 +1921,15 @@ private void WriteCmdlet(TextWriter output, StaticCmdletMetadata staticCmdlet) private static void AddPassThruParameter(IDictionary commonParameters, InstanceCmdletMetadata instanceCmdletMetadata) { - Dbg.Assert(commonParameters != null, "Caller should verify commonParameters != null"); - Dbg.Assert(instanceCmdletMetadata != null, "Caller should verify instanceCmdletMetadata != null"); + Dbg.Assert(commonParameters is not null, "Caller should verify commonParameters is not null"); + Dbg.Assert(instanceCmdletMetadata is not null, "Caller should verify instanceCmdletMetadata is not null"); bool outParametersArePresent = false; - if (instanceCmdletMetadata.Method.Parameters != null) + if (instanceCmdletMetadata.Method.Parameters is not null) { foreach (InstanceMethodParameterMetadata parameter in instanceCmdletMetadata.Method.Parameters) { - if ((parameter.CmdletOutputMetadata != null) && (parameter.CmdletOutputMetadata.ErrorCode is null)) + if ((parameter.CmdletOutputMetadata is not null) && (parameter.CmdletOutputMetadata.ErrorCode is null)) { outParametersArePresent = true; break; @@ -1937,9 +1937,9 @@ private static void AddPassThruParameter(IDictionary } } - if (instanceCmdletMetadata.Method.ReturnValue != null) + if (instanceCmdletMetadata.Method.ReturnValue is not null) { - if ((instanceCmdletMetadata.Method.ReturnValue.CmdletOutputMetadata != null) && + if ((instanceCmdletMetadata.Method.ReturnValue.CmdletOutputMetadata is not null) && (instanceCmdletMetadata.Method.ReturnValue.CmdletOutputMetadata.ErrorCode is null)) { outParametersArePresent = true; @@ -2034,9 +2034,9 @@ private string GetOutputAttributeForGetCmdlet() private CommonCmdletMetadata GetGetCmdletMetadata() { - Dbg.Assert(_cmdletizationMetadata.Class.InstanceCmdlets != null, "Caller should verify presence of instance cmdlets"); + Dbg.Assert(_cmdletizationMetadata.Class.InstanceCmdlets is not null, "Caller should verify presence of instance cmdlets"); CommonCmdletMetadata cmdletMetadata; - if (_cmdletizationMetadata.Class.InstanceCmdlets.GetCmdlet != null) + if (_cmdletizationMetadata.Class.InstanceCmdlets.GetCmdlet is not null) { cmdletMetadata = _cmdletizationMetadata.Class.InstanceCmdlets.GetCmdlet.CmdletMetadata; } @@ -2047,7 +2047,7 @@ private CommonCmdletMetadata GetGetCmdletMetadata() cmdletMetadata.Verb = VerbsCommon.Get; } - Dbg.Assert(cmdletMetadata != null, "xsd should ensure that cmdlet metadata element is always present"); + Dbg.Assert(cmdletMetadata is not null, "xsd should ensure that cmdlet metadata element is always present"); return cmdletMetadata; } @@ -2064,7 +2064,7 @@ private void WriteGetCmdlet(TextWriter output) GenerateQueryParametersProcessing(null, commonParameterSets, queryParameterSets, methodParameterSets, out queryProcessingScript, out queryParameters); CommonCmdletMetadata cmdletMetadata = this.GetGetCmdletMetadata(); - Dbg.Assert(cmdletMetadata != null, "xsd should ensure that cmdlet metadata element is always present"); + Dbg.Assert(cmdletMetadata is not null, "xsd should ensure that cmdlet metadata element is always present"); CommandMetadata commandMetadata = this.GetCommandMetadata(cmdletMetadata); string attributeString = this.GetCmdletAttributes(cmdletMetadata); @@ -2133,7 +2133,7 @@ internal void WriteScriptModule(TextWriter output) this.WriteModulePreamble(output); this.WriteBindCommonParametersFunction(output); - if (_cmdletizationMetadata.Enums != null) + if (_cmdletizationMetadata.Enums is not null) { foreach (EnumMetadataEnum enumMetadata in _cmdletizationMetadata.Enums) { @@ -2141,7 +2141,7 @@ internal void WriteScriptModule(TextWriter output) } } - if (_cmdletizationMetadata.Class.StaticCmdlets != null) + if (_cmdletizationMetadata.Class.StaticCmdlets is not null) { foreach (StaticCmdletMetadata staticCmdlet in _cmdletizationMetadata.Class.StaticCmdlets) { @@ -2149,10 +2149,10 @@ internal void WriteScriptModule(TextWriter output) } } - if (_cmdletizationMetadata.Class.InstanceCmdlets != null) + if (_cmdletizationMetadata.Class.InstanceCmdlets is not null) { this.WriteGetCmdlet(output); - if (_cmdletizationMetadata.Class.InstanceCmdlets.Cmdlet != null) + if (_cmdletizationMetadata.Class.InstanceCmdlets.Cmdlet is not null) { foreach (InstanceCmdletMetadata instanceCmdlet in _cmdletizationMetadata.Class.InstanceCmdlets.Cmdlet) { @@ -2196,10 +2196,10 @@ internal void ReportExportedCommands(PSModuleInfo moduleInfo, string prefix) moduleInfo.DeclaredFunctionExports = new Collection(); IEnumerable cmdletMetadatas = Enumerable.Empty(); - if (_cmdletizationMetadata.Class.InstanceCmdlets != null) + if (_cmdletizationMetadata.Class.InstanceCmdlets is not null) { cmdletMetadatas = cmdletMetadatas.Append(this.GetGetCmdletMetadata()); - if (_cmdletizationMetadata.Class.InstanceCmdlets.Cmdlet != null) + if (_cmdletizationMetadata.Class.InstanceCmdlets.Cmdlet is not null) { cmdletMetadatas = cmdletMetadatas.Concat( @@ -2207,7 +2207,7 @@ internal void ReportExportedCommands(PSModuleInfo moduleInfo, string prefix) } } - if (_cmdletizationMetadata.Class.StaticCmdlets != null) + if (_cmdletizationMetadata.Class.StaticCmdlets is not null) { cmdletMetadatas = cmdletMetadatas.Concat( @@ -2216,7 +2216,7 @@ internal void ReportExportedCommands(PSModuleInfo moduleInfo, string prefix) foreach (CommonCmdletMetadata cmdletMetadata in cmdletMetadatas) { - if (cmdletMetadata.Aliases != null) + if (cmdletMetadata.Aliases is not null) { foreach (string alias in cmdletMetadata.Aliases) { 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..eab74a67376 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 @@ -200,7 +200,7 @@ protected XmlDocument Document internal void InitPrimitiveIDs() { - if (_tokenID != null) return; + if (_tokenID is not null) return; object ns = _r.NameTable.Add("http://www.w3.org/2001/XMLSchema"); object ns2 = _r.NameTable.Add("http://microsoft.com/wsdl/types/"); @@ -392,7 +392,7 @@ protected string ReadString(string value, bool trim) // In this case, we use 'ReadContentAsString()' to read the text content at the current position. // We cannot use 'ReadElementContentAsString()'. It will fail because the XmlReader is not positioned on an Element start node. string str = _r.ReadContentAsString(); - if (str != null && trim) + if (str is not null && trim) str = str.Trim(); if (value is null || value.Length == 0) return str; @@ -2266,7 +2266,7 @@ public object Read87_EnumMetadataEnumValue() { if (isNull) { - if (xsiType != null) return (global::System.Object)ReadTypedNull(xsiType); + if (xsiType is not null) return (global::System.Object)ReadTypedNull(xsiType); else return null; } diff --git a/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.xmlSerializer.autogen.cs b/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.xmlSerializer.autogen.cs index f4892b51bc1..3ec33974681 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.xmlSerializer.autogen.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.xmlSerializer.autogen.cs @@ -567,7 +567,7 @@ private void Write48_EnumMetadataEnum(string n, string ns, global::Microsoft.Pow } { global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue[])o.@Value; - if (a != null) + if (a is not null) { for (int ia = 0; ia < a.Length; ia++) { @@ -633,7 +633,7 @@ private void Write47_ClassMetadataData(string n, string ns, global::Microsoft.Po WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(@"ClassMetadataData", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); WriteAttribute(@"Name", @"", ((global::System.String)o.@Name)); - if ((object)(o.@Value) != null) + if ((object)(o.@Value) is not null) { WriteValue(((global::System.String)o.@Value)); } @@ -719,7 +719,7 @@ private void Write12_Item(string n, string ns, global::Microsoft.PowerShell.Cmdl } { global::System.String[] a = (global::System.String[])o.@Aliases; - if (a != null) + if (a is not null) { Writer.WriteStartAttribute(null, @"Aliases", string.Empty); for (int i = 0; i < a.Length; i++) @@ -746,7 +746,7 @@ private void Write12_Item(string n, string ns, global::Microsoft.PowerShell.Cmdl } { global::System.String[] a = (global::System.String[])o.@CmdletParameterSets; - if (a != null) + if (a is not null) { Writer.WriteStartAttribute(null, @"CmdletParameterSets", string.Empty); for (int i = 0; i < a.Length; i++) @@ -775,7 +775,7 @@ private void Write12_Item(string n, string ns, global::Microsoft.PowerShell.Cmdl Write6_Item(@"ValidateRange", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange)o.@ValidateRange), false, false); { global::System.String[] a = (global::System.String[])((global::System.String[])o.@ValidateSet); - if (a != null) + if (a is not null) { WriteStartElement(@"ValidateSet", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); for (int ia = 0; ia < a.Length; ia++) @@ -1117,7 +1117,7 @@ private void Write1_Object(string n, string ns, global::System.Object o, bool is WriteXsiType(@"ArrayOfString", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); { global::System.String[] a = (global::System.String[])o; - if (a != null) + if (a is not null) { for (int ia = 0; ia < a.Length; ia++) { @@ -1135,7 +1135,7 @@ private void Write1_Object(string n, string ns, global::System.Object o, bool is WriteXsiType(@"ArrayOfPropertyMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); { global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata[])o; - if (a != null) + if (a is not null) { for (int ia = 0; ia < a.Length; ia++) { @@ -1153,7 +1153,7 @@ private void Write1_Object(string n, string ns, global::System.Object o, bool is WriteXsiType(@"ArrayOfAssociation", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); { global::Microsoft.PowerShell.Cmdletization.Xml.Association[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.Association[])o; - if (a != null) + if (a is not null) { for (int ia = 0; ia < a.Length; ia++) { @@ -1171,7 +1171,7 @@ private void Write1_Object(string n, string ns, global::System.Object o, bool is WriteXsiType(@"ArrayOfQueryOption", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); { global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[])o; - if (a != null) + if (a is not null) { for (int ia = 0; ia < a.Length; ia++) { @@ -1197,7 +1197,7 @@ private void Write1_Object(string n, string ns, global::System.Object o, bool is WriteXsiType(@"ArrayOfStaticMethodParameterMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); { global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[])o; - if (a != null) + if (a is not null) { for (int ia = 0; ia < a.Length; ia++) { @@ -1215,7 +1215,7 @@ private void Write1_Object(string n, string ns, global::System.Object o, bool is WriteXsiType(@"ArrayOfInstanceMethodParameterMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); { global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata[])o; - if (a != null) + if (a is not null) { for (int ia = 0; ia < a.Length; ia++) { @@ -1233,7 +1233,7 @@ private void Write1_Object(string n, string ns, global::System.Object o, bool is WriteXsiType(@"ArrayOfStaticCmdletMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); { global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata[])o; - if (a != null) + if (a is not null) { for (int ia = 0; ia < a.Length; ia++) { @@ -1251,7 +1251,7 @@ private void Write1_Object(string n, string ns, global::System.Object o, bool is WriteXsiType(@"ArrayOfClassMetadataData", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); { global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[])o; - if (a != null) + if (a is not null) { for (int ia = 0; ia < a.Length; ia++) { @@ -1269,7 +1269,7 @@ private void Write1_Object(string n, string ns, global::System.Object o, bool is WriteXsiType(@"ArrayOfEnumMetadataEnum", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); { global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[])o; - if (a != null) + if (a is not null) { for (int ia = 0; ia < a.Length; ia++) { @@ -1322,7 +1322,7 @@ private void Write38_EnumMetadataEnum(string n, string ns, global::Microsoft.Pow } { global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue[])o.@Value; - if (a != null) + if (a is not null) { for (int ia = 0; ia < a.Length; ia++) { @@ -1361,7 +1361,7 @@ private void Write35_ClassMetadataData(string n, string ns, global::Microsoft.Po WriteStartElement(n, ns, o, false, null); if (needType) WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); WriteAttribute(@"Name", @"", ((global::System.String)o.@Name)); - if ((object)(o.@Value) != null) + if ((object)(o.@Value) is not null) { WriteValue(((global::System.String)o.@Value)); } @@ -1394,7 +1394,7 @@ private void Write34_StaticCmdletMetadata(string n, string ns, global::Microsoft Write33_Item(@"CmdletMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata)o.@CmdletMetadata), false, false); { global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata[])o.@Method; - if (a != null) + if (a is not null) { for (int ia = 0; ia < a.Length; ia++) { @@ -1433,7 +1433,7 @@ private void Write28_StaticMethodMetadata(string n, string ns, global::Microsoft Write24_Item(@"ReturnValue", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue)o.@ReturnValue), false, false); { global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[])((global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[])o.@Parameters); - if (a != null) + if (a is not null) { WriteStartElement(@"Parameters", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); for (int ia = 0; ia < a.Length; ia++) @@ -1533,7 +1533,7 @@ private void Write8_Item(string n, string ns, global::Microsoft.PowerShell.Cmdle } { global::System.String[] a = (global::System.String[])o.@Aliases; - if (a != null) + if (a is not null) { Writer.WriteStartAttribute(null, @"Aliases", string.Empty); for (int i = 0; i < a.Length; i++) @@ -1569,7 +1569,7 @@ private void Write8_Item(string n, string ns, global::Microsoft.PowerShell.Cmdle Write6_Item(@"ValidateRange", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange)o.@ValidateRange), false, false); { global::System.String[] a = (global::System.String[])((global::System.String[])o.@ValidateSet); - if (a != null) + if (a is not null) { WriteStartElement(@"ValidateSet", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); for (int ia = 0; ia < a.Length; ia++) @@ -1677,7 +1677,7 @@ private void Write33_Item(string n, string ns, global::Microsoft.PowerShell.Cmdl WriteAttribute(@"Noun", @"", ((global::System.String)o.@Noun)); { global::System.String[] a = (global::System.String[])o.@Aliases; - if (a != null) + if (a is not null) { Writer.WriteStartAttribute(null, @"Aliases", string.Empty); for (int i = 0; i < a.Length; i++) @@ -1779,7 +1779,7 @@ private void Write9_Item(string n, string ns, global::Microsoft.PowerShell.Cmdle } { global::System.String[] a = (global::System.String[])o.@Aliases; - if (a != null) + if (a is not null) { Writer.WriteStartAttribute(null, @"Aliases", string.Empty); for (int i = 0; i < a.Length; i++) @@ -1810,7 +1810,7 @@ private void Write9_Item(string n, string ns, global::Microsoft.PowerShell.Cmdle Write6_Item(@"ValidateRange", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange)o.@ValidateRange), false, false); { global::System.String[] a = (global::System.String[])((global::System.String[])o.@ValidateSet); - if (a != null) + if (a is not null) { WriteStartElement(@"ValidateSet", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); for (int ia = 0; ia < a.Length; ia++) @@ -1895,7 +1895,7 @@ private void Write11_Item(string n, string ns, global::Microsoft.PowerShell.Cmdl } { global::System.String[] a = (global::System.String[])o.@Aliases; - if (a != null) + if (a is not null) { Writer.WriteStartAttribute(null, @"Aliases", string.Empty); for (int i = 0; i < a.Length; i++) @@ -1922,7 +1922,7 @@ private void Write11_Item(string n, string ns, global::Microsoft.PowerShell.Cmdl } { global::System.String[] a = (global::System.String[])o.@CmdletParameterSets; - if (a != null) + if (a is not null) { Writer.WriteStartAttribute(null, @"CmdletParameterSets", string.Empty); for (int i = 0; i < a.Length; i++) @@ -1946,7 +1946,7 @@ private void Write11_Item(string n, string ns, global::Microsoft.PowerShell.Cmdl Write6_Item(@"ValidateRange", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange)o.@ValidateRange), false, false); { global::System.String[] a = (global::System.String[])((global::System.String[])o.@ValidateSet); - if (a != null) + if (a is not null) { WriteStartElement(@"ValidateSet", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); for (int ia = 0; ia < a.Length; ia++) @@ -2056,7 +2056,7 @@ private void Write15_PropertyMetadata(string n, string ns, global::Microsoft.Pow Write2_TypeMetadata(@"Type", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata)o.@Type), false, false); { global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery[])o.@Items; - if (a != null) + if (a is not null) { global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType[] c = (global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType[])o.@ItemsElementName; if (c == null || c.Length < a.Length) @@ -2069,27 +2069,27 @@ private void Write15_PropertyMetadata(string n, string ns, global::Microsoft.Pow global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery ai = (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery)a[ia]; global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType ci = (global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType)c[ia]; { - if (ci == Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@RegularQuery && ((object)(ai) != null)) + if (ci == Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@RegularQuery && ((object)(ai) is not null)) { - if (((object)ai) != null && !(ai is global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery)) throw CreateMismatchChoiceException(@"Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery", @"ItemsElementName", @"Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@RegularQuery"); + if (((object)ai) is not null && !(ai is global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery)) throw CreateMismatchChoiceException(@"Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery", @"ItemsElementName", @"Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@RegularQuery"); Write13_WildcardablePropertyQuery(@"RegularQuery", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery)ai), false, false); } - else if (ci == Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@ExcludeQuery && ((object)(ai) != null)) + else if (ci == Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@ExcludeQuery && ((object)(ai) is not null)) { - if (((object)ai) != null && !(ai is global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery)) throw CreateMismatchChoiceException(@"Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery", @"ItemsElementName", @"Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@ExcludeQuery"); + if (((object)ai) is not null && !(ai is global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery)) throw CreateMismatchChoiceException(@"Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery", @"ItemsElementName", @"Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@ExcludeQuery"); Write13_WildcardablePropertyQuery(@"ExcludeQuery", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery)ai), false, false); } - else if (ci == Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@MaxValueQuery && ((object)(ai) != null)) + else if (ci == Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@MaxValueQuery && ((object)(ai) is not null)) { - if (((object)ai) != null && !(ai is global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery)) throw CreateMismatchChoiceException(@"Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery", @"ItemsElementName", @"Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@MaxValueQuery"); + if (((object)ai) is not null && !(ai is global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery)) throw CreateMismatchChoiceException(@"Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery", @"ItemsElementName", @"Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@MaxValueQuery"); Write14_PropertyQuery(@"MaxValueQuery", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery)ai), false, false); } - else if (ci == Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@MinValueQuery && ((object)(ai) != null)) + else if (ci == Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@MinValueQuery && ((object)(ai) is not null)) { - if (((object)ai) != null && !(ai is global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery)) throw CreateMismatchChoiceException(@"Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery", @"ItemsElementName", @"Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@MinValueQuery"); + if (((object)ai) is not null && !(ai is global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery)) throw CreateMismatchChoiceException(@"Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery", @"ItemsElementName", @"Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@MinValueQuery"); Write14_PropertyQuery(@"MinValueQuery", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery)ai), false, false); } - else if ((object)(ai) != null) + else if ((object)(ai) is not null) { throw CreateUnknownTypeException(ai); } @@ -2180,7 +2180,7 @@ private void Write10_CmdletParameterMetadata(string n, string ns, global::Micros } { global::System.String[] a = (global::System.String[])o.@Aliases; - if (a != null) + if (a is not null) { Writer.WriteStartAttribute(null, @"Aliases", string.Empty); for (int i = 0; i < a.Length; i++) @@ -2206,7 +2206,7 @@ private void Write10_CmdletParameterMetadata(string n, string ns, global::Micros Write6_Item(@"ValidateRange", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange)o.@ValidateRange), false, false); { global::System.String[] a = (global::System.String[])((global::System.String[])o.@ValidateSet); - if (a != null) + if (a is not null) { WriteStartElement(@"ValidateSet", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); for (int ia = 0; ia < a.Length; ia++) @@ -2251,7 +2251,7 @@ private void Write19_GetCmdletParameters(string n, string ns, global::Microsoft. WriteAttribute(@"DefaultCmdletParameterSet", @"", ((global::System.String)o.@DefaultCmdletParameterSet)); { global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata[])((global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata[])o.@QueryableProperties); - if (a != null) + if (a is not null) { WriteStartElement(@"QueryableProperties", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); for (int ia = 0; ia < a.Length; ia++) @@ -2264,7 +2264,7 @@ private void Write19_GetCmdletParameters(string n, string ns, global::Microsoft. } { global::Microsoft.PowerShell.Cmdletization.Xml.Association[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.Association[])((global::Microsoft.PowerShell.Cmdletization.Xml.Association[])o.@QueryableAssociations); - if (a != null) + if (a is not null) { WriteStartElement(@"QueryableAssociations", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); for (int ia = 0; ia < a.Length; ia++) @@ -2277,7 +2277,7 @@ private void Write19_GetCmdletParameters(string n, string ns, global::Microsoft. } { global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[])((global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[])o.@QueryOptions); - if (a != null) + if (a is not null) { WriteStartElement(@"QueryOptions", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); for (int ia = 0; ia < a.Length; ia++) @@ -2318,7 +2318,7 @@ private void Write45_Item(string n, string ns, global::Microsoft.PowerShell.Cmdl WriteAttribute(@"Noun", @"", ((global::System.String)o.@Noun)); { global::System.String[] a = (global::System.String[])o.@Aliases; - if (a != null) + if (a is not null) { Writer.WriteStartAttribute(null, @"Aliases", string.Empty); for (int i = 0; i < a.Length; i++) @@ -2378,7 +2378,7 @@ private void Write21_CommonCmdletMetadata(string n, string ns, global::Microsoft WriteAttribute(@"Noun", @"", ((global::System.String)o.@Noun)); { global::System.String[] a = (global::System.String[])o.@Aliases; - if (a != null) + if (a is not null) { Writer.WriteStartAttribute(null, @"Aliases", string.Empty); for (int i = 0; i < a.Length; i++) @@ -2459,7 +2459,7 @@ private void Write30_InstanceMethodMetadata(string n, string ns, global::Microso Write24_Item(@"ReturnValue", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue)o.@ReturnValue), false, false); { global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata[])((global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata[])o.@Parameters); - if (a != null) + if (a is not null) { WriteStartElement(@"Parameters", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); for (int ia = 0; ia < a.Length; ia++) @@ -2607,7 +2607,7 @@ private void Write36_ClassMetadata(string n, string ns, global::Microsoft.PowerS Write32_ClassMetadataInstanceCmdlets(@"InstanceCmdlets", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets)o.@InstanceCmdlets), false, false); { global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata[])((global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata[])o.@StaticCmdlets); - if (a != null) + if (a is not null) { WriteStartElement(@"StaticCmdlets", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); for (int ia = 0; ia < a.Length; ia++) @@ -2620,7 +2620,7 @@ private void Write36_ClassMetadata(string n, string ns, global::Microsoft.PowerS } { global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[])((global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[])o.@CmdletAdapterPrivateData); - if (a != null) + if (a is not null) { WriteStartElement(@"CmdletAdapterPrivateData", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); for (int ia = 0; ia < a.Length; ia++) @@ -2661,7 +2661,7 @@ private void Write32_ClassMetadataInstanceCmdlets(string n, string ns, global::M Write22_GetCmdletMetadata(@"GetCmdlet", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata)o.@GetCmdlet), false, false); { global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata[])o.@Cmdlet; - if (a != null) + if (a is not null) { for (int ia = 0; ia < a.Length; ia++) { @@ -2699,7 +2699,7 @@ private void Write40_ClassMetadataInstanceCmdlets(string n, string ns, global::M Write22_GetCmdletMetadata(@"GetCmdlet", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata)o.@GetCmdlet), false, false); { global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata[])o.@Cmdlet; - if (a != null) + if (a is not null) { for (int ia = 0; ia < a.Length; ia++) { @@ -2871,7 +2871,7 @@ private void Write39_PowerShellMetadata(string n, string ns, global::Microsoft.P Write36_ClassMetadata(@"Class", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadata)o.@Class), false, false); { global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[])((global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[])o.@Enums); - if (a != null) + if (a is not null) { WriteStartElement(@"Enums", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); for (int ia = 0; ia < a.Length; ia++) @@ -4619,7 +4619,7 @@ public object Read87_EnumMetadataEnumValue() { if (isNull) { - if (xsiType != null) return (global::System.Object)ReadTypedNull(xsiType); + if (xsiType is not null) return (global::System.Object)ReadTypedNull(xsiType); else return null; } diff --git a/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs b/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs index 98a0034ba35..8cbe9d6debc 100644 --- a/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs +++ b/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs @@ -75,12 +75,12 @@ public override System.Collections.ObjectModel.Collection Get Collection result = new Collection(); - if (cimInstance.CimInstanceProperties != null) + if (cimInstance.CimInstanceProperties is not null) { foreach (CimProperty property in cimInstance.CimInstanceProperties) { PSAdaptedProperty propertyToAdd = GetCimPropertyAdapter(property, baseObject); - if (propertyToAdd != null) + if (propertyToAdd is not null) { result.Add(propertyToAdd); } @@ -88,7 +88,7 @@ public override System.Collections.ObjectModel.Collection Get } PSAdaptedProperty psComputerNameProperty = GetPSComputerNameAdapter(cimInstance); - if (psComputerNameProperty != null) + if (psComputerNameProperty is not null) { result.Add(psComputerNameProperty); } @@ -120,7 +120,7 @@ public override PSAdaptedProperty GetProperty(object baseObject, string property } CimProperty cimProperty = cimInstance.CimInstanceProperties[propertyName]; - if (cimProperty != null) + if (cimProperty is not null) { PSAdaptedProperty prop = GetCimPropertyAdapter(cimProperty, baseObject, propertyName); return prop; @@ -163,7 +163,7 @@ public override PSAdaptedProperty GetFirstPropertyOrDefault(object baseObject, M foreach (CimProperty cimProperty in cimInstance.CimInstanceProperties) { - if (cimProperty != null && predicate(cimProperty.Name)) + if (cimProperty is not null && predicate(cimProperty.Name)) { PSAdaptedProperty prop = GetCimPropertyAdapter(cimProperty, baseObject, cimProperty.Name); return prop; @@ -203,7 +203,7 @@ public override string GetPropertyTypeName(PSAdaptedProperty adaptedProperty) } CimProperty cimProperty = adaptedProperty.Tag as CimProperty; - if (cimProperty != null) + if (cimProperty is not null) { return CimTypeToTypeNameDisplayString(cimProperty.CimType); } @@ -228,7 +228,7 @@ public override object GetPropertyValue(PSAdaptedProperty adaptedProperty) } CimProperty cimProperty = adaptedProperty.Tag as CimProperty; - if (cimProperty != null) + if (cimProperty is not null) { return cimProperty.Value; } @@ -262,8 +262,8 @@ private List GetInheritanceChain(CimInstance cimInstance) { List inheritanceChain = new List(); CimClass cimClass = cimInstance.CimClass; - Dbg.Assert(cimClass != null, "CimInstance should always have ClassDecl"); - while (cimClass != null) + Dbg.Assert(cimClass is not null, "CimInstance should always have ClassDecl"); + while (cimClass is not null) { inheritanceChain.Add(cimClass); try @@ -320,9 +320,9 @@ public override Collection GetTypeNameHierarchy(object baseObject) result.AddRange(typeNamesWithNamespace); result.AddRange(typeNamesWithoutNamespace); - if (baseObject != null) + if (baseObject is not null) { - for (Type type = baseObject.GetType(); type != null; type = type.BaseType) + for (Type type = baseObject.GetType(); type is not null; type = type.BaseType) { result.Add(type.FullName); } @@ -394,7 +394,7 @@ public override void SetPropertyValue(PSAdaptedProperty adaptedProperty, object CimProperty cimProperty = adaptedProperty.Tag as CimProperty; object valueToSet = value; - if (valueToSet != null) + if (valueToSet is not null) { // Convert only if value is not null Type paramType; @@ -408,7 +408,7 @@ public override void SetPropertyValue(PSAdaptedProperty adaptedProperty, object break; default: paramType = CimConverter.GetDotNetType(cimProperty.CimType); - Dbg.Assert(paramType != null, "'default' case should only be used for well-defined CimType->DotNetType conversions"); + Dbg.Assert(paramType is not null, "'default' case should only be used for well-defined CimType->DotNetType conversions"); break; } diff --git a/src/System.Management.Automation/engine/AliasInfo.cs b/src/System.Management.Automation/engine/AliasInfo.cs index 6e352b02cf7..28153bcaa91 100644 --- a/src/System.Management.Automation/engine/AliasInfo.cs +++ b/src/System.Management.Automation/engine/AliasInfo.cs @@ -36,7 +36,7 @@ internal AliasInfo(string name, string definition, ExecutionContext context) : b _definition = definition; this.Context = context; - if (context != null) + if (context is not null) { this.Module = context.SessionState.Internal.Module; } @@ -73,7 +73,7 @@ internal AliasInfo( this.Context = context; _options = options; - if (context != null) + if (context is not null) { this.Module = context.SessionState.Internal.Module; } @@ -98,7 +98,7 @@ public CommandInfo ReferencedCommand CommandInfo referencedCommand = null; - if ((_definition != null) && (Context != null)) + if ((_definition is not null) && (Context is not null)) { CommandSearcher commandSearcher = new CommandSearcher( @@ -140,14 +140,14 @@ public CommandInfo ResolvedCommand CommandInfo result = null; - if (_definition != null) + if (_definition is not null) { List cyclePrevention = new List(); cyclePrevention.Add(Name); string commandNameToResolve = _definition; result = ReferencedCommand; - while (result != null && result.CommandType == CommandTypes.Alias) + while (result is not null && result.CommandType == CommandTypes.Alias) { result = ((AliasInfo)result).ReferencedCommand; @@ -350,7 +350,7 @@ public override ReadOnlyCollection OutputType get { CommandInfo resolvedCommand = this.ResolvedCommand; - if (resolvedCommand != null) + if (resolvedCommand is not null) { return resolvedCommand.OutputType; } diff --git a/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs b/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs index c0ed9926de6..52fce50586e 100644 --- a/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs +++ b/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs @@ -62,7 +62,7 @@ internal object Transform(EngineIntrinsics engineIntrinsics, object inputData, b { object temp; PSObject mshObject = result as PSObject; - if (mshObject != null) + if (mshObject is not null) temp = mshObject.BaseObject; else temp = result; @@ -79,7 +79,7 @@ internal object Transform(EngineIntrinsics engineIntrinsics, object inputData, b { object temp; PSObject mshObject = result as PSObject; - if (mshObject != null) + if (mshObject is not null) temp = mshObject.BaseObject; else temp = result; @@ -87,7 +87,7 @@ internal object Transform(EngineIntrinsics engineIntrinsics, object inputData, b // If a non-ref type is expected but currently passed in is a ref, do an implicit dereference. PSReference reference = temp as PSReference; - if (reference != null) + if (reference is not null) { result = reference.Value; } @@ -97,7 +97,7 @@ internal object Transform(EngineIntrinsics engineIntrinsics, object inputData, b // Don't allow conversion from array to string in script w/ cmdlet binding. Allow // the conversion for ordinary script parameter binding for V1 compatibility. temp = PSObject.Base(result); - if (temp != null && temp.GetType().IsArray) + if (temp is not null && temp.GetType().IsArray) { throw new PSInvalidCastException("InvalidCastFromAnyTypeToString", null, ExtendedTypeSystem.InvalidCastCannotRetrieveString); @@ -125,7 +125,7 @@ internal object Transform(EngineIntrinsics engineIntrinsics, object inputData, b && LanguagePrimitives.IsBoolOrSwitchParameterType(collectionTypeInfo.ElementType)) { IList currentValueAsIList = ParameterBinderBase.GetIList(result); - if (currentValueAsIList != null) + if (currentValueAsIList is not null) { foreach (object val in currentValueAsIList) { @@ -177,7 +177,7 @@ internal object Transform(EngineIntrinsics engineIntrinsics, object inputData, b private static void CheckBoolValue(object value, Type boolType) { - if (value != null) + if (value is not null) { Type resultType = value.GetType(); diff --git a/src/System.Management.Automation/engine/Attributes.cs b/src/System.Management.Automation/engine/Attributes.cs index 05b7c353483..628309300d5 100644 --- a/src/System.Management.Automation/engine/Attributes.cs +++ b/src/System.Management.Automation/engine/Attributes.cs @@ -981,7 +981,7 @@ protected override void ValidateElement(object element) } var o = element as PSObject; - if (o != null) + if (o is not null) { element = o.BaseObject; } @@ -1023,7 +1023,7 @@ public ValidateRangeAttribute(object minRange, object maxRange) : base() { bool failure = true; _promotedType = GetCommonType(minRange.GetType(), maxRange.GetType()); - if (_promotedType != null) + if (_promotedType is not null) { if (LanguagePrimitives.TryConvertTo(minRange, _promotedType, out object minResultValue) && LanguagePrimitives.TryConvertTo(maxRange, _promotedType, out object maxResultValue)) @@ -1059,7 +1059,7 @@ public ValidateRangeAttribute(object minRange, object maxRange) : base() } _maxComparable = maxRange as IComparable; - Diagnostics.Assert(_maxComparable != null, "maxComparable comes from a type that is IComparable"); + Diagnostics.Assert(_maxComparable is not null, "maxComparable comes from a type that is IComparable"); // Thanks to the IComparable test above this will not throw. They have the same type and are IComparable. if (_minComparable.CompareTo(maxRange) > 0) @@ -1558,7 +1558,7 @@ public string[] GetValidValues() // Because we have a background task to clear the cache by '_validValues = null' // we use the local variable to exclude a race condition. var validValuesLocal = _validValues; - if (validValuesLocal != null) + if (validValuesLocal is not null) { return validValuesLocal; } @@ -1947,7 +1947,7 @@ protected bool IsArgumentCollection(Type argumentType, out bool isElementValueTy case ParameterCollectionType.IList: case ParameterCollectionType.ICollectionGeneric: Type elementType = information.ElementType; - isElementValueType = elementType != null && elementType.IsValueType; + isElementValueType = elementType is not null && elementType.IsValueType; return true; default: return false; @@ -2166,7 +2166,7 @@ internal object TransformInternal( bool trackDataInputSource = true) { object result = Transform(engineIntrinsics, inputData); - if (trackDataInputSource && engineIntrinsics != null) + if (trackDataInputSource && engineIntrinsics is not null) { ExecutionContext.PropagateInputSource( inputData, diff --git a/src/System.Management.Automation/engine/COM/ComAdapter.cs b/src/System.Management.Automation/engine/COM/ComAdapter.cs index f4a1d2b3a23..24b042e173f 100644 --- a/src/System.Management.Automation/engine/COM/ComAdapter.cs +++ b/src/System.Management.Automation/engine/COM/ComAdapter.cs @@ -23,7 +23,7 @@ internal class ComAdapter : Adapter /// Typeinfo for the com object we are adapting. internal ComAdapter(ComTypeInfo typeinfo) { - Diagnostics.Assert(typeinfo != null, "Caller to verify typeinfo is not null."); + Diagnostics.Assert(typeinfo is not null, "Caller to verify typeinfo is not null."); _comTypeInfo = typeinfo; } @@ -76,7 +76,7 @@ protected override T GetMember(object obj, string memberName) ComMethod method; if (typeof(T).IsAssignableFrom(typeof(PSMethod)) && - (_comTypeInfo != null) && (_comTypeInfo.Methods.TryGetValue(memberName, out method))) + (_comTypeInfo is not null) && (_comTypeInfo.Methods.TryGetValue(memberName, out method))) { PSMethod mshMethod = new PSMethod(method.Name, this, obj, method); return 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..83c5044d464 100644 --- a/src/System.Management.Automation/engine/COM/ComInvoker.cs +++ b/src/System.Management.Automation/engine/COM/ComInvoker.cs @@ -137,12 +137,12 @@ 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(target is not null, "Caller makes sure an IDispatch object passed in."); Diagnostics.Assert(args is null || byRef is 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; - int refCount = byRef != null ? byRef.Count(c => c) : 0; + int argCount = args is not null ? args.Length : 0; + int refCount = byRef is not null ? byRef.Count(c => c) : 0; IntPtr variantArgArray = IntPtr.Zero, dispIdArray = IntPtr.Zero, tmpVariants = IntPtr.Zero; try @@ -160,7 +160,7 @@ internal static object Invoke(IDispatch target, int dispId, object[] args, bool[ IntPtr varArgPtr = variantArgArray + s_variantSize * actualIndex; // If need to pass by ref, create a by-ref variant - if (byRef != null && byRef[i]) + if (byRef is not null && byRef[i]) { // Allocate memory for temporary VARIANTs used in by-ref marshalling if (tmpVariants == IntPtr.Zero) @@ -264,7 +264,7 @@ internal static object Invoke(IDispatch target, int dispId, object[] args, bool[ int actualIndex = argCount - i - 1; // If need to pass by ref, back propagate - if (byRef != null && byRef[i]) + if (byRef is not null && byRef[i]) { args[i] = Marshal.GetObjectForNativeVariant(variantArgArray + s_variantSize * actualIndex); } diff --git a/src/System.Management.Automation/engine/COM/ComTypeInfo.cs b/src/System.Management.Automation/engine/COM/ComTypeInfo.cs index 6a03f31c9ac..2bd70e53707 100644 --- a/src/System.Management.Automation/engine/COM/ComTypeInfo.cs +++ b/src/System.Management.Automation/engine/COM/ComTypeInfo.cs @@ -45,7 +45,7 @@ internal ComTypeInfo(COM.ITypeInfo info) _properties = new Dictionary(StringComparer.OrdinalIgnoreCase); _methods = new Dictionary(StringComparer.OrdinalIgnoreCase); - if (_typeinfo != null) + if (_typeinfo is not null) { Initialize(); } @@ -95,7 +95,7 @@ internal string Clsid /// private void Initialize() { - if (_typeinfo != null) + if (_typeinfo is not null) { COM.TYPEATTR typeattr = GetTypeAttr(_typeinfo); @@ -147,11 +147,11 @@ internal static ComTypeInfo GetDispatchTypeInfo(object comObject) { ComTypeInfo result = null; IDispatch disp = comObject as IDispatch; - if (disp != null) + if (disp is not null) { COM.ITypeInfo typeinfo = null; disp.GetTypeInfo(0, 0, out typeinfo); - if (typeinfo != null) + if (typeinfo is not null) { COM.TYPEATTR typeattr = GetTypeAttr(typeinfo); @@ -183,7 +183,7 @@ private void AddProperty(string strName, COM.FUNCDESC funcdesc, int index) _properties[strName] = prop; } - if (prop != null) + if (prop is not null) { prop.UpdateFuncDesc(funcdesc, index); } @@ -198,7 +198,7 @@ private void AddMethod(string strName, int index) _methods[strName] = method; } - if (method != null) + if (method is not null) { method.AddFuncDesc(index); } diff --git a/src/System.Management.Automation/engine/COM/ComUtil.cs b/src/System.Management.Automation/engine/COM/ComUtil.cs index 1ba9d9099b2..d137ef716fc 100644 --- a/src/System.Management.Automation/engine/COM/ComUtil.cs +++ b/src/System.Management.Automation/engine/COM/ComUtil.cs @@ -130,7 +130,7 @@ private static string GetStringFromCustomType(COM.ITypeInfo typeinfo, IntPtr ref typeinfo.GetRefTypeInfo(reftype, out custtypeinfo); - if (custtypeinfo != null) + if (custtypeinfo is not null) { string strName, strDoc, strHelp; int id; diff --git a/src/System.Management.Automation/engine/ChildrenCmdletProviderInterfaces.cs b/src/System.Management.Automation/engine/ChildrenCmdletProviderInterfaces.cs index cf51d549e9b..ba4dad14974 100644 --- a/src/System.Management.Automation/engine/ChildrenCmdletProviderInterfaces.cs +++ b/src/System.Management.Automation/engine/ChildrenCmdletProviderInterfaces.cs @@ -105,7 +105,7 @@ internal ChildItemCmdletProviderIntrinsics(SessionStateInternal sessionState) public Collection Get(string path, bool recurse) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -161,7 +161,7 @@ public Collection Get(string path, bool recurse) public Collection Get(string[] path, bool recurse, uint depth, bool force, bool literalPath) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -214,7 +214,7 @@ public Collection Get(string[] path, bool recurse, uint depth, bool fo public Collection Get(string[] path, bool recurse, bool force, bool literalPath) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -270,7 +270,7 @@ internal void Get( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -319,7 +319,7 @@ internal object GetChildItemsDynamicParameters( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -378,7 +378,7 @@ public Collection GetNames( bool recurse) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -441,7 +441,7 @@ public Collection GetNames( bool literalPath) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); return _sessionState.GetChildNames(path, returnContainers, recurse, uint.MaxValue, force, literalPath); @@ -506,7 +506,7 @@ public Collection GetNames( bool literalPath) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); return _sessionState.GetChildNames(path, returnContainers, recurse, depth, force, literalPath); @@ -566,7 +566,7 @@ internal void GetNames( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -609,7 +609,7 @@ internal object GetChildNamesDynamicParameters( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -654,7 +654,7 @@ internal object GetChildNamesDynamicParameters( public bool HasChild(string path) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -701,7 +701,7 @@ public bool HasChild(string path) public bool HasChild(string path, bool force, bool literalPath) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -747,7 +747,7 @@ internal bool HasChild( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object diff --git a/src/System.Management.Automation/engine/CmdletInfo.cs b/src/System.Management.Automation/engine/CmdletInfo.cs index 3f0b0a66cec..3983d4e3fe6 100644 --- a/src/System.Management.Automation/engine/CmdletInfo.cs +++ b/src/System.Management.Automation/engine/CmdletInfo.cs @@ -234,7 +234,7 @@ internal string PSSnapInName get { string result = null; - if (_PSSnapin != null) + if (_PSSnapin is not null) { result = _PSSnapin.Name; } @@ -252,11 +252,11 @@ public override Version Version { if (_version is null) { - if (Module != null) + if (Module is not null) { _version = base.Version; } - else if (_PSSnapin != null) + else if (_PSSnapin is not null) { _version = _PSSnapin.Version; } @@ -290,7 +290,7 @@ public override string Definition { StringBuilder synopsis = new StringBuilder(); - if (this.ImplementingType != null) + if (this.ImplementingType is not null) { foreach (CommandParameterSetInfo parameterSet in ParameterSets) { @@ -343,7 +343,7 @@ public override ReadOnlyCollection OutputType { _outputType = new List(); - if (ImplementingType != null) + if (ImplementingType is not null) { foreach (object o in ImplementingType.GetCustomAttributes(typeof(OutputTypeAttribute), false)) { @@ -355,10 +355,10 @@ public override ReadOnlyCollection OutputType List providerTypes = new List(); - if (Context != null) + if (Context is not null) { ProviderInfo provider = null; - if (Arguments != null) + if (Arguments is not null) { // See if we have a path argument - we only consider named arguments -Path and -LiteralPath, // and only if they are fully specified (no prefixes allowed, so we don't need to deal with @@ -367,12 +367,12 @@ public override ReadOnlyCollection OutputType for (int i = 0; i < Arguments.Length - 1; i++) { var arg = Arguments[i] as string; - if (arg != null && + if (arg is not null && (arg.Equals("-Path", StringComparison.OrdinalIgnoreCase) || (arg.Equals("-LiteralPath", StringComparison.OrdinalIgnoreCase)))) { var path = Arguments[i + 1] as string; - if (path != null) + if (path is not null) { Context.SessionState.Path.GetResolvedProviderPathFromPSPath(path, true, out provider); } @@ -460,7 +460,7 @@ internal void SetOptions(ScopedItemOptions newOptions, bool force) /// private static string GetFullName(string moduleName, string cmdletName) { - System.Diagnostics.Debug.Assert(cmdletName != null, "cmdletName != null"); + System.Diagnostics.Debug.Assert(cmdletName is not null, "cmdletName is not null"); string result = cmdletName; if (!string.IsNullOrEmpty(moduleName)) { @@ -546,9 +546,9 @@ internal override bool ImplementsDynamicParameters { get { - if (ImplementingType != null) + if (ImplementingType is not null) { - return (ImplementingType.GetInterface(typeof(IDynamicParameters).Name, true) != null); + return (ImplementingType.GetInterface(typeof(IDynamicParameters).Name, true) is not null); } else { diff --git a/src/System.Management.Automation/engine/CmdletParameterBinderController.cs b/src/System.Management.Automation/engine/CmdletParameterBinderController.cs index 435564d5997..af847c31901 100644 --- a/src/System.Management.Automation/engine/CmdletParameterBinderController.cs +++ b/src/System.Management.Automation/engine/CmdletParameterBinderController.cs @@ -202,7 +202,7 @@ internal void BindCommandLineParameters(Collection arg internal void BindCommandLineParametersNoValidation(Collection arguments) { var psCompiledScriptCmdlet = this.Command as PSScriptCmdlet; - if (psCompiledScriptCmdlet != null) + if (psCompiledScriptCmdlet is not null) { psCompiledScriptCmdlet.PrepareForBinding(this.CommandLineParameters); } @@ -368,7 +368,7 @@ private void ApplyDefaultParameterBinding(string bindingStage, bool isDynamic) } Dictionary qualifiedParameterValuePairs = GetQualifiedParameterValuePairs(_currentParameterSetFlag, _allDefaultParameterValuePairs); - if (qualifiedParameterValuePairs != null) + if (qualifiedParameterValuePairs is not null) { bool isSuccess = false; using (ParameterBinderBase.bindingTracer.TraceScope( @@ -409,7 +409,7 @@ private bool BindDefaultParameters(uint validParameterSetFlag, Dictionary GetDefaultParameterVa continue; } - Diagnostics.Assert(cmdletName != null && parameterName != null, "The cmdletName and parameterName should be set in CheckKeyIsValid"); + Diagnostics.Assert(cmdletName is not null && parameterName is not null, "The cmdletName and parameterName should be set in CheckKeyIsValid"); if (WildcardPattern.ContainsWildcardCharacters(key)) { @@ -875,7 +875,7 @@ private void VerifyArgumentsProcessed(ParameterBindingException originalBindingE Type specifiedType = null; object argumentValue = parameter.ArgumentValue; - if (argumentValue != null && argumentValue != UnboundParameter.Value) + if (argumentValue is not null && argumentValue != UnboundParameter.Value) { specifiedType = argumentValue.GetType(); } @@ -897,7 +897,7 @@ private void VerifyArgumentsProcessed(ParameterBindingException originalBindingE { // If this was a positional parameter, and we have the original exception, // report on the original error - if (originalBindingException != null) + if (originalBindingException is not null) { bindingException = originalBindingException; } @@ -905,7 +905,7 @@ private void VerifyArgumentsProcessed(ParameterBindingException originalBindingE else { string argument = StringLiterals.DollarNull; - if (parameter.ArgumentValue != null) + if (parameter.ArgumentValue is not null) { try { @@ -1052,7 +1052,7 @@ private bool RestoreParameter(CommandParameterInternal argumentToBind, MergedCom _commandMetadata.ImplementsDynamicParameters, "The metadata for the dynamic parameters should only be available if the command supports IDynamicParameters"); - if (_dynamicParameterBinder != null) + if (_dynamicParameterBinder is not null) { _dynamicParameterBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue, parameter.Parameter); } @@ -1112,7 +1112,7 @@ private Collection BindParameters(uint parameterSets, // If the parameter is not in the specified parameter set, // throw a binding exception - if (parameter != null) + if (parameter is not null) { // Now check to make sure it hasn't already been // bound by looking in the boundParameters collection @@ -1397,7 +1397,7 @@ internal override bool BindParameter( // Attributes are used to do type coercion and result in various exceptions. // We assume that if we aren't trying to do type coercion, we should avoid // propagating type conversion exceptions. - while (e != null) + while (e is not null) { if (e is PSInvalidCastException) { @@ -1502,7 +1502,7 @@ private bool BindParameter( _commandMetadata.ImplementsDynamicParameters, "The metadata for the dynamic parameters should only be available if the command supports IDynamicParameters"); - if (_dynamicParameterBinder != null) + if (_dynamicParameterBinder is not null) { result = _dynamicParameterBinder.BindParameter( @@ -1535,7 +1535,7 @@ private bool BindParameter( BoundArguments.Add(parameter.Parameter.Name, argument); } - if (parameter.Parameter.ObsoleteAttribute != null && + if (parameter.Parameter.ObsoleteAttribute is not null && (flags & ParameterBindingFlags.IsDefaultValue) == 0 && !BoundObsoleteParameterNames.Contains(parameter.Parameter.Name)) { @@ -1586,7 +1586,7 @@ private void HandleRemainingArguments() if (parameterSetData.ValueFromRemainingArguments) { - if (varargsParameter != null) + if (varargsParameter is not null) { ParameterBindingException bindingException = new ParameterBindingException( @@ -1614,7 +1614,7 @@ private void HandleRemainingArguments() } } - if (varargsParameter != null) + if (varargsParameter is not null) { using (ParameterBinderBase.bindingTracer.TraceScope( "BIND REMAININGARGUMENTS cmd line args to param: [{0}]", @@ -1709,7 +1709,7 @@ private void HandleCommandLineDynamicParameters(out ParameterBindingException ou IDynamicParameters dynamicParameterCmdlet = this.Command as IDynamicParameters; - if (dynamicParameterCmdlet != null) + if (dynamicParameterCmdlet is not null) { if (_dynamicParameterBinder is null) { @@ -1744,7 +1744,7 @@ private void HandleCommandLineDynamicParameters(out ParameterBindingException ou throw bindingException; } - if (dynamicParamBindableObject != null) + if (dynamicParamBindableObject is not null) { ParameterBinderBase.bindingTracer.WriteLine( "DYNAMIC parameter object: [{0}]", @@ -1755,7 +1755,7 @@ private void HandleCommandLineDynamicParameters(out ParameterBindingException ou InternalParameterMetadata dynamicParameterMetadata; RuntimeDefinedParameterDictionary runtimeParamDictionary = dynamicParamBindableObject as RuntimeDefinedParameterDictionary; - if (runtimeParamDictionary != null) + if (runtimeParamDictionary is not null) { // Generate the type metadata for the runtime-defined parameters dynamicParameterMetadata = @@ -2783,7 +2783,7 @@ Cmdlet command { _currentParameterSetFlag = remainingParameterSetsWithNoMandatoryUnboundParameters; - if (command != null) + if (command is not null) { string currentParameterSetName = bindableParameters.GetParameterSetName(_currentParameterSetFlag); command.SetParameterSetName(currentParameterSetName); @@ -2937,7 +2937,7 @@ internal bool HandleUnboundMandatoryParameters( if ((Context.EngineHostInterface is null) || (!promptForMandatory)) { Diagnostics.Assert( - Context.EngineHostInterface != null, + Context.EngineHostInterface is not null, "The EngineHostInterface should never be null"); ParameterBinderBase.bindingTracer.WriteLine( @@ -3036,7 +3036,7 @@ private Dictionary PromptForMissingMandatoryParameters( error = invalidOperation; } - if (error != null) + if (error is not null) { ParameterBinderBase.bindingTracer.WriteLine( "ERROR: host does not support prompting for missing mandatory parameters"); @@ -3362,7 +3362,7 @@ private bool BindPipelineParametersPrivate(PSObject inputToOperateOn) "PIPELINE object TYPE = [{0}]", inputToOperateOn is null || inputToOperateOn == AutomationNull.Value ? "null" - : ((dontuseInternalTypeNames = inputToOperateOn.InternalTypeNames).Count > 0 && dontuseInternalTypeNames[0] != null) + : ((dontuseInternalTypeNames = inputToOperateOn.InternalTypeNames).Count > 0 && dontuseInternalTypeNames[0] is not null) ? dontuseInternalTypeNames[0] : inputToOperateOn.BaseObject.GetType().FullName); @@ -3546,7 +3546,7 @@ private bool BindUnboundParametersForBindingStateInParameterSet( // the property name else if (currentlyBinding == CurrentlyBinding.ValueFromPipelineByPropertyNameNoCoercion && parameterSetMetadata.ValueFromPipelineByPropertyName && - inputToOperateOn != null) + inputToOperateOn is not null) { bindResult = BindValueFromPipelineByPropertyName(inputToOperateOn, parameter, ParameterBindingFlags.None); } @@ -3561,7 +3561,7 @@ private bool BindUnboundParametersForBindingStateInParameterSet( // the property name else if (currentlyBinding == CurrentlyBinding.ValueFromPipelineByPropertyNameWithCoercion && parameterSetMetadata.ValueFromPipelineByPropertyName && - inputToOperateOn != null) + inputToOperateOn is not null) { bindResult = BindValueFromPipelineByPropertyName(inputToOperateOn, parameter, ParameterBindingFlags.ShouldCoerceType); } @@ -3631,7 +3631,7 @@ private bool BindValueFromPipeline( bindResult = false; } - if (parameterBindingException != null) + if (parameterBindingException is not null) { if (!DefaultParameterBindingInUse) { @@ -3670,14 +3670,14 @@ private bool BindValueFromPipelineByPropertyName( { member = inputToOperateOn.Properties[alias]; - if (member != null) + if (member is not null) { break; } } } - if (member != null) + if (member is not null) { ParameterBindingException parameterBindingException = null; try @@ -3706,7 +3706,7 @@ private bool BindValueFromPipelineByPropertyName( bindResult = false; } - if (parameterBindingException != null) + if (parameterBindingException is not null) { if (!DefaultParameterBindingInUse) { @@ -3779,7 +3779,7 @@ private bool InvokeAndBindDelayBindScriptBlock(PSObject inputToOperateOn, out bo ScriptBlock script = argument.ArgumentValue as ScriptBlock; Diagnostics.Assert( - script != null, + script is not null, "An argument should only be put in the delayBindScriptBlocks collection if it is a ScriptBlock"); Collection output = null; @@ -3806,7 +3806,7 @@ private bool InvokeAndBindDelayBindScriptBlock(PSObject inputToOperateOn, out bo } } - if (error != null) + if (error is not null) { ParameterBindingException bindingException = new ParameterBindingException( @@ -3941,7 +3941,7 @@ internal object GetDefaultParameterValue(string name) break; case ParameterBinderAssociation.DynamicParameters: - if (_dynamicParameterBinder != null) + if (_dynamicParameterBinder is not null) { result = _dynamicParameterBinder.GetDefaultParameterValue(name); } @@ -4317,7 +4317,7 @@ private void RestoreDefaultParameterValues(IEnumerable temps, List initTemps) { - Debug.Assert(args != null); + Debug.Assert(args is not null); DynamicMetaObject[] newArgs = new DynamicMetaObject[args.Length]; bool[] isByRefArg = new bool[args.Length]; @@ -91,7 +91,7 @@ internal static bool[] ProcessArgumentsForCom(ComMethodDesc method, ref DynamicM ); PSReference value = curArgument.Value as PSReference; - object boxedValue = value != null ? value.Value : null; + object boxedValue = value is not null ? value.Value : null; newArgs[i] = new DynamicMetaObject( boxedValueAccessor, @@ -103,7 +103,7 @@ internal static bool[] ProcessArgumentsForCom(ComMethodDesc method, ref DynamicM } else { - if ((method.ParameterInformation != null) && (i < method.ParameterInformation.Length)) + if ((method.ParameterInformation is not null) && (i < method.ParameterInformation.Length)) { newArgs[i] = new DynamicMetaObject(curArgument.CastOrConvertMethodArgument( method.ParameterInformation[i].parameterType, diff --git a/src/System.Management.Automation/engine/ComInterop/ComEventSink.cs b/src/System.Management.Automation/engine/ComInterop/ComEventSink.cs index c4146cf08b3..602f4f20194 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComEventSink.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComEventSink.cs @@ -170,7 +170,7 @@ public void RemoveHandler(int dispid, object func) foreach (Delegate d in delegates) { SplatCallSite callContext = d.Target as SplatCallSite; - if (callContext != null && callContext._callable.Equals(func)) + if (callContext is not null && callContext._callable.Equals(func)) { sinkEntry._handlers -= d as Func; break; @@ -200,7 +200,7 @@ public object ExecuteHandler(string name, object[] args) ComEventSinkMethod site; site = FindSinkMethod(name); - if (site != null && site._handlers != null) + if (site is not null && site._handlers is not null) { return site._handlers(args); } @@ -331,7 +331,7 @@ private void DisposeAll() // the Unadvise is going to throw. In this case, since we're going away anyway, // we'll ignore the failure and quietly go on our merry way. COMException exCOM = ex as COMException; - if (exCOM != null && exCOM.ErrorCode == ComHresults.CONNECT_E_NOCONNECTION) + if (exCOM is not null && exCOM.ErrorCode == ComHresults.CONNECT_E_NOCONNECTION) { Debug.Assert(false, "IConnectionPoint::Unadvise returned CONNECT_E_NOCONNECTION."); throw; diff --git a/src/System.Management.Automation/engine/ComInterop/ComEventSinksContainer.cs b/src/System.Management.Automation/engine/ComInterop/ComEventSinksContainer.cs index 029068323f6..5e1d5230825 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComEventSinksContainer.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComEventSinksContainer.cs @@ -28,7 +28,7 @@ public static ComEventSinksContainer FromRuntimeCallableWrapper(object rcw, bool // !!! Marshal.Get/SetComObjectData has a LinkDemand for UnmanagedCode which will turn into // a full demand. We need to avoid this by making this method SecurityCritical object data = Marshal.GetComObjectData(rcw, s_comObjectEventSinksKey); - if (data != null || createIfNotFound == false) + if (data is not null || createIfNotFound == false) { return (ComEventSinksContainer)data; } @@ -36,7 +36,7 @@ public static ComEventSinksContainer FromRuntimeCallableWrapper(object rcw, bool lock (s_comObjectEventSinksKey) { data = Marshal.GetComObjectData(rcw, s_comObjectEventSinksKey); - if (data != null) + if (data is not null) { return (ComEventSinksContainer)data; } diff --git a/src/System.Management.Automation/engine/ComInterop/ComInvokeBinder.cs b/src/System.Management.Automation/engine/ComInterop/ComInvokeBinder.cs index f35f3976f0a..b7e583c93ce 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComInvokeBinder.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComInvokeBinder.cs @@ -52,11 +52,11 @@ internal ComInvokeBinder( ComMethodDesc methodDesc ) { - Debug.Assert(callInfo != null, "arguments"); - Debug.Assert(args != null, "args"); - Debug.Assert(isByRef != null, "isByRef"); - Debug.Assert(method != null, "method"); - Debug.Assert(dispatch != null, "dispatch"); + Debug.Assert(callInfo is not null, "arguments"); + Debug.Assert(args is not null, "args"); + Debug.Assert(isByRef is not null, "isByRef"); + Debug.Assert(method is not null, "method"); + Debug.Assert(dispatch is not null, "dispatch"); Debug.Assert(TypeUtils.AreReferenceAssignable(typeof(ComMethodDesc), method.Type), "method"); Debug.Assert(TypeUtils.AreReferenceAssignable(typeof(IDispatch), dispatch.Type), "dispatch"); @@ -124,7 +124,7 @@ private ParameterExpression ParamVariantsVariable private static ParameterExpression EnsureVariable(ref ParameterExpression var, Type type, string name) { - if (var != null) + if (var is not null) { return var; } @@ -176,7 +176,7 @@ internal DynamicMetaObject Invoke() private static void AddNotNull(List list, ParameterExpression var) { - if (var != null) list.Add(var); + if (var is not null) list.Add(var); } private Expression CreateScope(Expression expression) @@ -262,7 +262,7 @@ private Expression GenerateTryBlock() parameters[i + 1] ); - if (marshal != null) + if (marshal is not null) { tryStatements.Add(marshal); } @@ -338,7 +338,7 @@ private Expression GenerateTryBlock() for (int i = 0, n = variants.Length; i < n; i++) { Expression updateFromReturn = variants[i].UpdateFromReturn(parametersForUpdates[i + 1]); - if (updateFromReturn != null) + if (updateFromReturn is not null) { tryStatements.Add(updateFromReturn); } @@ -369,7 +369,7 @@ private Expression GenerateFinallyBlock() for (int i = 0, n = _varEnumSelector.VariantBuilders.Length; i < n; i++) { Expression clear = _varEnumSelector.VariantBuilders[i].Clear(); - if (clear != null) + if (clear is not null) { finallyStatements.Add(clear); } @@ -389,7 +389,7 @@ private Expression GenerateFinallyBlock() // // _dispIdsOfKeywordArgsPinned.Free() // - if (_dispIdsOfKeywordArgsPinned != null) + if (_dispIdsOfKeywordArgsPinned is not null) { finallyStatements.Add( Expression.Call( @@ -533,7 +533,7 @@ private Expression MakeIDispatchInvokeTarget() var vars = new List(); foreach (var variant in _varEnumSelector.VariantBuilders) { - if (variant.TempVariable != null) + if (variant.TempVariable is not null) { vars.Add(variant.TempVariable); } @@ -555,7 +555,7 @@ private Expression[] MakeArgumentExpressions() { Expression[] res; int copy = 0; - if (_instance != null) + if (_instance is not null) { res = new Expression[_args.Length + 1]; res[copy++] = _instance; diff --git a/src/System.Management.Automation/engine/ComInterop/ComMethodDesc.cs b/src/System.Management.Automation/engine/ComInterop/ComMethodDesc.cs index 79ba5d8f2a4..82817d46f8e 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComMethodDesc.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComMethodDesc.cs @@ -61,7 +61,7 @@ public string Name { get { - Debug.Assert(_name != null); + Debug.Assert(_name is not null); return _name; } } diff --git a/src/System.Management.Automation/engine/ComInterop/ComObject.cs b/src/System.Management.Automation/engine/ComInterop/ComObject.cs index 65ac238a06c..02c51ca4510 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComObject.cs @@ -46,7 +46,7 @@ public static ComObject ObjectToComObject(object rcw) // Marshal.Get/SetComObjectData has a LinkDemand for UnmanagedCode which will turn into // a full demand. We could avoid this by making this method SecurityCritical object data = Marshal.GetComObjectData(rcw, s_comObjectInfoKey); - if (data != null) + if (data is not null) { return (ComObject)data; } @@ -54,7 +54,7 @@ public static ComObject ObjectToComObject(object rcw) lock (s_comObjectInfoKey) { data = Marshal.GetComObjectData(rcw, s_comObjectInfoKey); - if (data != null) + if (data is not null) { return (ComObject)data; } @@ -72,7 +72,7 @@ public static ComObject ObjectToComObject(object rcw) // Expression that unwraps ComObject internal static MemberExpression RcwFromComObject(Expression comObject) { - Debug.Assert(comObject != null && typeof(ComObject).IsAssignableFrom(comObject.Type), "must be ComObject"); + Debug.Assert(comObject is not null && typeof(ComObject).IsAssignableFrom(comObject.Type), "must be ComObject"); return Expression.Property( Helpers.Convert(comObject, typeof(ComObject)), @@ -92,7 +92,7 @@ internal static MethodCallExpression RcwToComObject(Expression rcw) private static ComObject CreateComObject(object rcw) { IDispatch dispatchObject = rcw as IDispatch; - if (dispatchObject != null) + if (dispatchObject is not null) { // We can do method invocations on IDispatch objects return new IDispatchComObject(dispatchObject); @@ -122,7 +122,7 @@ DynamicMetaObject IDynamicMetaObjectProvider.GetMetaObject(Expression parameter) internal static bool IsComObject(object obj) { // we can't use System.Runtime.InteropServices.Marshal.IsComObject(obj) since it doesn't work in partial trust - return obj != null && s_comObjectType.IsAssignableFrom(obj.GetType()); + return obj is not null && s_comObjectType.IsAssignableFrom(obj.GetType()); } } } diff --git a/src/System.Management.Automation/engine/ComInterop/ComRuntimeHelpers.cs b/src/System.Management.Automation/engine/ComInterop/ComRuntimeHelpers.cs index c421fe09ac9..59e7be519e2 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComRuntimeHelpers.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComRuntimeHelpers.cs @@ -465,13 +465,13 @@ internal static Variant GetVariantForObject(object obj) internal static void InitVariantForObject(object obj, ref Variant variant) { - Debug.Assert(obj != null); + Debug.Assert(obj is not null); // GetNativeVariantForObject is very expensive for values that marshal as VT_DISPATCH // also is is extremely common scenario when object at hand is an RCW. // Therefore we are going to test for IDispatch before defaulting to GetNativeVariantForObject. IDispatch disp = obj as IDispatch; - if (disp != null) + if (disp is not null) { variant.AsDispatch = obj; return; @@ -631,7 +631,7 @@ internal static ModuleBuilder DynamicModule { get { - if (s_dynamicModule != null) + if (s_dynamicModule is not null) { return s_dynamicModule; } diff --git a/src/System.Management.Automation/engine/ComInterop/ComTypeDesc.cs b/src/System.Management.Automation/engine/ComInterop/ComTypeDesc.cs index 12375c978fb..6ddc6a23b44 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComTypeDesc.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComTypeDesc.cs @@ -23,7 +23,7 @@ internal class ComTypeDesc : ComTypeLibMemberDesc internal ComTypeDesc(ITypeInfo typeInfo, ComType memberType, ComTypeLibDesc typeLibDesc) : base(memberType) { - if (typeInfo != null) + if (typeInfo is not null) { ComRuntimeHelpers.GetInfoFromType(typeInfo, out _typeName, out _documentation); } @@ -188,7 +188,7 @@ internal string[] GetMemberNames(bool dataOnly) } } - if (Events != null && Events.Count > 0) + if (Events is not null && Events.Count > 0) { foreach (string name in Events.Keys) { diff --git a/src/System.Management.Automation/engine/ComInterop/ComTypeLibDesc.cs b/src/System.Management.Automation/engine/ComInterop/ComTypeLibDesc.cs index 5bded65e70a..9ca17861478 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComTypeLibDesc.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComTypeLibDesc.cs @@ -178,7 +178,7 @@ public object GetTypeLibObjectDesc(string member) } ComTypeEnumDesc enumDesc; - if (_enums != null && _enums.TryGetValue(member, out enumDesc) == true) + if (_enums is not null && _enums.TryGetValue(member, out enumDesc) == true) return enumDesc; return null; diff --git a/src/System.Management.Automation/engine/ComInterop/DispCallable.cs b/src/System.Management.Automation/engine/ComInterop/DispCallable.cs index aba2fc5f6f2..7965305c8dc 100644 --- a/src/System.Management.Automation/engine/ComInterop/DispCallable.cs +++ b/src/System.Management.Automation/engine/ComInterop/DispCallable.cs @@ -48,7 +48,7 @@ public DynamicMetaObject GetMetaObject(Expression parameter) public override bool Equals(object obj) { var other = obj as DispCallable; - return other != null && other.DispatchComObject == DispatchComObject && other.DispId == DispId; + return other is not null && other.DispatchComObject == DispatchComObject && other.DispId == DispId; } public override int GetHashCode() diff --git a/src/System.Management.Automation/engine/ComInterop/DispCallableMetaObject.cs b/src/System.Management.Automation/engine/ComInterop/DispCallableMetaObject.cs index 130eaa524c2..c482504a315 100644 --- a/src/System.Management.Automation/engine/ComInterop/DispCallableMetaObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/DispCallableMetaObject.cs @@ -111,7 +111,7 @@ private DynamicMetaObject BindComInvoke(ComMethodDesc method, DynamicMetaObject[ method ).Invoke(); - if ((temps != null) && (temps.Any())) + if ((temps is not null) && (temps.Any())) { Expression invokeExpression = invoke.Expression; Expression call = Expression.Block(invokeExpression.Type, temps, initTemps.Append(invokeExpression)); diff --git a/src/System.Management.Automation/engine/ComInterop/ExcepInfo.cs b/src/System.Management.Automation/engine/ComInterop/ExcepInfo.cs index c1a937fd318..ddb0d8e20cf 100644 --- a/src/System.Management.Automation/engine/ComInterop/ExcepInfo.cs +++ b/src/System.Management.Automation/engine/ComInterop/ExcepInfo.cs @@ -75,7 +75,7 @@ internal Exception GetException() Exception exception = Marshal.GetExceptionForHR(errorCode); string message = ConvertAndFreeBstr(ref _bstrDescription); - if (message != null) + if (message is not null) { // If we have a custom message, create a new Exception object with the message set correctly. // We need to create a new object because "exception.Message" is a read-only property. @@ -87,7 +87,7 @@ internal Exception GetException() { Type exceptionType = exception.GetType(); ConstructorInfo ctor = exceptionType.GetConstructor(new Type[] { typeof(string) }); - if (ctor != null) + if (ctor is not null) { exception = (Exception)ctor.Invoke(new object[] { message }); } @@ -97,7 +97,7 @@ internal Exception GetException() exception.Source = ConvertAndFreeBstr(ref _bstrSource); string helpLink = ConvertAndFreeBstr(ref _bstrHelpFile); - if (helpLink != null && _dwHelpContext != 0) + if (helpLink is not null && _dwHelpContext != 0) { helpLink += "#" + _dwHelpContext; } diff --git a/src/System.Management.Automation/engine/ComInterop/IDispatchComObject.cs b/src/System.Management.Automation/engine/ComInterop/IDispatchComObject.cs index bb8a2eeb5a8..9fffff01890 100644 --- a/src/System.Management.Automation/engine/ComInterop/IDispatchComObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/IDispatchComObject.cs @@ -101,7 +101,7 @@ public override string ToString() ComTypeDesc ctd = _comTypeDesc; string typeName = null; - if (ctd != null) + if (ctd is not null) { typeName = ctd.TypeName; } @@ -162,7 +162,7 @@ private static int Invoke(IDispatch dispatch, int memberDispId, out object resul internal bool TryGetGetItem(out ComMethodDesc value) { ComMethodDesc methodDesc = _comTypeDesc.GetItem; - if (methodDesc != null) + if (methodDesc is not null) { value = methodDesc; return true; @@ -193,7 +193,7 @@ private bool SlowTryGetGetItem(out ComMethodDesc value) internal bool TryGetSetItem(out ComMethodDesc value) { ComMethodDesc methodDesc = _comTypeDesc.SetItem; - if (methodDesc != null) + if (methodDesc is not null) { value = methodDesc; return true; @@ -376,7 +376,7 @@ private void EnsureScanDefinedEvents() { // _comTypeDesc.Events is null if we have not yet attempted // to scan the object for events. - if (_comTypeDesc != null && _comTypeDesc.Events != null) + if (_comTypeDesc is not null && _comTypeDesc.Events is not null) { return; } @@ -396,7 +396,7 @@ private void EnsureScanDefinedEvents() lock (s_cacheComTypeDesc) { if (s_cacheComTypeDesc.TryGetValue(typeAttr.guid, out _comTypeDesc) == true && - _comTypeDesc.Events != null) + _comTypeDesc.Events is not null) { return; } @@ -515,10 +515,10 @@ private static void ScanSourceInterface(ComTypes.ITypeInfo sourceTypeInfo, ref D private static ComTypes.ITypeInfo GetCoClassTypeInfo(object rcw, ComTypes.ITypeInfo typeInfo) { - Debug.Assert(typeInfo != null); + Debug.Assert(typeInfo is not null); IProvideClassInfo provideClassInfo = rcw as IProvideClassInfo; - if (provideClassInfo != null) + if (provideClassInfo is not null) { IntPtr typeInfoPtr = IntPtr.Zero; try @@ -561,7 +561,7 @@ private static ComTypes.ITypeInfo GetCoClassTypeInfo(object rcw, ComTypes.ITypeI private void EnsureScanDefinedMethods() { - if (_comTypeDesc != null && _comTypeDesc.Funcs != null) + if (_comTypeDesc is not null && _comTypeDesc.Funcs is not null) { return; } @@ -580,7 +580,7 @@ private void EnsureScanDefinedMethods() lock (s_cacheComTypeDesc) { if (s_cacheComTypeDesc.TryGetValue(typeAttr.guid, out _comTypeDesc) == true && - _comTypeDesc.Funcs != null) + _comTypeDesc.Funcs is not null) { return; } diff --git a/src/System.Management.Automation/engine/ComInterop/IDispatchMetaObject.cs b/src/System.Management.Automation/engine/ComInterop/IDispatchMetaObject.cs index 9a4c9693c27..87584f0ec24 100644 --- a/src/System.Management.Automation/engine/ComInterop/IDispatchMetaObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/IDispatchMetaObject.cs @@ -31,7 +31,7 @@ public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, Dy // See if this is actually a property set ComBinder.ComInvokeMemberBinder comInvokeBinder = binder as ComBinder.ComInvokeMemberBinder; - if ((comInvokeBinder != null) && (comInvokeBinder.IsPropertySet)) + if ((comInvokeBinder is not null) && (comInvokeBinder.IsPropertySet)) { DynamicMetaObject value = args[args.Length - 1]; @@ -51,7 +51,7 @@ public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, Dy } } - if (method != null) + if (method is not null) { List temps = new List(); List initTemps = new List(); @@ -94,7 +94,7 @@ private DynamicMetaObject BindComInvoke(DynamicMetaObject[] args, ComMethodDesc method ).Invoke(); - if ((temps != null) && (temps.Any())) + if ((temps is not null) && (temps.Any())) { Expression invokeExpression = invoke.Expression; Expression call = Expression.Block(invokeExpression.Type, temps, initTemps.Append(invokeExpression)); diff --git a/src/System.Management.Automation/engine/ComInterop/SimpleArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/SimpleArgBuilder.cs index 1df83daf12b..9815e08b1a5 100644 --- a/src/System.Management.Automation/engine/ComInterop/SimpleArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/SimpleArgBuilder.cs @@ -27,13 +27,13 @@ internal SimpleArgBuilder(Type parameterType) internal override Expression Marshal(Expression parameter) { - Debug.Assert(parameter != null); + Debug.Assert(parameter is not null); return Helpers.Convert(parameter, ParameterType); } internal override Expression UnmarshalFromRef(Expression newValue) { - Debug.Assert(newValue != null && newValue.Type.IsAssignableFrom(ParameterType)); + Debug.Assert(newValue is not null && newValue.Type.IsAssignableFrom(ParameterType)); return base.UnmarshalFromRef(newValue); } diff --git a/src/System.Management.Automation/engine/ComInterop/SplatCallSite.cs b/src/System.Management.Automation/engine/ComInterop/SplatCallSite.cs index 07ad10f6bac..5e6a5a111f9 100644 --- a/src/System.Management.Automation/engine/ComInterop/SplatCallSite.cs +++ b/src/System.Management.Automation/engine/ComInterop/SplatCallSite.cs @@ -24,17 +24,17 @@ internal sealed class SplatCallSite internal SplatCallSite(object callable) { - Debug.Assert(callable != null); + Debug.Assert(callable is not null); _callable = callable; } internal object Invoke(object[] args) { - Debug.Assert(args != null); + Debug.Assert(args is not null); // If it is a delegate, just let DynamicInvoke do the binding. var d = _callable as Delegate; - if (d != null) + if (d is not null) { return d.DynamicInvoke(args); } diff --git a/src/System.Management.Automation/engine/ComInterop/TypeLibMetaObject.cs b/src/System.Management.Automation/engine/ComInterop/TypeLibMetaObject.cs index a4eab6f7ad5..c1f5c442db1 100644 --- a/src/System.Management.Automation/engine/ComInterop/TypeLibMetaObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/TypeLibMetaObject.cs @@ -65,7 +65,7 @@ public override DynamicMetaObject BindGetMember(GetMemberBinder binder) public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) { var result = TryBindGetMember(binder.Name); - if (result != null) + if (result is not null) { return binder.FallbackInvoke(result, args, null); } diff --git a/src/System.Management.Automation/engine/ComInterop/TypeUtils.cs b/src/System.Management.Automation/engine/ComInterop/TypeUtils.cs index ab82f854f28..aef20738f33 100644 --- a/src/System.Management.Automation/engine/ComInterop/TypeUtils.cs +++ b/src/System.Management.Automation/engine/ComInterop/TypeUtils.cs @@ -89,7 +89,7 @@ internal static bool IsImplicitlyConvertible(Type source, Type destination) internal static bool IsImplicitlyConvertible(Type source, Type destination, bool considerUserDefined) { return IsImplicitlyConvertible(source, destination) || - (considerUserDefined && GetUserDefinedCoercionMethod(source, destination, true) != null); + (considerUserDefined && GetUserDefinedCoercionMethod(source, destination, true) is not null); } // CONFORMING @@ -101,14 +101,14 @@ internal static MethodInfo GetUserDefinedCoercionMethod(Type convertFrom, Type c // try exact match on types MethodInfo[] eMethods = nnExprType.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); MethodInfo method = FindConversionOperator(eMethods, convertFrom, convertToType, implicitOnly); - if (method != null) + if (method is not null) { return method; } MethodInfo[] cMethods = nnConvType.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); method = FindConversionOperator(cMethods, convertFrom, convertToType, implicitOnly); - if (method != null) + if (method is not null) { return method; } @@ -117,7 +117,7 @@ internal static MethodInfo GetUserDefinedCoercionMethod(Type convertFrom, Type c { method = FindConversionOperator(eMethods, nnExprType, nnConvType, implicitOnly) ?? FindConversionOperator(cMethods, nnExprType, nnConvType, implicitOnly); - if (method != null) + if (method is not null) { return method; } diff --git a/src/System.Management.Automation/engine/ComInterop/Variant.cs b/src/System.Management.Automation/engine/ComInterop/Variant.cs index 0e1561fbe17..70bdb2d1383 100644 --- a/src/System.Management.Automation/engine/ComInterop/Variant.cs +++ b/src/System.Management.Automation/engine/ComInterop/Variant.cs @@ -766,7 +766,7 @@ public string AsBstr { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_BSTR; - if (value != null) + if (value is not null) { Marshal.GetNativeVariantForObject(value, UnsafeMethods.ConvertVariantByrefToPtr(ref this)); } @@ -800,7 +800,7 @@ public object AsUnknown { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_UNKNOWN; - if (value != null) + if (value is not null) { _typeUnion._unionTypes._unknown = Marshal.GetIUnknownForObject(value); } @@ -834,7 +834,7 @@ public object AsDispatch { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise VariantType = VarEnum.VT_DISPATCH; - if (value != null) + if (value is not null) { _typeUnion._unionTypes._unknown = Marshal.GetIDispatchForObject(value); } @@ -864,7 +864,7 @@ public object AsVariant set { Debug.Assert(IsEmpty); // The setter can only be called once as VariantClear might be needed otherwise - if (value != null) + if (value is not null) { UnsafeMethods.InitVariantForObject(value, ref this); } diff --git a/src/System.Management.Automation/engine/ComInterop/VariantBuilder.cs b/src/System.Management.Automation/engine/ComInterop/VariantBuilder.cs index 06d449ece27..b4b9a23d8f0 100644 --- a/src/System.Management.Automation/engine/ComInterop/VariantBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/VariantBuilder.cs @@ -116,22 +116,22 @@ internal Expression Clear() { if (_argBuilder is StringArgBuilder) { - Debug.Assert(TempVariable != null); + Debug.Assert(TempVariable is not null); return Expression.Call(typeof(Marshal).GetMethod("FreeBSTR"), TempVariable); } else if (_argBuilder is DispatchArgBuilder) { - Debug.Assert(TempVariable != null); + Debug.Assert(TempVariable is not null); return Release(TempVariable); } else if (_argBuilder is UnknownArgBuilder) { - Debug.Assert(TempVariable != null); + Debug.Assert(TempVariable is not null); return Release(TempVariable); } else if (_argBuilder is VariantArgBuilder) { - Debug.Assert(TempVariable != null); + Debug.Assert(TempVariable is not null); return Expression.Call(TempVariable, typeof(Variant).GetMethod("Clear")); } diff --git a/src/System.Management.Automation/engine/CommandBase.cs b/src/System.Management.Automation/engine/CommandBase.cs index fa952a38a23..d2782fc58dc 100644 --- a/src/System.Management.Automation/engine/CommandBase.cs +++ b/src/System.Management.Automation/engine/CommandBase.cs @@ -125,7 +125,7 @@ internal bool IsStopping get { MshCommandRuntime mcr = this.commandRuntime as MshCommandRuntime; - return (mcr != null && mcr.IsStopping); + return (mcr is not null && mcr.IsStopping); } } @@ -489,7 +489,7 @@ public PathInfo CurrentProviderLocation(string providerId) PathInfo result = SessionState.Path.CurrentProviderLocation(providerId); - Diagnostics.Assert(result != null, "DataStoreAdapterCollection.GetNamespaceCurrentLocation() should " + "throw an exception, not return null"); + Diagnostics.Assert(result is not null, "DataStoreAdapterCollection.GetNamespaceCurrentLocation() should " + "throw an exception, not return null"); return result; } } diff --git a/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs b/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs index 6689cf81fec..9bcad0edc92 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs @@ -157,14 +157,14 @@ public static CommandCompletion CompleteInput(string input, int cursorIndex, Has } // If we are in a debugger stop, let the debugger do the command completion. - var debugger = (powershell.Runspace != null) ? powershell.Runspace.Debugger : null; - if ((debugger != null) && debugger.InBreakpoint) + var debugger = (powershell.Runspace is not null) ? powershell.Runspace.Debugger : null; + if ((debugger is not null) && debugger.InBreakpoint) { return CompleteInputInDebugger(input, cursorIndex, options, debugger); } var remoteRunspace = powershell.Runspace as RemoteRunspace; - if (remoteRunspace != null) + if (remoteRunspace is not null) { // If the runspace is not available to run commands then exit here because nested commands are not // supported on remote runspaces. @@ -236,14 +236,14 @@ public static CommandCompletion CompleteInput(Ast ast, Token[] tokens, IScriptPo } // If we are in a debugger stop, let the debugger do the command completion. - var debugger = (powershell.Runspace != null) ? powershell.Runspace.Debugger : null; - if ((debugger != null) && debugger.InBreakpoint) + var debugger = (powershell.Runspace is not null) ? powershell.Runspace.Debugger : null; + if ((debugger is not null) && debugger.InBreakpoint) { return CompleteInputInDebugger(ast, tokens, cursorPosition, options, debugger); } var remoteRunspace = powershell.Runspace as RemoteRunspace; - if (remoteRunspace != null) + if (remoteRunspace is not null) { // If the runspace is not available to run commands then exit here because nested commands are not // supported on remote runspaces. @@ -412,7 +412,7 @@ private static CommandCompletion ProcessCompleteInputCommand( if (output.Count == 1) { var commandCompletion = output[0].BaseObject as CommandCompletion; - if (commandCompletion != null) + if (commandCompletion is not null) { return commandCompletion; } @@ -428,10 +428,10 @@ private static CommandCompletion ProcessCompleteInputCommand( private static void CheckScriptCallOnRemoteRunspace(RemoteRunspace remoteRunspace) { var remoteRunspaceInternal = remoteRunspace.RunspacePool.RemoteRunspacePoolInternal; - if (remoteRunspaceInternal != null) + if (remoteRunspaceInternal is not null) { var transportManager = remoteRunspaceInternal.DataStructureHandler.TransportManager; - if (transportManager != null && transportManager.TypeTable is null) + if (transportManager is not null && transportManager.TypeTable is null) { // The remote runspace was created without a TypeTable instance. // The tab completion results cannot be deserialized if the TypeTable is not available @@ -459,7 +459,7 @@ private static CommandCompletion CallScriptWithStringParameterSet(string input, { var result = PSObject.Base(results[0]); var commandCompletion = result as CommandCompletion; - if (commandCompletion != null) + if (commandCompletion is not null) { return commandCompletion; } @@ -496,7 +496,7 @@ private static CommandCompletion CallScriptWithAstParameterSet(Ast ast, Token[] { var result = PSObject.Base(results[0]); var commandCompletion = result as CommandCompletion; - if (commandCompletion != null) + if (commandCompletion is not null) { return commandCompletion; } @@ -560,17 +560,17 @@ private static CommandCompletion CompleteInputImpl(Ast ast, Token[] tokens, IScr } SessionStateScope scopeToRestore = null; - if (tupleForFrameToSkipPast != null) + if (tupleForFrameToSkipPast is not null) { // Find this tuple in the scope stack. scopeToRestore = context.EngineSessionState.CurrentScope; var scope = context.EngineSessionState.CurrentScope; - while (scope != null && scope.LocalsTuple != tupleForFrameToSkipPast) + while (scope is not null && scope.LocalsTuple != tupleForFrameToSkipPast) { scope = scope.Parent; } - if (scope != null) + if (scope is not null) { context.EngineSessionState.CurrentScope = scope.Parent; } @@ -585,7 +585,7 @@ private static CommandCompletion CompleteInputImpl(Ast ast, Token[] tokens, IScr } finally { - if (scopeToRestore != null) + if (scopeToRestore is not null) { context.EngineSessionState.CurrentScope = scopeToRestore; } @@ -631,11 +631,11 @@ private static bool NeedToInvokeLegacyTabExpansion(PowerShell powershell) // We don't want command discovery to search unloaded modules for TabExpansion. var functionInfo = executionContext.EngineSessionState.GetFunction("TabExpansion"); - if (functionInfo != null) + if (functionInfo is not null) return true; var aliasInfo = executionContext.EngineSessionState.GetAlias("TabExpansion"); - if (aliasInfo != null) + if (aliasInfo is not null) return true; return false; @@ -655,7 +655,7 @@ private static List InvokeLegacyTabExpansion(PowerShell powers Exception exceptionThrown; var oldResults = helper.ExecuteCurrentPowerShell(out exceptionThrown); - if (oldResults != null) + if (oldResults is not null) { results = new List(); foreach (var oldResult in oldResults) @@ -687,7 +687,7 @@ private static List InvokeLegacyTabExpansion(PowerShell powers results = PSv2CompletionCompleter.PSv2GenerateMatchSetOfFiles(helper, lastword, replacementIndex == 0, quoteStr); var cmdletResults = PSv2CompletionCompleter.PSv2GenerateMatchSetOfCmdlets(helper, lastword, quoteStr, replacementIndex == 0); - if (cmdletResults != null && cmdletResults.Count > 0) + if (cmdletResults is not null && cmdletResults.Count > 0) { results.AddRange(cmdletResults); } @@ -777,7 +777,7 @@ internal static List PSv2GenerateMatchSetOfCmdlets(PowerShellE Exception exceptionThrown; Collection commands = helper.ExecuteCurrentPowerShell(out exceptionThrown); - if (commands != null && commands.Count > 0) + if (commands is not null && commands.Count > 0) { // convert the PSObjects into strings CommandAndName[] cmdlets = new CommandAndName[commands.Count]; @@ -808,7 +808,7 @@ internal static List PSv2GenerateMatchSetOfCmdlets(PowerShellE private static void AddCommandResult(CommandAndName commandAndName, bool useFullName, bool completingAtStartOfLine, string quote, List results) { - Diagnostics.Assert(results != null, "Caller needs to make sure the result list is not null"); + Diagnostics.Assert(results is not null, "Caller needs to make sure the result list is not null"); string name = useFullName ? commandAndName.CommandName.FullName : commandAndName.CommandName.ShortName; string quotedFileName = AddQuoteIfNecessary(name, quote, completingAtStartOfLine); @@ -836,7 +836,7 @@ private static void AddCommandResult(CommandAndName commandAndName, bool useFull private static void PrependSnapInNameForSameCmdletNames(CommandAndName[] cmdlets, bool completingAtStartOfLine, string quote, List results) { - Diagnostics.Assert(cmdlets != null && cmdlets.Length > 0, + Diagnostics.Assert(cmdlets is not null && cmdlets.Length > 0, "HasMultiplePSSnapIns must be called with a non-empty collection of PSObject"); int i = 0; @@ -926,7 +926,7 @@ internal static List PSv2GenerateMatchSetOfFiles(PowerShellExe IEnumerable combinedMatches = CombineMatchSets(s1, s2); - if (combinedMatches != null) + if (combinedMatches is not null) { foreach (var combinedMatch in combinedMatches) { @@ -940,7 +940,7 @@ internal static List PSv2GenerateMatchSetOfFiles(PowerShellExe string childName = SafeGetProperty(combinedMatch.Item, "PSChildName"); string toolTip = PowerShellExecutionHelper.SafeToString(combinedMatch.ConvertedPath); - if (isContainer != null && childName != null && toolTip != null) + if (isContainer is not null && childName is not null && toolTip is not null) { CompletionResultType resultType = isContainer.Value ? CompletionResultType.ProviderContainer @@ -986,8 +986,8 @@ private static IEnumerable CombineMatchSets(List 0, "s1 should have results"); - Diagnostics.Assert(s2 != null && s2.Count > 0, "if s1 has results, s2 must also"); + Diagnostics.Assert(s1 is not null && s1.Count > 0, "s1 should have results"); + Diagnostics.Assert(s2 is not null && s2.Count > 0, "if s1 has results, s2 must also"); Diagnostics.Assert(s1.Count <= s2.Count, "s2 should always be larger than s1"); var result = new List(); @@ -1114,7 +1114,7 @@ private static List PSv2FindMatches(PowerShellExecutio foreach (PSObject t in paths) { var pathsArray = t.BaseObject as IList; - if (pathsArray != null && pathsArray.Count == 3) + if (pathsArray is not null && pathsArray.Count == 3) { object objectPath = pathsArray[0]; PSObject item = pathsArray[1] as PSObject; @@ -1139,7 +1139,7 @@ private static List PSv2FindMatches(PowerShellExecutio result.Sort(delegate (PathItemAndConvertedPath x, PathItemAndConvertedPath y) { - Diagnostics.Assert(x.Path != null && y.Path != null, "SafeToString always returns a non-null string"); + Diagnostics.Assert(x.Path is not null && y.Path is not null, "SafeToString always returns a non-null string"); return string.Compare(x.Path, y.Path, StringComparison.CurrentCultureIgnoreCase); }); @@ -1163,7 +1163,7 @@ internal static string FindLastWord(string sentence, out int replacementIndexOut private LastWordFinder(string sentence) { _replacementIndex = 0; - Diagnostics.Assert(sentence != null, "need to provide an instance"); + Diagnostics.Assert(sentence is not null, "need to provide an instance"); _sentence = sentence; } @@ -1293,7 +1293,7 @@ private void HandleQuote(ref bool inQuote, ref bool inOppositeQuote, char c) private void Consume(char c) { - Diagnostics.Assert(_wordBuffer != null, "wordBuffer is not initialized"); + Diagnostics.Assert(_wordBuffer is not null, "wordBuffer is not initialized"); Diagnostics.Assert(_wordBufferIndex < _wordBuffer.Length, "wordBufferIndex is out of range"); _wordBuffer[_wordBufferIndex++] = c; diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs index 1d6b3a3666d..16792dafd91 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs @@ -114,7 +114,7 @@ private CompletionContext InitializeCompletionContext(TypeInferenceContext typeI if (tokenAtCursor is null) { tokenBeforeCursor = InterstingTokenBeforeCursorOrDefault(_tokens, _cursorPosition); - if (tokenBeforeCursor != null) + if (tokenBeforeCursor is not null) { positionForAstSearch = tokenBeforeCursor.Extent.EndScriptPosition; adjustLineAndColumn = true; @@ -123,7 +123,7 @@ private CompletionContext InitializeCompletionContext(TypeInferenceContext typeI else { var stringExpandableToken = tokenAtCursor as StringExpandableToken; - if (stringExpandableToken?.NestedTokens != null) + if (stringExpandableToken?.NestedTokens is not null) { tokenAtCursor = InterstingTokenAtCursorOrDefault(stringExpandableToken.NestedTokens, _cursorPosition) ?? stringExpandableToken; } @@ -182,7 +182,7 @@ private static bool CompleteAgainstSwitchFile(Ast lastAst, Token tokenBeforeCurs Tuple fileConditionTuple; var errorStatement = lastAst as ErrorStatementAst; - if (errorStatement != null && errorStatement.Flags != null && errorStatement.Kind != null && tokenBeforeCursor != null && + if (errorStatement is not null && errorStatement.Flags is not null && errorStatement.Kind is not null && tokenBeforeCursor is not null && errorStatement.Kind.Kind.Equals(TokenKind.Switch) && errorStatement.Flags.TryGetValue("file", out fileConditionTuple)) { // Handle "switch -file " @@ -232,7 +232,7 @@ private static bool CompleteAgainstStatementFlags(Ast scriptAst, Ast lastAst, To // Handle "switch -f" var errorStatement = lastAst as ErrorStatementAst; - if (errorStatement != null && errorStatement.Kind != null) + if (errorStatement is not null && errorStatement.Kind is not null) { switch (errorStatement.Kind.Kind) { @@ -246,29 +246,29 @@ private static bool CompleteAgainstStatementFlags(Ast scriptAst, Ast lastAst, To // Handle "switch -". Skip cases like "switch ($a) {} - " var scriptBlockAst = scriptAst as ScriptBlockAst; - if (token != null && token.Kind == TokenKind.Minus && scriptBlockAst != null) + if (token is not null && token.Kind == TokenKind.Minus && scriptBlockAst is not null) { var asts = AstSearcher.FindAll(scriptBlockAst, ast => IsCursorAfterExtent(token.Extent.StartScriptPosition, ast.Extent), searchNestedScriptBlocks: true); Ast last = asts.LastOrDefault(); errorStatement = null; - while (last != null) + while (last is not null) { errorStatement = last as ErrorStatementAst; - if (errorStatement != null) { break; } + if (errorStatement is not null) { break; } last = last.Parent; } - if (errorStatement != null && errorStatement.Kind != null) + if (errorStatement is not null && errorStatement.Kind is not null) { switch (errorStatement.Kind.Kind) { case TokenKind.Switch: Tuple value; - if (errorStatement.Flags != null && errorStatement.Flags.TryGetValue(Parser.VERBATIM_ARGUMENT, out value)) + if (errorStatement.Flags is not null && errorStatement.Flags.TryGetValue(Parser.VERBATIM_ARGUMENT, out value)) { if (IsTokenTheSame(value.Item1, token)) { @@ -337,7 +337,7 @@ internal List GetResultHelper(CompletionContext completionCont var tokenAtCursor = completionContext.TokenAtCursor; var lastAst = completionContext.RelatedAsts.Last(); List result = null; - if (tokenAtCursor != null) + if (tokenAtCursor is not null) { replacementIndex = tokenAtCursor.Extent.StartScriptPosition.Offset; replacementLength = tokenAtCursor.Extent.EndScriptPosition.Offset - replacementIndex; @@ -367,7 +367,7 @@ internal List GetResultHelper(CompletionContext completionCont completionContext.WordToComplete = tokenAtCursor.Text; var cmdAst = lastAst.Parent as CommandAst; - if (lastAst is StringConstantExpressionAst && cmdAst != null && cmdAst.CommandElements.Count == 1) + if (lastAst is StringConstantExpressionAst && cmdAst is not null && cmdAst.CommandElements.Count == 1) { result = CompleteFileNameAsCommand(completionContext); break; @@ -564,7 +564,7 @@ internal List GetResultHelper(CompletionContext completionCont DynamicKeywordStatementAst keywordAst; ConfigurationDefinitionAst configureAst = GetAncestorConfigurationAstAndKeywordAst( completionContext.CursorPosition, lastAst, out keywordAst); - Diagnostics.Assert(configureAst != null, "ConfigurationDefinitionAst should never be null"); + Diagnostics.Assert(configureAst is not null, "ConfigurationDefinitionAst should never be null"); bool matched = false; completionContext.WordToComplete = tokenAtCursor.Text.Trim(); // Current token is within ConfigurationDefinitionAst or DynamicKeywordStatementAst @@ -626,7 +626,7 @@ internal List GetResultHelper(CompletionContext completionCont // Handle the command name completion var commandNameResult = CompletionCompleters.CompleteCommand(completionContext); - if (commandNameResult != null && commandNameResult.Count > 0) + if (commandNameResult is not null && commandNameResult.Count > 0) { result.AddRange(commandNameResult); } @@ -646,7 +646,7 @@ internal List GetResultHelper(CompletionContext completionCont bool isCursorLineEmpty = string.IsNullOrWhiteSpace(cursor.Line); var tokenBeforeCursor = completionContext.TokenBeforeCursor; bool isLineContinuationBeforeCursor = false; - if (tokenBeforeCursor != null) + if (tokenBeforeCursor is not null) { // // Handle following scenario, cursor is in next line and after a command call, @@ -686,13 +686,13 @@ internal List GetResultHelper(CompletionContext completionCont // e.g., // new-object System.Drawing.Point -prop @{ X = 100; Y = <- Incomplete line // new-object new-object System.Drawing.Point -prop @{ X = <- Tab will yield hash properties. - if (hashTableAst != null && + if (hashTableAst is not null && CheckForPendingAssignment(hashTableAst)) { return result; } - if (hashTableAst != null) + if (hashTableAst is not null) { completionContext.ReplacementIndex = replacementIndex = completionContext.CursorPosition.Offset; completionContext.ReplacementLength = replacementLength = 0; @@ -712,8 +712,8 @@ internal List GetResultHelper(CompletionContext completionCont // Ignore the auto completion if there is a backtick character in previous line // bool cursorAtLineContinuation; - if ((tokenAtCursor != null && tokenAtCursor.Kind == TokenKind.LineContinuation) || - (tokenBeforeCursor != null && tokenBeforeCursor.Kind == TokenKind.LineContinuation)) + if ((tokenAtCursor is not null && tokenAtCursor.Kind == TokenKind.LineContinuation) || + (tokenBeforeCursor is not null && tokenBeforeCursor.Kind == TokenKind.LineContinuation)) cursorAtLineContinuation = true; else cursorAtLineContinuation = false; @@ -734,7 +734,7 @@ internal List GetResultHelper(CompletionContext completionCont { DynamicKeywordStatementAst keywordAst; ConfigurationDefinitionAst configAst = GetAncestorConfigurationAstAndKeywordAst(cursor, lastAst, out keywordAst); - if (configAst != null) + if (configAst is not null) { bool matched; result = GetResultForIdentifierInConfiguration(completionContext, configAst, keywordAst, out matched); @@ -743,7 +743,7 @@ internal List GetResultHelper(CompletionContext completionCont } else if (completionContext.TokenAtCursor is null) { - if (tokenBeforeCursor != null) + if (tokenBeforeCursor is not null) { // // Handle auto completion for enum/dependson property of DSC resource, @@ -797,7 +797,7 @@ internal List GetResultHelper(CompletionContext completionCont } } - if (result != null && result.Count > 0) + if (result is not null && result.Count > 0) { completionContext.ReplacementIndex = replacementIndex = completionContext.CursorPosition.Offset; completionContext.ReplacementLength = replacementLength = 0; @@ -832,20 +832,20 @@ internal List GetResultHelper(CompletionContext completionCont { var typeAst = completionContext.RelatedAsts.OfType().FirstOrDefault(); TypeName typeNameToComplete = null; - if (typeAst != null) + if (typeAst is not null) { typeNameToComplete = FindTypeNameToComplete(typeAst.TypeName, _cursorPosition); } else { var typeConstraintAst = completionContext.RelatedAsts.OfType().FirstOrDefault(); - if (typeConstraintAst != null) + if (typeConstraintAst is not null) { typeNameToComplete = FindTypeNameToComplete(typeConstraintAst.TypeName, _cursorPosition); } } - if (typeNameToComplete != null) + if (typeNameToComplete is not null) { // See if the typename to complete really is within the typename, and if so, which one, in the case of generics. @@ -885,7 +885,7 @@ private List GetResultForHashtable(CompletionContext completio HashtableAst tempHashtableAst = null; IScriptPosition cursor = completionContext.CursorPosition; var hashTableAst = lastAst as HashtableAst; - if (hashTableAst != null) + if (hashTableAst is not null) { // Check if the cursor within the hashtable if (cursor.Offset < hashTableAst.Extent.EndOffset) @@ -909,10 +909,10 @@ private List GetResultForHashtable(CompletionContext completio hashTableAst = Ast.GetAncestorHashtableAst(lastAst, out lastChildofHashtableAst); // Check if the hashtable within a DynamicKeyword statement - if (hashTableAst != null) + if (hashTableAst is not null) { var keywordAst = Ast.GetAncestorAst(hashTableAst); - if (keywordAst != null) + if (keywordAst is not null) { // Handle only empty line if (string.IsNullOrWhiteSpace(cursor.Line)) @@ -929,7 +929,7 @@ private List GetResultForHashtable(CompletionContext completio } hashTableAst = tempHashtableAst; - if (hashTableAst != null) + if (hashTableAst is not null) { completionContext.ReplacementIndex = completionContext.CursorPosition.Offset; completionContext.ReplacementLength = 0; @@ -957,7 +957,7 @@ private bool CheckForPendingAssignment(HashtableAst hashTableAst) internal static TypeName FindTypeNameToComplete(ITypeName type, IScriptPosition cursor) { var typeName = type as TypeName; - if (typeName != null) + if (typeName is not null) { // If the cursor is at the start offset, it's not really inside, so return null. // If the cursor is at the end offset, it's not really inside, but it's just before the cursor, @@ -968,15 +968,15 @@ internal static TypeName FindTypeNameToComplete(ITypeName type, IScriptPosition } var genericTypeName = type as GenericTypeName; - if (genericTypeName != null) + if (genericTypeName is not null) { typeName = FindTypeNameToComplete(genericTypeName.TypeName, cursor); - if (typeName != null) + if (typeName is not null) return typeName; foreach (var t in genericTypeName.GenericArguments) { typeName = FindTypeNameToComplete(t, cursor); - if (typeName != null) + if (typeName is not null) return typeName; } @@ -984,7 +984,7 @@ internal static TypeName FindTypeNameToComplete(ITypeName type, IScriptPosition } var arrayTypeName = type as ArrayTypeName; - if (arrayTypeName != null) + if (arrayTypeName is not null) { return FindTypeNameToComplete(arrayTypeName.ElementType, cursor) ?? null; } @@ -1135,7 +1135,7 @@ private static bool TryGetTypeConstraintOnVariable( } } - return typeConstraint != null || setConstraint != null; + return typeConstraint is not null || setConstraint is not null; } private static bool TryGetCompletionsForVariableAssignment( @@ -1147,7 +1147,7 @@ bool TryGetResultForEnum(Type typeConstraint, CompletionContext completionContex { completions = null; - if (typeConstraint != null && typeConstraint.IsEnum) + if (typeConstraint is not null && typeConstraint.IsEnum) { completions = GetResultForEnum(typeConstraint, completionContext); return true; @@ -1160,7 +1160,7 @@ bool TryGetResultForSet(Type typeConstraint, ValidateSetAttribute setConstraint, { completions = null; - if (setConstraint?.ValidValues != null) + if (setConstraint?.ValidValues is not null) { completions = GetResultForSet(typeConstraint, setConstraint.ValidValues, completionContext); return true; @@ -1224,7 +1224,7 @@ private static List GetResultForSet( var allValues = new List(); foreach (string value in validValues) { - if (typeConstraint != null && (typeConstraint == typeof(string) || typeConstraint.IsEnum)) + if (typeConstraint is not null && (typeConstraint == typeof(string) || typeConstraint.IsEnum)) { allValues.Add(GetQuotedString(value, completionContext)); } @@ -1242,7 +1242,7 @@ private static List GetMatchedResults( CompletionContext completionContext) { var stringToComplete = string.Empty; - if (completionContext.TokenAtCursor != null && completionContext.TokenAtCursor.Kind != TokenKind.Equals) + if (completionContext.TokenAtCursor is not null && completionContext.TokenAtCursor.Kind != TokenKind.Equals) { stringToComplete = completionContext.TokenAtCursor.Text; } @@ -1275,7 +1275,7 @@ private static string GetQuotedString( CompletionContext completionContext) { var stringToComplete = string.Empty; - if (completionContext.TokenAtCursor != null) + if (completionContext.TokenAtCursor is not null) { stringToComplete = completionContext.TokenAtCursor.Text; } @@ -1312,19 +1312,19 @@ private List GetResultForEnumPropertyValueOfDSCResource( var lastAst = completionContext.RelatedAsts.Last(); Ast lastChildofHashtableAst; var hashTableAst = Ast.GetAncestorHashtableAst(lastAst, out lastChildofHashtableAst); - Diagnostics.Assert(stringToComplete != null, "stringToComplete should never be null"); + Diagnostics.Assert(stringToComplete is not null, "stringToComplete should never be null"); // Check if the hashtable within a DynamicKeyword statement - if (hashTableAst != null) + if (hashTableAst is not null) { var keywordAst = Ast.GetAncestorAst(hashTableAst); - if (keywordAst != null) + if (keywordAst is not null) { IScriptPosition cursor = completionContext.CursorPosition; var keyValuePairWithCursor = GetHashEntryContainsCursor(cursor, hashTableAst, isCursorInString); - if (keyValuePairWithCursor != null) + if (keyValuePairWithCursor is not null) { var propertyNameAst = keyValuePairWithCursor.Item1 as StringConstantExpressionAst; - if (propertyNameAst != null) + if (propertyNameAst is not null) { DynamicKeywordProperty property; if (keywordAst.Keyword.Properties.TryGetValue(propertyNameAst.Value, out property)) @@ -1334,14 +1334,14 @@ private List GetResultForEnumPropertyValueOfDSCResource( bool isDependsOnProperty = string.Equals(property.Name, @"DependsOn", StringComparison.OrdinalIgnoreCase); bool hasNewLine = false; string stringQuote = (completionContext.TokenAtCursor is StringExpandableToken) ? "\"" : "'"; - if ((property.ValueMap != null && property.ValueMap.Count > 0) || isDependsOnProperty) + if ((property.ValueMap is not null && property.ValueMap.Count > 0) || isDependsOnProperty) { shouldContinue = false; existingValues = new List(); if (string.Equals(property.TypeConstraint, "StringArray", StringComparison.OrdinalIgnoreCase)) { var arrayAst = Ast.GetAncestorAst(lastAst); - if (arrayAst != null && arrayAst.Elements.Count > 0) + if (arrayAst is not null && arrayAst.Elements.Count > 0) { foreach (ExpressionAst expression in arrayAst.Elements) { @@ -1350,7 +1350,7 @@ private List GetResultForEnumPropertyValueOfDSCResource( // DependsOn='[user]x',| // var stringAst = expression as StringConstantExpressionAst; - if (stringAst != null && IsCursorOutsideOfExtent(cursor, expression.Extent)) + if (stringAst is not null && IsCursorOutsideOfExtent(cursor, expression.Extent)) { existingValues.Add(stringAst.Value); } @@ -1382,7 +1382,7 @@ private List GetResultForEnumPropertyValueOfDSCResource( } Diagnostics.Assert(isCursorInString || (!hasNewLine), "hasNoQuote and hasNewLine cannot be true at the same time"); - if (property.ValueMap != null && property.ValueMap.Count > 0) + if (property.ValueMap is not null && property.ValueMap.Count > 0) { IEnumerable orderedValues = property.ValueMap.Keys.OrderBy(x => x).Where(v => !existingValues.Contains(v, StringComparer.OrdinalIgnoreCase)); var matchedResults = orderedValues.Where(v => wildcardPattern.IsMatch(v)); @@ -1407,16 +1407,16 @@ private List GetResultForEnumPropertyValueOfDSCResource( else if (isDependsOnProperty) { var configAst = Ast.GetAncestorAst(keywordAst); - if (configAst != null) + if (configAst is not null) { var namedBlockAst = Ast.GetAncestorAst(keywordAst); - if (namedBlockAst != null) + if (namedBlockAst is not null) { List allResources = new List(); foreach (var statementAst in namedBlockAst.Statements) { var dynamicKeywordAst = statementAst as DynamicKeywordStatementAst; - if (dynamicKeywordAst != null && + if (dynamicKeywordAst is not null && dynamicKeywordAst != keywordAst && !string.Equals(dynamicKeywordAst.Keyword.Keyword, @"Node", StringComparison.OrdinalIgnoreCase)) { @@ -1479,13 +1479,13 @@ private List GetResultForString(CompletionContext completionCo var constantString = lastAst as StringConstantExpressionAst; if (constantString is null && expandableString is null) { return null; } - string strValue = constantString != null ? constantString.Value : expandableString.Value; - StringConstantType strType = constantString != null ? constantString.StringConstantType : expandableString.StringConstantType; + string strValue = constantString is not null ? constantString.Value : expandableString.Value; + StringConstantType strType = constantString is not null ? constantString.StringConstantType : expandableString.StringConstantType; string subInput = null; bool shouldContinue; result = GetResultForEnumPropertyValueOfDSCResource(completionContext, strValue, ref replacementIndex, ref replacementLength, out shouldContinue); - if (!shouldContinue || (result != null && result.Count > 0)) + if (!shouldContinue || (result is not null && result.Count > 0)) { return result; } @@ -1504,7 +1504,7 @@ private List GetResultForString(CompletionContext completionCo } // Handle variable/member completion - if (subInput != null) + if (subInput is not null) { int stringStartIndex = tokenAtCursor.Extent.StartScriptPosition.Offset; int cursorIndexInString = _cursorPosition.Offset - stringStartIndex - 1; @@ -1516,7 +1516,7 @@ private List GetResultForString(CompletionContext completionCo var subResult = analysis.GetResultHelper(subContext, out int subReplaceIndex, out _, true); - if (subResult != null && subResult.Count > 0) + if (subResult is not null && subResult.Count > 0) { result = new List(); replacementIndex = stringStartIndex + 1 + (cursorIndexInString - subInput.Length); @@ -1546,7 +1546,7 @@ private List GetResultForString(CompletionContext completionCo string wordToComplete = CompletionCompleters.ConcatenateStringPathArguments(commandElementAst, string.Empty, completionContext); - if (wordToComplete != null) + if (wordToComplete is not null) { completionContext.WordToComplete = wordToComplete; @@ -1567,7 +1567,7 @@ private List GetResultForString(CompletionContext completionCo if (wordToComplete.Contains('-')) { var commandNameResult = CompletionCompleters.CompleteCommand(completionContext); - if (commandNameResult != null && commandNameResult.Count > 0) + if (commandNameResult is not null && commandNameResult.Count > 0) { result.AddRange(commandNameResult); } @@ -1595,7 +1595,7 @@ private ConfigurationDefinitionAst GetAncestorConfigurationAstAndKeywordAst( // Find the configuration statement contains current cursor // Note: cursorPosition.Offset < configureAst.Extent.EndOffset means cursor locates inside the configuration // cursorPosition.Offset = configureAst.Extent.EndOffset means cursor locates at the end of the configuration - while (configureAst != null && cursorPosition.Offset > configureAst.Extent.EndOffset) + while (configureAst is not null && cursorPosition.Offset > configureAst.Extent.EndOffset) { configureAst = Ast.GetAncestorAst(configureAst.Parent); } @@ -1642,10 +1642,10 @@ private List GetResultForIdentifierInConfiguration( ) ); - if (keywordAst != null && completionContext.CursorPosition.Offset < keywordAst.Extent.EndOffset) + if (keywordAst is not null && completionContext.CursorPosition.Offset < keywordAst.Extent.EndOffset) keywords = keywordAst.Keyword.GetAllowedKeywords(keywords); - if (keywords != null && keywords.Any()) + if (keywords is not null && keywords.Any()) { string commandName = (completionContext.WordToComplete ?? string.Empty) + "*"; var wildcardPattern = WildcardPattern.Get(commandName, WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); @@ -1691,7 +1691,7 @@ private List GetResultForIdentifier(CompletionContext completi completionContext.WordToComplete = tokenAtCursorText; var strConst = lastAst as StringConstantExpressionAst; - if (strConst != null) + if (strConst is not null) { if (strConst.Value.Equals("$", StringComparison.Ordinal)) { @@ -1701,7 +1701,7 @@ private List GetResultForIdentifier(CompletionContext completi else { UsingStatementAst usingState = strConst.Parent as UsingStatementAst; - if (usingState != null) + if (usingState is not null) { completionContext.ReplacementIndex = strConst.Extent.StartOffset; completionContext.ReplacementLength = strConst.Extent.EndOffset - replacementIndex; @@ -1730,7 +1730,7 @@ private List GetResultForIdentifier(CompletionContext completi } var moduleResults = CompletionCompleters.CompleteModuleName(completionContext, false); - if (moduleResults != null && moduleResults.Count > 0) + if (moduleResults is not null && moduleResults.Count > 0) result.AddRange(moduleResults); return result; case UsingStatementKind.Namespace: @@ -1746,7 +1746,7 @@ private List GetResultForIdentifier(CompletionContext completi } result = GetResultForAttributeArgument(completionContext, ref replacementIndex, ref replacementLength); - if (result != null) return result; + if (result is not null) return result; if ((tokenAtCursor.TokenFlags & TokenFlags.CommandName) != 0) { @@ -1763,7 +1763,7 @@ private List GetResultForIdentifier(CompletionContext completi cursorAst = GetLastAstAtCursor(scriptBlockAst, cursorBeforeCmdName); } - if (cursorAst != null && + if (cursorAst is not null && cursorAst.Extent.EndLineNumber == tokenAtCursor.Extent.StartLineNumber && cursorAst.Extent.EndColumnNumber == tokenAtCursor.Extent.StartColumnNumber) { @@ -1771,7 +1771,7 @@ private List GetResultForIdentifier(CompletionContext completi { string wordToComplete = CompletionCompleters.ConcatenateStringPathArguments(cursorAst as CommandElementAst, tokenAtCursorText, completionContext); - if (wordToComplete != null) + if (wordToComplete is not null) { completionContext.WordToComplete = wordToComplete; result = new List(CompletionCompleters.CompleteFilename(completionContext)); @@ -1786,7 +1786,7 @@ private List GetResultForIdentifier(CompletionContext completi else { var variableAst = cursorAst as VariableExpressionAst; - string fullPath = variableAst != null + string fullPath = variableAst is not null ? CompletionCompleters.CombineVariableWithPartialPath( variableAst: variableAst, extraText: tokenAtCursorText, @@ -1817,7 +1817,7 @@ private List GetResultForIdentifier(CompletionContext completi // Handle the StringExpandableToken; var strToken = tokenAtCursor as StringExpandableToken; - if (strToken != null && strToken.NestedTokens != null && strConst != null) + if (strToken is not null && strToken.NestedTokens is not null && strConst is not null) { try { @@ -1848,7 +1848,7 @@ private List GetResultForIdentifier(CompletionContext completi ConfigurationDefinitionAst configureAst = GetAncestorConfigurationAstAndKeywordAst(completionContext.CursorPosition, lastAst, out keywordAst); bool matched = false; List keywordResult = null; - if (configureAst != null) + if (configureAst is not null) { // Current token is within ConfigurationDefinitionAst or DynamicKeywordStatementAst keywordResult = GetResultForIdentifierInConfiguration(completionContext, configureAst, keywordAst, out matched); @@ -1859,16 +1859,16 @@ private List GetResultForIdentifier(CompletionContext completi // Handle the command name completion var commandNameResult = CompletionCompleters.CompleteCommand(completionContext); - if (commandNameResult != null && commandNameResult.Count > 0) + if (commandNameResult is not null && commandNameResult.Count > 0) { result.AddRange(commandNameResult); } - if (matched && keywordResult != null) + if (matched && keywordResult is not null) { result.InsertRange(0, keywordResult); } - else if (!matched && keywordResult != null && commandNameResult.Count == 0) + else if (!matched && keywordResult is not null && commandNameResult.Count == 0) { result.AddRange(keywordResult); } @@ -1924,7 +1924,7 @@ private List GetResultForIdentifier(CompletionContext completi var memberExpressionAst = binaryExpressionAst.Left as MemberExpressionAst; var errorPosition = binaryExpressionAst.ErrorPosition; - if (memberExpressionAst != null && binaryExpressionAst.Operator == TokenKind.Multiply && + if (memberExpressionAst is not null && binaryExpressionAst.Operator == TokenKind.Multiply && errorPosition.StartOffset == memberExpressionAst.Member.Extent.EndOffset) { isStatic = memberExpressionAst.Static; @@ -1938,7 +1938,7 @@ private List GetResultForIdentifier(CompletionContext completi completionContext.RelatedAsts.Add(memberExpressionAst); var memberAst = memberExpressionAst.Member as StringConstantExpressionAst; - if (memberAst != null) + if (memberAst is not null) { replacementIndex = memberAst.Extent.StartScriptPosition.Offset; replacementLength += memberAst.Extent.Text.Length; @@ -1969,7 +1969,7 @@ private List GetResultForIdentifier(CompletionContext completi if (lastAst.Parent is HashtableAst) { result = CompletionCompleters.CompleteHashtableKey(completionContext, (HashtableAst)lastAst.Parent); - if (result != null && result.Count > 0) + if (result is not null && result.Count > 0) { return result; } @@ -1983,7 +1983,7 @@ private List GetResultForIdentifier(CompletionContext completi { string wordToComplete = CompletionCompleters.ConcatenateStringPathArguments(lastAst as CommandElementAst, string.Empty, completionContext); - if (wordToComplete != null) + if (wordToComplete is not null) { needFileCompletion = true; completionContext.WordToComplete = wordToComplete; @@ -1992,17 +1992,17 @@ private List GetResultForIdentifier(CompletionContext completi else if (tokenAtCursorText.IndexOfAny(Utils.Separators.Directory) == 0) { var command = lastAst.Parent as CommandBaseAst; - if (command != null && command.Redirections.Count > 0) + if (command is not null && command.Redirections.Count > 0) { var fileRedirection = command.Redirections[0] as FileRedirectionAst; - if (fileRedirection != null && + if (fileRedirection is not null && fileRedirection.Extent.EndLineNumber == lastAst.Extent.StartLineNumber && fileRedirection.Extent.EndColumnNumber == lastAst.Extent.StartColumnNumber) { string wordToComplete = CompletionCompleters.ConcatenateStringPathArguments(fileRedirection.Location, tokenAtCursorText, completionContext); - if (wordToComplete != null) + if (wordToComplete is not null) { needFileCompletion = true; completionContext.WordToComplete = wordToComplete; @@ -2024,7 +2024,7 @@ private List GetResultForIdentifier(CompletionContext completi { string wordToComplete = CompletionCompleters.ConcatenateStringPathArguments(lastAst as CommandElementAst, string.Empty, completionContext); - if (wordToComplete != null) + if (wordToComplete is not null) { completionContext.WordToComplete = wordToComplete; } @@ -2043,7 +2043,7 @@ private List GetResultForAttributeArgument(CompletionContext c string argName = string.Empty; Ast argAst = completionContext.RelatedAsts.Find(ast => ast is NamedAttributeArgumentAst); NamedAttributeArgumentAst namedArgAst = argAst as NamedAttributeArgumentAst; - if (argAst != null && namedArgAst != null) + if (argAst is not null && namedArgAst is not null) { attributeType = ((AttributeAst)namedArgAst.Parent).TypeName.GetReflectionAttributeType(); argName = namedArgAst.ArgumentName; @@ -2054,13 +2054,13 @@ private List GetResultForAttributeArgument(CompletionContext c { Ast astAtt = completionContext.RelatedAsts.Find(ast => ast is AttributeAst); AttributeAst attAst = astAtt as AttributeAst; - if (astAtt != null && attAst != null) + if (astAtt is not null && attAst is not null) { attributeType = attAst.TypeName.GetReflectionAttributeType(); } } - if (attributeType != null) + if (attributeType is not null) { PropertyInfo[] propertyInfos = attributeType.GetProperties(BindingFlags.Public | BindingFlags.Instance); List result = new List(); diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index 61fdb8f5489..6a8d33b861e 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -95,21 +95,21 @@ private static List CompleteCommand(CompletionContext context, // The name to complete is neither module qualified nor is it a relative/rooted file path. Ast lastAst = null; - if (context.RelatedAsts != null && context.RelatedAsts.Count > 0) + if (context.RelatedAsts is not null && context.RelatedAsts.Count > 0) { lastAst = context.RelatedAsts.Last(); } commandResults = ExecuteGetCommandCommand(useModulePrefix: false); - if (lastAst != null) + if (lastAst is not null) { // We need to add the wildcard to the end so the regex is built correctly. commandName += "*"; // Search the asts for function definitions that we might be calling var findFunctionsVisitor = new FindFunctionsVisitor(); - while (lastAst.Parent != null) + while (lastAst.Parent is not null) { lastAst = lastAst.Parent; } @@ -153,7 +153,7 @@ List ExecuteGetCommandCommand(bool useModulePrefix) .AddParameter("All") .AddParameter("Name", commandName + "*"); - if (moduleName != null) + if (moduleName is not null) { powershell.AddParameter("Module", moduleName); } @@ -176,7 +176,7 @@ List ExecuteGetCommandCommand(bool useModulePrefix) .AddParameter("Name", commandName) .AddParameter("UseAbbreviationExpansion"); - if (moduleName != null) + if (moduleName is not null) { powershell.AddParameter("Module", moduleName); } @@ -191,7 +191,7 @@ List ExecuteGetCommandCommand(bool useModulePrefix) List completionResults = null; - if (commandInfos != null && commandInfos.Count > 1) + if (commandInfos is not null && commandInfos.Count > 1) { // OrderBy is using stable sorting var sortedCommandInfos = commandInfos.OrderBy(a => a, new CommandNameComparer()); @@ -214,7 +214,7 @@ internal static CompletionResult GetCommandNameCompletionResult(string name, obj string syntax = name, listItem = name; var commandInfo = command as CommandInfo; - if (commandInfo != null) + if (commandInfo is not null) { try { @@ -280,7 +280,7 @@ internal static List MakeCommandsUnique(IEnumerable string name = null; var commandInfo = baseObj as CommandInfo; - if (commandInfo != null) + if (commandInfo is not null) { // Skip the private commands if (commandInfo.Visibility == SessionStateEntryVisibility.Private) { continue; } @@ -314,7 +314,7 @@ internal static List MakeCommandsUnique(IEnumerable else { var list = value as List; - if (list != null) + if (list is not null) { list.Add(baseObj); } @@ -330,7 +330,7 @@ internal static List MakeCommandsUnique(IEnumerable foreach (var keyValuePair in commandTable) { var commandList = keyValuePair.Value as List; - if (commandList != null) + if (commandList is not null) { if (endResults is null) { @@ -344,7 +344,7 @@ internal static List MakeCommandsUnique(IEnumerable if (!includeModulePrefix) { var commandInfo = commandList[0] as CommandInfo; - if (commandInfo != null && !string.IsNullOrEmpty(commandInfo.Prefix)) + if (commandInfo is not null && !string.IsNullOrEmpty(commandInfo.Prefix)) { Diagnostics.Assert(!string.IsNullOrEmpty(commandInfo.ModuleName), "the module name should exist if commandInfo.Prefix is not an empty string"); if (!ModuleCmdletBase.IsPrefixedCommand(commandInfo)) @@ -363,7 +363,7 @@ internal static List MakeCommandsUnique(IEnumerable for (int index = 1; index < commandList.Count; index++) { var commandInfo = commandList[index] as CommandInfo; - Diagnostics.Assert(commandInfo != null, "Elements should always be CommandInfo"); + Diagnostics.Assert(commandInfo is not null, "Elements should always be CommandInfo"); if (commandInfo.CommandType == CommandTypes.Application) { @@ -385,7 +385,7 @@ internal static List MakeCommandsUnique(IEnumerable if (!includeModulePrefix) { var commandInfo = keyValuePair.Value as CommandInfo; - if (commandInfo != null && !string.IsNullOrEmpty(commandInfo.Prefix)) + if (commandInfo is not null && !string.IsNullOrEmpty(commandInfo.Prefix)) { Diagnostics.Assert(!string.IsNullOrEmpty(commandInfo.ModuleName), "the module name should exist if commandInfo.Prefix is not an empty string"); if (!ModuleCmdletBase.IsPrefixedCommand(commandInfo)) @@ -399,7 +399,7 @@ internal static List MakeCommandsUnique(IEnumerable } } - if (endResults != null && endResults.Count > 0) + if (endResults is not null && endResults.Count > 0) { results.AddRange(endResults); } @@ -448,7 +448,7 @@ internal static List CompleteModuleName(CompletionContext cont Exception exceptionThrown; var psObjects = context.Helper.ExecuteCurrentPowerShell(out exceptionThrown); - if (psObjects != null) + if (psObjects is not null) { foreach (dynamic moduleInfo in psObjects) { @@ -497,17 +497,17 @@ internal static List CompleteCommandParameter(CompletionContex if (keywordAst is null) keywordAst = context.RelatedAsts[i] as DynamicKeywordStatementAst; parameterAst = (context.RelatedAsts[i] as CommandParameterAst); - if (parameterAst != null) break; + if (parameterAst is not null) break; } - if (parameterAst != null) + if (parameterAst is not null) { keywordAst = parameterAst.Parent as DynamicKeywordStatementAst; } // If parent is DynamicKeywordStatementAst - 'Import-DscResource', // then customize the auto completion results - if (keywordAst != null && string.Equals(keywordAst.Keyword.Keyword, "Import-DscResource", StringComparison.OrdinalIgnoreCase) + if (keywordAst is not null && string.Equals(keywordAst.Keyword.Keyword, "Import-DscResource", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(context.WordToComplete) && context.WordToComplete.StartsWith('-')) { var lastAst = context.RelatedAsts.Last(); @@ -532,7 +532,7 @@ internal static List CompleteCommandParameter(CompletionContex return result; } - if (parameterAst != null) + if (parameterAst is not null) { // Parent must be a command commandAst = (CommandAst)parameterAst.Parent; @@ -692,11 +692,11 @@ private static List GetParameterCompletionResults(string param break; } - if (matchedParameterName != null) + if (matchedParameterName is not null) break; } - Diagnostics.Assert(matchedParameterName != null, "we should find matchedParameterName from the BoundArguments"); + Diagnostics.Assert(matchedParameterName is not null, "we should find matchedParameterName from the BoundArguments"); MergedCompiledCommandParameter param = bindingInfo.BoundParameters[matchedParameterName]; WildcardPattern pattern = WildcardPattern.Get(parameterName + "*", WildcardOptions.IgnoreCase); @@ -758,12 +758,12 @@ private static List GetParameterCompletionResults( // don't show set, we won't show any of the common parameters either. bool showToUser = true; var compiledAttributes = param.Parameter.CompiledAttributes; - if (compiledAttributes != null && compiledAttributes.Count > 0) + if (compiledAttributes is not null && compiledAttributes.Count > 0) { foreach (var attr in compiledAttributes) { var pattr = attr as ParameterAttribute; - if (pattr != null && pattr.DontShow) + if (pattr is not null && pattr.DontShow) { showToUser = false; addCommonParameters = false; @@ -841,7 +841,7 @@ internal static List CompleteCommandArgument(CompletionContext Ast lastAst = context.RelatedAsts.Last(); expressionAst = lastAst as ExpressionAst; - if (expressionAst != null) + if (expressionAst is not null) { if (expressionAst.Parent is CommandAst) { @@ -875,7 +875,7 @@ internal static List CompleteCommandArgument(CompletionContext } var partialPathAst = expressionAst as StringConstantExpressionAst; - if (partialPathAst != null && secondToLastAst != null && + if (partialPathAst is not null && secondToLastAst is not null && partialPathAst.StringConstantType == StringConstantType.BareWord && secondToLastAst.Extent.EndLineNumber == partialPathAst.Extent.StartLineNumber && secondToLastAst.Extent.EndColumnNumber == partialPathAst.Extent.StartColumnNumber && @@ -886,10 +886,10 @@ internal static List CompleteCommandArgument(CompletionContext var secondToLastArrayAst = secondToLastAst as ArrayLiteralAst; var secondToLastParamAst = secondToLastAst as CommandParameterAst; - if (secondToLastStringConstantAst != null || secondToLastExpandableStringAst != null) + if (secondToLastStringConstantAst is not null || secondToLastExpandableStringAst is not null) { var fullPath = ConcatenateStringPathArguments(secondToLastAst, partialPathAst.Value, context); - expressionAst = secondToLastStringConstantAst != null + expressionAst = secondToLastStringConstantAst is not null ? (ExpressionAst)secondToLastStringConstantAst : (ExpressionAst)secondToLastExpandableStringAst; @@ -898,12 +898,12 @@ internal static List CompleteCommandArgument(CompletionContext context.WordToComplete = fullPath; // context.CursorPosition = secondToLastAst.Extent.StartScriptPosition; } - else if (secondToLastArrayAst != null) + else if (secondToLastArrayAst is not null) { // Handle cases like: dir -Path .\cd, 'a b'\new var lastArrayElement = secondToLastArrayAst.Elements.LastOrDefault(); var fullPath = ConcatenateStringPathArguments(lastArrayElement, partialPathAst.Value, context); - if (fullPath != null) + if (fullPath is not null) { expressionAst = secondToLastArrayAst; @@ -912,11 +912,11 @@ internal static List CompleteCommandArgument(CompletionContext context.WordToComplete = fullPath; } } - else if (secondToLastParamAst != null) + else if (secondToLastParamAst is not null) { // Handle cases like: dir -Path: .\cd, 'a b'\new || dir -Path: 'a b'\new var fullPath = ConcatenateStringPathArguments(secondToLastParamAst.Argument, partialPathAst.Value, context); - if (fullPath != null) + if (fullPath is not null) { expressionAst = secondToLastParamAst.Argument; @@ -927,11 +927,11 @@ internal static List CompleteCommandArgument(CompletionContext else { var arrayArgAst = secondToLastParamAst.Argument as ArrayLiteralAst; - if (arrayArgAst != null) + if (arrayArgAst is not null) { var lastArrayElement = arrayArgAst.Elements.LastOrDefault(); fullPath = ConcatenateStringPathArguments(lastArrayElement, partialPathAst.Value, context); - if (fullPath != null) + if (fullPath is not null) { expressionAst = arrayArgAst; @@ -995,7 +995,7 @@ internal static List CompleteCommandArgument(CompletionContext else { var paramAst = lastAst as CommandParameterAst; - if (paramAst != null) + if (paramAst is not null) { commandAst = paramAst.Parent as CommandAst; } @@ -1022,16 +1022,16 @@ internal static List CompleteCommandArgument(CompletionContext bool parsedArgumentsProvidesMatch = false; - if (pseudoBinding.AllParsedArguments != null && pseudoBinding.AllParsedArguments.Count > 0) + if (pseudoBinding.AllParsedArguments is not null && pseudoBinding.AllParsedArguments.Count > 0) { ArgumentLocation argLocation; bool treatAsExpression = false; - if (expressionAst != null) + if (expressionAst is not null) { treatAsExpression = true; var dashExp = expressionAst as StringConstantExpressionAst; - if (dashExp != null && dashExp.Value.Trim().Equals("-", StringComparison.OrdinalIgnoreCase)) + if (dashExp is not null && dashExp.Value.Trim().Equals("-", StringComparison.OrdinalIgnoreCase)) { // "-" is represented as StringConstantExpressionAst. Most likely the user is typing a // after it, so in the pseudo binder, we ignore it to avoid treating it as an argument. @@ -1052,7 +1052,7 @@ internal static List CompleteCommandArgument(CompletionContext pseudoBinding.AllParsedArguments, context.TokenAtCursor ?? context.TokenBeforeCursor); } - if (argLocation != null) + if (argLocation is not null) { context.PseudoBindingInfo = pseudoBinding; switch (pseudoBinding.InfoType) @@ -1073,7 +1073,7 @@ internal static List CompleteCommandArgument(CompletionContext { int index = 0; CommandElementAst prevElem = null; - if (expressionAst != null) + if (expressionAst is not null) { foreach (CommandElementAst eleAst in commandAst.CommandElements) { @@ -1177,7 +1177,7 @@ internal static List CompleteCommandArgument(CompletionContext { // It's actually command name completion, other than argument completion var cmdletCompletionResults = CompleteCommand(context); - if (cmdletCompletionResults != null && cmdletCompletionResults.Count > 0) + if (cmdletCompletionResults is not null && cmdletCompletionResults.Count > 0) { fileCompletionResults.AddRange(cmdletCompletionResults); } @@ -1208,7 +1208,7 @@ internal static List CompleteCommandArgument(CompletionContext out fakeReplacementIndex, out fakeReplacementLength); - if (ret != null && ret.Count > 0) + if (ret is not null && ret.Count > 0) { var prefix = TokenKind.LParen.Text() + input.Substring(0, fakeReplacementIndex); foreach (CompletionResult entry in ret) @@ -1225,7 +1225,7 @@ internal static List CompleteCommandArgument(CompletionContext } // Handle member completion with wildcard: echo $a.* - if (pathAst.Value.Contains('*') && secondToLastMemberAst != null && + if (pathAst.Value.Contains('*') && secondToLastMemberAst is not null && secondToLastMemberAst.Extent.EndLineNumber == pathAst.Extent.StartLineNumber && secondToLastMemberAst.Extent.EndColumnNumber == pathAst.Extent.StartColumnNumber) { @@ -1240,7 +1240,7 @@ internal static List CompleteCommandArgument(CompletionContext } var memberAst = secondToLastMemberAst.Member as StringConstantExpressionAst; - if (memberAst != null) + if (memberAst is not null) { memberName = memberAst.Value + memberName; } @@ -1250,7 +1250,7 @@ internal static List CompleteCommandArgument(CompletionContext { context.ReplacementIndex = ((InternalScriptPosition)secondToLastMemberAst.Expression.Extent.EndScriptPosition).Offset + 1; - if (memberAst != null) + if (memberAst is not null) context.ReplacementLength += memberAst.Value.Length; return result; } @@ -1264,7 +1264,7 @@ internal static List CompleteCommandArgument(CompletionContext commandAst.CommandElements[0].Extent.EndLineNumber == expressionAst.Extent.StartLineNumber && commandAst.CommandElements[0].Extent.EndColumnNumber == expressionAst.Extent.StartColumnNumber) { - if (pseudoBinding != null) + if (pseudoBinding is not null) { // CommandElements[0] is resolved to a command return result; @@ -1301,7 +1301,7 @@ internal static List CompleteCommandArgument(CompletionContext "NativeArgumentCompleters", new[] { commandName, Path.GetFileName(commandName), Path.GetFileNameWithoutExtension(commandName) }, context); - if (customCompleter != null) + if (customCompleter is not null) { if (InvokeScriptArgumentCompleter( customCompleter, @@ -1332,7 +1332,7 @@ internal static List CompleteCommandArgument(CompletionContext if (context.WordToComplete != string.Empty && context.WordToComplete.Contains('-')) { var commandResults = CompleteCommand(context); - if (commandResults != null) + if (commandResults is not null) result.AddRange(commandResults); } } @@ -1343,7 +1343,7 @@ internal static List CompleteCommandArgument(CompletionContext internal static string ConcatenateStringPathArguments(CommandElementAst stringAst, string partialPath, CompletionContext completionContext) { var constantPathAst = stringAst as StringConstantExpressionAst; - if (constantPathAst != null) + if (constantPathAst is not null) { string quote = string.Empty; switch (constantPathAst.StringConstantType) @@ -1364,7 +1364,7 @@ internal static string ConcatenateStringPathArguments(CommandElementAst stringAs { var expandablePathAst = stringAst as ExpandableStringExpressionAst; string fullPath = null; - if (expandablePathAst != null && + if (expandablePathAst is not null && IsPathSafelyExpandable(expandableStringAst: expandablePathAst, extraText: partialPath, executionContext: completionContext.ExecutionContext, @@ -1452,11 +1452,11 @@ private static List GetArgumentCompletionResultsWithSuccessful argLocation.Position, out lastPositionalArg); - if (targetPositionalArg != null) + if (targetPositionalArg is not null) argLocation.Argument = targetPositionalArg; else { - if (lastPositionalArg != null) + if (lastPositionalArg is not null) { bool lastPositionalGetBound = false; Collection parameterNames = new Collection(); @@ -1518,7 +1518,7 @@ private static List GetArgumentCompletionResultsWithSuccessful } } - if (argLocation.Argument != null) + if (argLocation.Argument is not null) { Collection parameterNames = new Collection(); foreach (KeyValuePair entry in bindingInfo.BoundArguments) @@ -1624,7 +1624,7 @@ private static void CompletePositionalArgument( break; } - if (!isProcessedAsPositional && positionalParam != null) + if (!isProcessedAsPositional && positionalParam is not null) { isProcessedAsPositional = true; ProcessParameter(commandName, commandAst, context, result, positionalParam, boundArguments); @@ -1711,7 +1711,7 @@ private static void ProcessParameter( } } - if (fullMatch != null) + if (fullMatch is not null) { result.Add(fullMatch); } @@ -1768,7 +1768,7 @@ private static void ProcessParameter( } } - if (fullMatch != null) + if (fullMatch is not null) { result.Add(fullMatch); } @@ -1838,7 +1838,7 @@ private static IEnumerable NativeCommandArgumentCompletion_InferType case AstParameterArgumentType.PipeObject: { var pipelineAst = commandAst.Parent as PipelineAst; - if (pipelineAst != null) + if (pipelineAst is not null) { int i; for (i = 0; i < pipelineAst.PipelineElements.Count; i++) @@ -1869,16 +1869,16 @@ private static IEnumerable NativeCommandArgumentCompletion_InferType if (argumentExpressionAst is null) { CommandExpressionAst argumentCommandExpressionAst = argumentAst as CommandExpressionAst; - if (argumentCommandExpressionAst != null) + if (argumentCommandExpressionAst is not null) { argumentExpressionAst = argumentCommandExpressionAst.Expression; } } object argumentValue; - if (argumentExpressionAst != null && SafeExprEvaluator.TrySafeEval(argumentExpressionAst, context.ExecutionContext, out argumentValue)) + if (argumentExpressionAst is not null && SafeExprEvaluator.TrySafeEval(argumentExpressionAst, context.ExecutionContext, out argumentValue)) { - if (argumentValue != null) + if (argumentValue is not null) { IEnumerable enumerable = LanguagePrimitives.GetEnumerable(argumentValue) ?? new object[] { argumentValue }; @@ -1944,7 +1944,7 @@ internal static IList NativeCommandArgumentCompletion_ExtractSecondaryAr foreach (ExpressionAst entry in argument.Elements) { var entryAsString = entry as StringConstantExpressionAst; - if (entryAsString != null) + if (entryAsString is not null) { result.Add(entryAsString.Value); } @@ -1966,7 +1966,7 @@ internal static IList NativeCommandArgumentCompletion_ExtractSecondaryAr foreach (ExpressionAst entry in argument) { var entryAsString = entry as StringConstantExpressionAst; - if (entryAsString != null) + if (entryAsString is not null) { result.Add(entryAsString.Value); } @@ -2015,7 +2015,7 @@ private static void NativeCommandArgumentCompletion( new[] { parameterFullName, parameterName }, context); - if (customCompleter != null) + if (customCompleter is not null) { if (InvokeScriptArgumentCompleter( customCompleter, @@ -2027,18 +2027,18 @@ private static void NativeCommandArgumentCompletion( } var argumentCompleterAttribute = parameter.CompiledAttributes.OfType().FirstOrDefault(); - if (argumentCompleterAttribute != null) + if (argumentCompleterAttribute is not null) { try { - if (argumentCompleterAttribute.Type != null) + if (argumentCompleterAttribute.Type is not null) { var completer = Activator.CreateInstance(argumentCompleterAttribute.Type) as IArgumentCompleter; - if (completer != null) + if (completer is not null) { var customResults = completer.CompleteArgument(commandName, parameterName, context.WordToComplete, commandAst, GetBoundArgumentsAsHashtable(context)); - if (customResults != null) + if (customResults is not null) { result.AddRange(customResults); result.Add(CompletionResult.Null); @@ -2063,11 +2063,11 @@ private static void NativeCommandArgumentCompletion( } var argumentCompletionsAttribute = parameter.CompiledAttributes.OfType().FirstOrDefault(); - if (argumentCompletionsAttribute != null) + if (argumentCompletionsAttribute is not null) { var customResults = argumentCompletionsAttribute.CompleteArgument(commandName, parameterName, context.WordToComplete, commandAst, GetBoundArgumentsAsHashtable(context)); - if (customResults != null) + if (customResults is not null) { result.AddRange(customResults); result.Add(CompletionResult.Null); @@ -2128,7 +2128,7 @@ private static void NativeCommandArgumentCompletion( if (parameterName.Equals("Command", StringComparison.OrdinalIgnoreCase)) { var commandResults = CompleteCommand(context); - if (commandResults != null) + if (commandResults is not null) result.AddRange(commandResults); } @@ -2176,7 +2176,7 @@ private static void NativeCommandArgumentCompletion( } case "Import-Module": { - bool skipEditionCheck = boundArguments != null && boundArguments.ContainsKey("SkipEditionCheck"); + bool skipEditionCheck = boundArguments is not null && boundArguments.ContainsKey("SkipEditionCheck"); NativeCompletionModuleCommands(context, parameterName, result, isImportModule: true, skipEditionCheck: skipEditionCheck); break; } @@ -2341,22 +2341,22 @@ private static void NativeCommandArgumentCompletion( private static Hashtable GetBoundArgumentsAsHashtable(CompletionContext context) { var result = new Hashtable(StringComparer.OrdinalIgnoreCase); - if (context.PseudoBindingInfo != null) + if (context.PseudoBindingInfo is not null) { var boundArguments = context.PseudoBindingInfo.BoundArguments; - if (boundArguments != null) + if (boundArguments is not null) { foreach (var boundArgument in boundArguments) { var astPair = boundArgument.Value as AstPair; - if (astPair != null) + if (astPair is not null) { var parameterAst = astPair.Argument as CommandParameterAst; - var exprAst = parameterAst != null + var exprAst = parameterAst is not null ? parameterAst.Argument : astPair.Argument as ExpressionAst; object value; - if (exprAst != null && SafeExprEvaluator.TrySafeEval(exprAst, context.ExecutionContext, out value)) + if (exprAst is not null && SafeExprEvaluator.TrySafeEval(exprAst, context.ExecutionContext, out value)) { result[boundArgument.Key] = value; } @@ -2365,7 +2365,7 @@ private static Hashtable GetBoundArgumentsAsHashtable(CompletionContext context) } var switchPair = boundArgument.Value as SwitchPair; - if (switchPair != null) + if (switchPair is not null) { result[boundArgument.Key] = switchPair.Argument; continue; @@ -2388,17 +2388,17 @@ private static ScriptBlock GetCustomArgumentCompleter( { ScriptBlock scriptBlock; var options = context.Options; - if (options != null) + if (options is not null) { var customCompleters = options[optionKey] as Hashtable; - if (customCompleters != null) + if (customCompleters is not null) { foreach (var key in keys) { if (customCompleters.ContainsKey(key)) { scriptBlock = customCompleters[key] as ScriptBlock; - if (scriptBlock != null) + if (scriptBlock is not null) return scriptBlock; } } @@ -2409,7 +2409,7 @@ private static ScriptBlock GetCustomArgumentCompleter( ? context.NativeArgumentCompleters : context.CustomArgumentCompleters; - if (registeredCompleters != null) + if (registeredCompleters is not null) { foreach (var key in keys) { @@ -2466,7 +2466,7 @@ private static bool InvokeScriptArgumentCompleter( foreach (var customResult in customResults) { var resultAsCompletion = customResult.BaseObject as CompletionResult; - if (resultAsCompletion != null) + if (resultAsCompletion is not null) { result.Add(resultAsCompletion); continue; @@ -2499,12 +2499,12 @@ private static void NativeCompletionCimCommands( CommandAst commandAst, CompletionContext context) { - if (boundArguments != null) + if (boundArguments is not null) { AstParameterArgumentPair astParameterArgumentPair; if ((boundArguments.TryGetValue("ComputerName", out astParameterArgumentPair) || boundArguments.TryGetValue("CimSession", out astParameterArgumentPair)) - && astParameterArgumentPair != null) + && astParameterArgumentPair is not null) { switch (astParameterArgumentPair.ParameterArgumentType) { @@ -2536,20 +2536,20 @@ private static void NativeCompletionCimCommands( bool gotInstance = false; IEnumerable cimClassTypeNames = null; string pseudoboundClassName = NativeCommandArgumentCompletion_ExtractSecondaryArgument(boundArguments, "ClassName").FirstOrDefault(); - if (pseudoboundClassName != null) + if (pseudoboundClassName is not null) { gotInstance = false; var tmp = new List(); tmp.Add(new PSTypeName(typeof(CimInstance).FullName + "#" + (pseudoboundCimNamespace ?? "root/cimv2") + "/" + pseudoboundClassName)); cimClassTypeNames = tmp; } - else if (boundArguments != null && boundArguments.ContainsKey("InputObject")) + else if (boundArguments is not null && boundArguments.ContainsKey("InputObject")) { gotInstance = true; cimClassTypeNames = NativeCommandArgumentCompletion_InferTypesOfArgument(boundArguments, commandAst, context, "InputObject"); } - if (cimClassTypeNames != null) + if (cimClassTypeNames is not null) { foreach (PSTypeName typeName in cimClassTypeNames) { @@ -2590,7 +2590,7 @@ private static IEnumerable NativeCompletionCimAssociationResultClassName using (var cimSession = CimSession.Create(null)) { CimClass cimClass = cimSession.GetClass(cimNamespaceOfSource ?? "root/cimv2", cimClassNameOfSource); - while (cimClass != null) + while (cimClass is not null) { string query = string.Format( CultureInfo.InvariantCulture, @@ -2833,7 +2833,7 @@ private static void NativeCompletionGetCommand(CompletionContext context, string // Available commands var commandResults = CompleteCommand(context, moduleName); - if (commandResults != null) + if (commandResults is not null) result.AddRange(commandResults); // Consider files only if the -Module parameter is not present @@ -2855,7 +2855,7 @@ private static void NativeCompletionGetCommand(CompletionContext context, string var modules = new HashSet(StringComparer.OrdinalIgnoreCase); var moduleResults = CompleteModuleName(context, loadedModulesOnly: true); - if (moduleResults != null) + if (moduleResults is not null) { foreach (CompletionResult moduleResult in moduleResults) { @@ -2868,7 +2868,7 @@ private static void NativeCompletionGetCommand(CompletionContext context, string } moduleResults = CompleteModuleName(context, loadedModulesOnly: false); - if (moduleResults != null) + if (moduleResults is not null) { foreach (CompletionResult moduleResult in moduleResults) { @@ -2893,7 +2893,7 @@ private static void NativeCompletionGetHelpCommand(CompletionContext context, st // Available commands const CommandTypes commandTypes = CommandTypes.Cmdlet | CommandTypes.Function | CommandTypes.Alias | CommandTypes.ExternalScript | CommandTypes.Configuration; var commandResults = CompleteCommand(context, /* moduleName: */ null, commandTypes); - if (commandResults != null) + if (commandResults is not null) result.AddRange(commandResults); // ps1 files and directories @@ -2906,7 +2906,7 @@ private static void NativeCompletionGetHelpCommand(CompletionContext context, st { // Available topics var helpTopicResults = CompleteHelpTopics(context); - if (helpTopicResults != null) + if (helpTopicResults is not null) result.AddRange(helpTopicResults); } @@ -2936,7 +2936,7 @@ private static void NativeCompletionEventLogCommands(CompletionContext context, Exception exceptionThrown; var psObjects = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); - if (psObjects != null) + if (psObjects is not null) { foreach (dynamic eventLog in psObjects) { @@ -3169,7 +3169,7 @@ private static void NativeCompletionModuleCommands( } var moduleResults = CompleteModuleName(context, loadedModulesOnly, skipEditionCheck); - if (moduleResults != null && moduleResults.Count > 0) + if (moduleResults is not null && moduleResults.Count > 0) result.AddRange(moduleResults); result.Add(CompletionResult.Null); @@ -3339,11 +3339,11 @@ private static void NativeCompletionDriveCommands(CompletionContext context, str var powershell = powerShellExecutionHelper .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-PSDrive") .AddParameter("Name", wordToComplete); - if (psProvider != null) + if (psProvider is not null) powershell.AddParameter("PSProvider", psProvider); var psObjects = powerShellExecutionHelper.ExecuteCurrentPowerShell(out _); - if (psObjects != null) + if (psObjects is not null) { foreach (dynamic driveInfo in psObjects) { @@ -3394,7 +3394,7 @@ private static void NativeCompletionServiceCommands(CompletionContext context, s .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Utility\\Sort-Object") .AddParameter("Property", "DisplayName"); var psObjects = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); - if (psObjects != null) + if (psObjects is not null) { foreach (dynamic serviceInfo in psObjects) { @@ -3425,7 +3425,7 @@ private static void NativeCompletionServiceCommands(CompletionContext context, s powerShellExecutionHelper.AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-Service").AddParameter("Name", wordToComplete); var psObjects = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); - if (psObjects != null) + if (psObjects is not null) { foreach (dynamic serviceInfo in psObjects) { @@ -3531,7 +3531,7 @@ private static void NativeCompletionAliasCommands(CompletionContext context, str Exception exceptionThrown; var powershell = powerShellExecutionHelper.AddCommandWithPreferenceSetting("Microsoft.PowerShell.Utility\\Get-Alias").AddParameter("Name", commandName); var psObjects = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); - if (psObjects != null) + if (psObjects is not null) { foreach (dynamic aliasInfo in psObjects) { @@ -3560,7 +3560,7 @@ private static void NativeCompletionAliasCommands(CompletionContext context, str // Available commands const CommandTypes commandTypes = CommandTypes.Cmdlet | CommandTypes.Function | CommandTypes.ExternalScript | CommandTypes.Configuration; var commandResults = CompleteCommand(context, /* moduleName: */ null, commandTypes); - if (commandResults != null && commandResults.Count > 0) + if (commandResults is not null && commandResults.Count > 0) result.AddRange(commandResults); // The parameter Definition takes a file @@ -3640,7 +3640,7 @@ private static void NativeCompletionSetLocationCommand(CompletionContext context try { var fileNameResults = CompleteFilename(context, containerOnly: true, extension: null); - if (fileNameResults != null) + if (fileNameResults is not null) result.AddRange(fileNameResults); } finally @@ -3673,7 +3673,7 @@ private static void NativeCompletionNewItemCommand(CompletionContext context, st ProviderInfo provider; executionContext.LocationGlobber.GetProviderPath(providedPath, out provider); - var isFileSystem = provider != null && + var isFileSystem = provider is not null && provider.Name.Equals(FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase); // AutoComplete only if filesystem provider. @@ -3742,7 +3742,7 @@ private static void NativeCompletionCopyMoveItemCommand(CompletionContext contex try { var fileNameResults = CompleteFilename(context); - if (fileNameResults != null) + if (fileNameResults is not null) result.AddRange(fileNameResults); } finally @@ -3777,7 +3777,7 @@ private static void NativeCompletionPathArgument(CompletionContext context, stri try { var fileNameResults = CompleteFilename(context); - if (fileNameResults != null) + if (fileNameResults is not null) result.AddRange(fileNameResults); } finally @@ -3893,7 +3893,7 @@ private static void NativeCompletionTypeName(CompletionContext context, List private static ArgumentLocation FindTargetArgumentLocation(Collection parsedArguments, ExpressionAst expAst) { - Diagnostics.Assert(expAst != null, "Caller needs to make sure expAst is not null"); + Diagnostics.Assert(expAst is not null, "Caller needs to make sure expAst is not null"); int position = 0; foreach (AstParameterArgumentPair pair in parsedArguments) { @@ -4168,7 +4168,7 @@ internal static IEnumerable CompleteFilename(CompletionContext wordToComplete = WildcardPattern.Escape(wordToComplete, Utils.Separators.StarOrQuestion); } - if (!defaultRelative && wordToComplete.Length >= 2 && wordToComplete[1] == ':' && char.IsLetter(wordToComplete[0]) && executionContext != null) + if (!defaultRelative && wordToComplete.Length >= 2 && wordToComplete[1] == ':' && char.IsLetter(wordToComplete[0]) && executionContext is not null) { // We don't actually need the drive, but the drive must be "mounted" in PowerShell before completion // can succeed. This call will mount the drive if it wasn't already. @@ -4183,7 +4183,7 @@ internal static IEnumerable CompleteFilename(CompletionContext Exception exceptionThrown; var psobjs = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); - if (psobjs != null) + if (psobjs is not null) { var isFileSystem = false; var wordContainsProviderId = ProviderSpecified(wordToComplete); @@ -4192,7 +4192,7 @@ internal static IEnumerable CompleteFilename(CompletionContext { dynamic firstObj = psobjs[0]; var provider = firstObj.Provider as ProviderInfo; - isFileSystem = provider != null && + isFileSystem = provider is not null && provider.Name.Equals(FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase); } @@ -4210,7 +4210,7 @@ internal static IEnumerable CompleteFilename(CompletionContext executionContext.LocationGlobber.GetProviderPath(wordToComplete, out provider); } - isFileSystem = provider != null && + isFileSystem = provider is not null && provider.Name.Equals(FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase); } @@ -4257,7 +4257,7 @@ internal static IEnumerable CompleteFilename(CompletionContext } } - if (leaf != null) + if (leaf is not null) { leaf = leaf + "*"; var parentPath = Path.GetDirectoryName(providerPath); @@ -4274,7 +4274,7 @@ internal static IEnumerable CompleteFilename(CompletionContext { } - if (entries != null) + if (entries is not null) { hiddenFilesAreHandled = true; @@ -4314,7 +4314,7 @@ internal static IEnumerable CompleteFilename(CompletionContext .AddParameter("Hidden", true); var hiddenItems = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); - if (hiddenItems != null && hiddenItems.Count > 0) + if (hiddenItems is not null && hiddenItems.Count > 0) { foreach (var hiddenItem in hiddenItems) { @@ -4337,7 +4337,7 @@ internal static IEnumerable CompleteFilename(CompletionContext // 2. a FileSystemInfo Object -- results of Get-ChildItem // 3. a string -- the path results return by the direct .NET API invocation var baseObjAsPathInfo = baseObj as PathInfo; - if (baseObjAsPathInfo != null) + if (baseObjAsPathInfo is not null) { path = baseObjAsPathInfo.Path; providerPath = baseObjAsPathInfo.ProviderPath; @@ -4352,7 +4352,7 @@ internal static IEnumerable CompleteFilename(CompletionContext else { var baseObjAsString = baseObj as string; - if (baseObjAsString != null) + if (baseObjAsString is not null) { // The target provider is the FileSystem providerPath = baseObjAsString; @@ -4452,7 +4452,7 @@ internal static IEnumerable CompleteFilename(CompletionContext .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-Item") .AddParameter("LiteralPath", path); var items = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); - if (items != null && items.Count == 1) + if (items is not null && items.Count == 1) { dynamic item = items[0]; var isContainer = LanguagePrimitives.ConvertTo(item.PSIsContainer); @@ -4465,7 +4465,7 @@ internal static IEnumerable CompleteFilename(CompletionContext .AddParameter("LiteralPath", item.PSPath); var tooltips = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); string tooltip = null, listItemText = item.PSChildName; - if (tooltips != null && tooltips.Count == 1) + if (tooltips is not null && tooltips.Count == 1) { tooltip = PSObject.Base(tooltips[0]) as string; } @@ -4597,16 +4597,16 @@ internal static List CompleteVariable(CompletionContext contex var lastAst = context.RelatedAsts?.Last(); var variableAst = lastAst as VariableExpressionAst; - var prefix = variableAst != null && variableAst.Splatted ? "@" : "$"; + var prefix = variableAst is not null && variableAst.Splatted ? "@" : "$"; // Look for variables in the input (e.g. parameters, etc.) before checking session state - these // variables might not exist in session state yet. var wildcardPattern = WildcardPattern.Get(wordToComplete + "*", WildcardOptions.IgnoreCase); - if (lastAst != null) + if (lastAst is not null) { Ast parent = lastAst.Parent; var findVariablesVisitor = new FindVariablesVisitor { CompletionVariableAst = lastAst }; - while (parent != null) + while (parent is not null) { if (parent is IParameterMetadataProvider) { @@ -4623,7 +4623,7 @@ internal static List CompleteVariable(CompletionContext contex string userPath = null; VariableExpressionAst variableDefinitionAst = varAst.Item2 as VariableExpressionAst; - if (variableDefinitionAst != null) + if (variableDefinitionAst is not null) { userPath = varAst.Item1; astTarget = varAst.Item2.Parent; @@ -4631,7 +4631,7 @@ internal static List CompleteVariable(CompletionContext contex else { CommandAst commandParameterAst = varAst.Item2 as CommandAst; - if (commandParameterAst != null) + if (commandParameterAst is not null) { userPath = varAst.Item1; astTarget = varAst.Item2; @@ -4651,13 +4651,13 @@ internal static List CompleteVariable(CompletionContext contex var tooltip = userPath; var ast = astTarget; - while (ast != null) + while (ast is not null) { var parameterAst = ast as ParameterAst; - if (parameterAst != null) + if (parameterAst is not null) { var typeConstraint = parameterAst.Attributes.OfType().FirstOrDefault(); - if (typeConstraint != null) + if (typeConstraint is not null) { tooltip = StringUtil.Format("{0}${1}", typeConstraint.Extent.Text, userPath); } @@ -4666,7 +4666,7 @@ internal static List CompleteVariable(CompletionContext contex } var assignmentAst = ast.Parent as AssignmentStatementAst; - if (assignmentAst != null) + if (assignmentAst is not null) { if (assignmentAst.Left == ast) { @@ -4677,10 +4677,10 @@ internal static List CompleteVariable(CompletionContext contex } var commandAst = ast as CommandAst; - if (commandAst != null) + if (commandAst is not null) { PSTypeName discoveredType = AstTypeInference.InferTypeOf(ast, context.TypeInferenceContext, TypeInferenceRuntimePermissions.AllowSafeEval).FirstOrDefault(); - if (discoveredType != null) + if (discoveredType is not null) { tooltip = StringUtil.Format("[{0}]${1}", discoveredType.Name, userPath); } @@ -4723,7 +4723,7 @@ internal static List CompleteVariable(CompletionContext contex Exception exceptionThrown; var psobjs = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); - if (psobjs != null) + if (psobjs is not null) { foreach (dynamic psobj in psobjs) { @@ -4732,10 +4732,10 @@ internal static List CompleteVariable(CompletionContext contex { var tooltip = name; var variable = PSObject.Base(psobj) as PSVariable; - if (variable != null) + if (variable is not null) { var value = variable.Value; - if (value != null) + if (value is not null) { tooltip = StringUtil.Format("[{0}]${1}", ToStringCodeMethods.Type(value.GetType(), @@ -4758,7 +4758,7 @@ internal static List CompleteVariable(CompletionContext contex .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Utility\\Sort-Object").AddParameter("Property", "Key"); psobjs = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); - if (psobjs != null) + if (psobjs is not null) { foreach (dynamic psobj in psobjs) { @@ -4797,15 +4797,15 @@ internal static List CompleteVariable(CompletionContext contex .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-PSDrive").AddParameter("Name", pattern) .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Utility\\Sort-Object").AddParameter("Property", "Name"); psobjs = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); - if (psobjs != null) + if (psobjs is not null) { foreach (var psobj in psobjs) { var driveInfo = PSObject.Base(psobj) as PSDriveInfo; - if (driveInfo != null) + if (driveInfo is not null) { var name = driveInfo.Name; - if (name != null && !string.IsNullOrWhiteSpace(name) && name.Length > 1) + if (name is not null && !string.IsNullOrWhiteSpace(name) && name.Length > 1) { var completedName = (name.IndexOfAny(s_charactersRequiringQuotes) == -1) ? prefix + name + ":" @@ -4871,7 +4871,7 @@ public override AstVisitAction VisitCommand(CommandAst commandAst) string[] desiredParameters = new string[] { "PV", "PipelineVariable", "OV", "OutVariable" }; StaticBindingResult bindingResult = StaticParameterBinder.BindCommand(commandAst, false, desiredParameters); - if (bindingResult != null) + if (bindingResult is not null) { ParameterBindingResult parameterBindingResult; @@ -4941,10 +4941,10 @@ internal static List CompleteComment(CompletionContext context context.Helper.AddCommandWithPreferenceSetting("Get-History", typeof(GetHistoryCommand)).AddParameter("Id", entryId); psobjs = context.Helper.ExecuteCurrentPowerShell(out _); - if (psobjs != null && psobjs.Count == 1) + if (psobjs is not null && psobjs.Count == 1) { var historyInfo = PSObject.Base(psobjs[0]) as HistoryInfo; - if (historyInfo != null) + if (historyInfo is not null) { var commandLine = historyInfo.CommandLine; if (!string.IsNullOrEmpty(commandLine)) @@ -4968,7 +4968,7 @@ internal static List CompleteComment(CompletionContext context psobjs = context.Helper.ExecuteCurrentPowerShell(out _); var pattern = WildcardPattern.Get(wordToComplete, WildcardOptions.IgnoreCase); - if (psobjs != null) + if (psobjs is not null) { for (int index = psobjs.Count - 1; index >= 0; index--) { @@ -5023,7 +5023,7 @@ internal static List CompleteMember(CompletionContext context, var lastAstAsMemberExpr = lastAst as MemberExpressionAst; Ast memberNameCandidateAst = null; ExpressionAst targetExpr = null; - if (lastAstAsMemberExpr != null) + if (lastAstAsMemberExpr is not null) { // If the cursor is not inside the member name in the member expression, assume // that the user had incomplete input, but the parser got lucky and succeeded parsing anyway. @@ -5042,7 +5042,7 @@ internal static List CompleteMember(CompletionContext context, var memberNameAst = memberNameCandidateAst as StringConstantExpressionAst; var memberName = "*"; - if (memberNameAst != null) + if (memberNameAst is not null) { // Make sure to correctly handle: echo $foo. if (!memberNameAst.Value.Equals(".", StringComparison.OrdinalIgnoreCase) && !memberNameAst.Value.Equals("::", StringComparison.OrdinalIgnoreCase)) @@ -5057,7 +5057,7 @@ internal static List CompleteMember(CompletionContext context, } var commandAst = lastAst.Parent as CommandAst; - if (commandAst != null) + if (commandAst is not null) { int i; for (i = commandAst.CommandElements.Count - 1; i >= 0; --i) @@ -5097,7 +5097,7 @@ internal static List CompleteMember(CompletionContext context, else if (lastAst.Parent is BinaryExpressionAst && context.TokenAtCursor.Kind.Equals(TokenKind.Multiply)) { var memberExprAst = ((BinaryExpressionAst)lastAst.Parent).Left as MemberExpressionAst; - if (memberExprAst != null) + if (memberExprAst is not null) { targetExpr = memberExprAst.Expression; if (memberExprAst.Member is StringConstantExpressionAst) @@ -5128,7 +5128,7 @@ internal static List CompleteMember(CompletionContext context, if (@static) { var typeExpr = targetExpr as TypeExpressionAst; - if (typeExpr != null) + if (typeExpr is not null) { inferredTypes = new[] { new PSTypeName(typeExpr.TypeName) }; } @@ -5138,7 +5138,7 @@ internal static List CompleteMember(CompletionContext context, inferredTypes = AstTypeInference.InferTypeOf(targetExpr, context.TypeInferenceContext, TypeInferenceRuntimePermissions.AllowSafeEval).ToArray(); } - if (inferredTypes != null && inferredTypes.Length > 0) + if (inferredTypes is not null && inferredTypes.Length > 0) { // Use inferred types if we have any CompleteMemberByInferredType(context.TypeInferenceContext, inferredTypes, results, memberName, filter: null, isStatic: @static); @@ -5153,7 +5153,7 @@ internal static List CompleteMember(CompletionContext context, // We complete against extension methods 'Where' and 'ForEach' for the following DSC variables // $SelectedNodes, $AllNodes, $ConfigurationData.AllNodes - if (variableAst != null) + if (variableAst is not null) { // Handle $SelectedNodes and $AllNodes var variablePath = variableAst.VariablePath; @@ -5162,11 +5162,11 @@ internal static List CompleteMember(CompletionContext context, shouldAddExtensionMethods = true; } } - else if (memberExprAst != null) + else if (memberExprAst is not null) { // Handle $ConfigurationData.AllNodes var member = memberExprAst.Member as StringConstantExpressionAst; - if (IsConfigurationDataVariable(memberExprAst.Expression) && member != null && + if (IsConfigurationDataVariable(memberExprAst.Expression) && member is not null && string.Equals("AllNodes", member.Value, StringComparison.OrdinalIgnoreCase) && IsInDscContext(memberExprAst)) { @@ -5224,7 +5224,7 @@ where pattern.IsMatch(member.Item1) private static bool IsConfigurationDataVariable(ExpressionAst targetExpr) { var variableExpr = targetExpr as VariableExpressionAst; - if (variableExpr != null) + if (variableExpr is not null) { var varPath = variableExpr.VariablePath; if (varPath.IsVariable && @@ -5242,7 +5242,7 @@ private static bool IsConfigurationDataVariable(ExpressionAst targetExpr) /// private static bool IsInDscContext(ExpressionAst expression) { - return Ast.GetAncestorAst(expression) != null; + return Ast.GetAncestorAst(expression) is not null; } internal static void CompleteMemberByInferredType(TypeInferenceContext context, IEnumerable inferredTypes, List results, string memberName, Func filter, bool isStatic) @@ -5265,7 +5265,7 @@ internal static void CompleteMemberByInferredType(TypeInferenceContext context, } // Check if we need to complete against the extension methods 'Where' and 'ForEach' - if (!extensionMethodsAdded && psTypeName.Type != null && IsStaticTypeEnumerable(psTypeName.Type)) + if (!extensionMethodsAdded && psTypeName.Type is not null && IsStaticTypeEnumerable(psTypeName.Type)) { // Complete extension methods 'Where' and 'ForEach' for Enumerable types extensionMethodsAdded = true; @@ -5294,23 +5294,23 @@ private static void AddInferredMember(object member, WildcardPattern memberNameP bool isMethod = false; Func getToolTip = null; var propertyInfo = member as PropertyInfo; - if (propertyInfo != null) + if (propertyInfo is not null) { memberName = propertyInfo.Name; getToolTip = () => ToStringCodeMethods.Type(propertyInfo.PropertyType) + " " + memberName - + " { " + (propertyInfo.GetGetMethod() != null ? "get; " : string.Empty) - + (propertyInfo.GetSetMethod() != null ? "set; " : string.Empty) + "}"; + + " { " + (propertyInfo.GetGetMethod() is not null ? "get; " : string.Empty) + + (propertyInfo.GetSetMethod() is not null ? "set; " : string.Empty) + "}"; } var fieldInfo = member as FieldInfo; - if (fieldInfo != null) + if (fieldInfo is not null) { memberName = fieldInfo.Name; getToolTip = () => ToStringCodeMethods.Type(fieldInfo.FieldType) + " " + memberName; } var methodCacheEntry = member as DotNetAdapter.MethodCacheEntry; - if (methodCacheEntry != null) + if (methodCacheEntry is not null) { memberName = methodCacheEntry[0].method.Name; isMethod = true; @@ -5318,7 +5318,7 @@ private static void AddInferredMember(object member, WildcardPattern memberNameP } var psMemberInfo = member as PSMemberInfo; - if (psMemberInfo != null) + if (psMemberInfo is not null) { memberName = psMemberInfo.Name; isMethod = member is PSMethodInfo; @@ -5326,7 +5326,7 @@ private static void AddInferredMember(object member, WildcardPattern memberNameP } var cimProperty = member as CimPropertyDeclaration; - if (cimProperty != null) + if (cimProperty is not null) { memberName = cimProperty.Name; isMethod = false; @@ -5334,7 +5334,7 @@ private static void AddInferredMember(object member, WildcardPattern memberNameP } var memberAst = member as MemberAst; - if (memberAst != null) + if (memberAst is not null) { memberName = memberAst is CompilerGeneratedMemberFunctionAst ? "new" : memberAst.Name; isMethod = memberAst is FunctionMemberAst || memberAst is CompilerGeneratedMemberFunctionAst; @@ -5378,13 +5378,13 @@ private static string GetCimPropertyToString(CimPropertyDeclaration cimProperty) private static bool IsWriteablePropertyMember(object member) { var propertyInfo = member as PropertyInfo; - if (propertyInfo != null) + if (propertyInfo is not null) { return propertyInfo.CanWrite; } var psPropertyInfo = member as PSPropertyInfo; - if (psPropertyInfo != null) + if (psPropertyInfo is not null) { return psPropertyInfo.IsSettable; } @@ -5404,19 +5404,19 @@ internal static bool IsPropertyMember(object member) private static bool IsMemberHidden(object member) { var psMemberInfo = member as PSMemberInfo; - if (psMemberInfo != null) + if (psMemberInfo is not null) return psMemberInfo.IsHidden; var memberInfo = member as MemberInfo; - if (memberInfo != null) + if (memberInfo is not null) return memberInfo.GetCustomAttributes(typeof(HiddenAttribute), false).Length > 0; var propertyMemberAst = member as PropertyMemberAst; - if (propertyMemberAst != null) + if (propertyMemberAst is not null) return propertyMemberAst.IsHidden; var functionMemberAst = member as FunctionMemberAst; - if (functionMemberAst != null) + if (functionMemberAst is not null) return functionMemberAst.IsHidden; return false; @@ -5425,10 +5425,10 @@ private static bool IsMemberHidden(object member) private static bool IsConstructor(object member) { var psMethod = member as PSMethod; - if (psMethod != null) + if (psMethod is not null) { var methodCacheEntry = psMethod.adapterData as DotNetAdapter.MethodCacheEntry; - if (methodCacheEntry != null) + if (methodCacheEntry is not null) { return methodCacheEntry.methodInformationStructures[0].method.IsConstructor; } @@ -5742,7 +5742,7 @@ private static TypeCompletionMapping[][] InitializeTypeCache() item => { var typeCompletion = item as TypeCompletion; - return typeCompletion != null && typeCompletion.Type == acceleratorType; + return typeCompletion is not null && typeCompletion.Type == acceleratorType; }); // If it's already included, skip it. @@ -5895,7 +5895,7 @@ private static void HandleType(Dictionary entryCa // Nested generic types aren't useful for completion. if (isNested) { return; } - typeCompletionBase = actualType != null + typeCompletionBase = actualType is not null ? (TypeCompletionBase)new GenericTypeCompletion { Type = actualType } : new GenericTypeCompletionInStringFormat { FullTypeName = fullTypeName }; @@ -5906,7 +5906,7 @@ private static void HandleType(Dictionary entryCa } else { - typeCompletionBase = actualType != null + typeCompletionBase = actualType is not null ? (TypeCompletionBase)new TypeCompletion { Type = actualType } : new TypeCompletionInStringFormat { FullTypeName = fullTypeName }; @@ -6013,7 +6013,7 @@ internal static List CompleteType(CompletionContext context, s } // this is a temporary fix. Only the type defined in the same script get complete. Need to use using Module when that is available. - if (context.RelatedAsts != null && context.RelatedAsts.Count > 0) + if (context.RelatedAsts is not null && context.RelatedAsts.Count > 0) { var scriptBlockAst = (ScriptBlockAst)context.RelatedAsts[0]; var typeAsts = scriptBlockAst.FindAll(ast => ast is TypeDefinitionAst, false).Cast(); @@ -6043,14 +6043,14 @@ private static string GetNamespaceToRemove(CompletionContext context, TypeComple } var typeCompletion = completion as TypeCompletion; - string typeNameSpace = typeCompletion != null + string typeNameSpace = typeCompletion is not null ? typeCompletion.Type.Namespace : ((TypeCompletionInStringFormat)completion).Namespace; var scriptBlockAst = (ScriptBlockAst)context.RelatedAsts[0]; var matchingNsStates = scriptBlockAst.UsingStatements.Where(s => s.UsingStatementKind == UsingStatementKind.Namespace - && typeNameSpace != null + && typeNameSpace is not null && typeNameSpace.StartsWith(s.Name.Value, StringComparison.OrdinalIgnoreCase)); string ns = string.Empty; @@ -6109,7 +6109,7 @@ internal static List CompleteHelpTopics(CompletionContext cont { } - if (files != null) + if (files is not null) { foreach (string file in files) { @@ -6179,7 +6179,7 @@ internal static List CompleteStatementFlags(TokenKind kind, st } } - if (fullMatch != null) + if (fullMatch is not null) { result.Add(fullMatch); } @@ -6224,7 +6224,7 @@ internal static List CompleteHashtableKeyForDynamicKeyword( DynamicKeywordStatementAst ast, HashtableAst hashtableAst) { - Diagnostics.Assert(ast.Keyword != null, "DynamicKeywordStatementAst.Keyword can never be null"); + Diagnostics.Assert(ast.Keyword is not null, "DynamicKeywordStatementAst.Keyword can never be null"); List results = null; var dynamicKeywordProperties = ast.Keyword.Properties; var memberPattern = completionContext.WordToComplete + "*"; @@ -6238,7 +6238,7 @@ internal static List CompleteHashtableKeyForDynamicKeyword( { var propName = keyValueTuple.Item1 as StringConstantExpressionAst; // Exclude the property name at cursor - if (propName != null && propName.Extent.EndOffset != cursorOffset) + if (propName is not null && propName.Extent.EndOffset != cursorOffset) { propertiesName.Add(propName.Value); } @@ -6248,7 +6248,7 @@ internal static List CompleteHashtableKeyForDynamicKeyword( { // Excludes existing properties in the hashtable statement var tempProperties = dynamicKeywordProperties.Where(p => !propertiesName.Contains(p.Key, StringComparer.OrdinalIgnoreCase)); - if (tempProperties != null && tempProperties.Any()) + if (tempProperties is not null && tempProperties.Any()) { results = new List(); // Filter by name @@ -6288,7 +6288,7 @@ internal static List CompleteHashtableKeyForDynamicKeyword( internal static List CompleteHashtableKey(CompletionContext completionContext, HashtableAst hashtableAst) { var typeAst = hashtableAst.Parent as ConvertExpressionAst; - if (typeAst != null) + if (typeAst is not null) { var result = new List(); CompleteMemberByInferredType( @@ -6331,7 +6331,7 @@ internal static List CompleteHashtableKey(CompletionContext co // Handle completion for hashtable within DynamicKeyword statement var dynamicKeywordStatementAst = ast as DynamicKeywordStatementAst; - if (dynamicKeywordStatementAst != null) + if (dynamicKeywordStatementAst is not null) { return CompleteHashtableKeyForDynamicKeyword(completionContext, dynamicKeywordStatementAst, hashtableAst); } @@ -6347,7 +6347,7 @@ internal static List CompleteHashtableKey(CompletionContext co } var commandAst = ast as CommandAst; - if (commandAst != null) + if (commandAst is not null) { var binding = new PseudoParameterBinder().DoPseudoParameterBinding(commandAst, null, null, bindingType: PseudoParameterBinder.BindingType.ArgumentCompletion); if (binding is null) @@ -6359,7 +6359,7 @@ internal static List CompleteHashtableKey(CompletionContext co foreach (var boundArg in binding.BoundArguments) { var astPair = boundArg.Value as AstPair; - if (astPair != null) + if (astPair is not null) { if (astPair.Argument == hashtableAst) { @@ -6371,7 +6371,7 @@ internal static List CompleteHashtableKey(CompletionContext co } var astArrayPair = boundArg.Value as AstArrayPair; - if (astArrayPair != null) + if (astArrayPair is not null) { if (astArrayPair.Argument.Contains(hashtableAst)) { @@ -6383,7 +6383,7 @@ internal static List CompleteHashtableKey(CompletionContext co } } - if (parameterName != null) + if (parameterName is not null) { if (parameterName.Equals("GroupBy", StringComparison.OrdinalIgnoreCase)) { @@ -6464,7 +6464,7 @@ internal static bool IsPathSafelyExpandable(ExpandableStringExpressionAst expand if (variableAst is null) { return false; } string strValue = CombineVariableWithPartialPath(variableAst, null, executionContext); - if (strValue != null) + if (strValue is not null) { varValues.Add(strValue); } @@ -6501,7 +6501,7 @@ internal static string CombineVariableWithPartialPath(VariableExpressionAst vari } } - if (strValue != null) + if (strValue is not null) { return strValue + extraText; } @@ -6565,7 +6565,7 @@ internal static void CompleteMemberHelper( List results) { object value; - if (SafeExprEvaluator.TrySafeEval(targetExpr, context.ExecutionContext, out value) && value != null) + if (SafeExprEvaluator.TrySafeEval(targetExpr, context.ExecutionContext, out value) && value is not null) { if (targetExpr is ArrayExpressionAst && !(value is object[])) { @@ -6648,7 +6648,7 @@ internal static void CompleteMemberHelper( } var dictionary = PSObject.Base(value) as IDictionary; - if (dictionary != null) + if (dictionary is not null) { var pattern = WildcardPattern.Get(memberName, WildcardOptions.IgnoreCase); foreach (DictionaryEntry entry in dictionary) @@ -6790,12 +6790,12 @@ private static bool TurnOnLiteralPathOption(CompletionContext completionContext) /// internal static bool IsAmpersandNeeded(CompletionContext context, bool defaultChoice) { - if (context.RelatedAsts != null && !string.IsNullOrEmpty(context.WordToComplete)) + if (context.RelatedAsts is not null && !string.IsNullOrEmpty(context.WordToComplete)) { var lastAst = context.RelatedAsts.Last(); var parent = lastAst.Parent as CommandAst; - if (parent != null && parent.CommandElements.Count == 1 && + if (parent is not null && parent.CommandElements.Count == 1 && ((!defaultChoice && parent.InvocationOperator == TokenKind.Unknown) || (defaultChoice && parent.InvocationOperator != TokenKind.Unknown))) { @@ -6824,18 +6824,18 @@ public int Compare(PSObject x, PSObject y) string xPath = null, yPath = null; - if (xPathInfo != null) + if (xPathInfo is not null) xPath = xPathInfo.ProviderPath; - else if (xFileInfo != null) + else if (xFileInfo is not null) xPath = xFileInfo.FullName; - else if (xPathStr != null) + else if (xPathStr is not null) xPath = xPathStr; - if (yPathInfo != null) + if (yPathInfo is not null) yPath = yPathInfo.ProviderPath; - else if (yFileInfo != null) + else if (yFileInfo is not null) yPath = yFileInfo.FullName; - else if (yPathStr != null) + else if (yPathStr is not null) yPath = yPathStr; if (string.IsNullOrEmpty(xPath) || string.IsNullOrEmpty(yPath)) @@ -6856,10 +6856,10 @@ public int Compare(PSObject x, PSObject y) object yObj = PSObject.Base(y); var xCommandInfo = xObj as CommandInfo; - xName = xCommandInfo != null ? xCommandInfo.Name : xObj as string; + xName = xCommandInfo is not null ? xCommandInfo.Name : xObj as string; var yCommandInfo = yObj as CommandInfo; - yName = yCommandInfo != null ? yCommandInfo.Name : yObj as string; + yName = yCommandInfo is not null ? yCommandInfo.Name : yObj as string; if (xName is null || yName is null) Diagnostics.Assert(false, "Base object of Command PSObject should be either CommandInfo or string"); @@ -7005,17 +7005,17 @@ public object VisitConfigurationDefinition(ConfigurationDefinitionAst configurat public object VisitStatementBlock(StatementBlockAst statementBlockAst) { - if (statementBlockAst.Traps != null) return false; + if (statementBlockAst.Traps is not null) return false; // REVIEW: we could relax this to allow multiple statements if (statementBlockAst.Statements.Count > 1) return false; var pipeline = statementBlockAst.Statements.FirstOrDefault(); - return pipeline != null && (bool)pipeline.Accept(this); + return pipeline is not null && (bool)pipeline.Accept(this); } public object VisitPipeline(PipelineAst pipelineAst) { var expr = pipelineAst.GetPureExpression(); - return expr != null && (bool)expr.Accept(this); + return expr is not null && (bool)expr.Accept(this); } public object VisitTernaryExpression(TernaryExpressionAst ternaryExpressionAst) @@ -7165,7 +7165,7 @@ IEnumerable IArgumentCompleter.CompleteArgument( return null; } - if (pair is AstPair astPair && astPair.Argument != null) + if (pair is AstPair astPair && astPair.Argument is not null) { prevType = AstTypeInference.InferTypeOf(astPair.Argument, typeInferenceContext, TypeInferenceRuntimePermissions.AllowSafeEval); } diff --git a/src/System.Management.Automation/engine/CommandCompletion/ExtensibleCompletion.cs b/src/System.Management.Automation/engine/CommandCompletion/ExtensibleCompletion.cs index 350322e38c9..20b666fb554 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/ExtensibleCompletion.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/ExtensibleCompletion.cs @@ -116,7 +116,7 @@ public class RegisterArgumentCompleterCommand : PSCmdlet protected override void EndProcessing() { Dictionary completerDictionary; - if (ParameterName != null) + if (ParameterName is not null) { completerDictionary = Context.CustomArgumentCompleters ?? (Context.CustomArgumentCompleters = new Dictionary(StringComparer.OrdinalIgnoreCase)); diff --git a/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs b/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs index 1287dd586c8..46923aa76cd 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs @@ -191,7 +191,7 @@ internal AstPair(CommandParameterAst parameterAst) internal AstPair(CommandParameterAst parameterAst, ExpressionAst argumentAst) { - if (parameterAst != null && parameterAst.Argument != null) + if (parameterAst is not null && parameterAst.Argument is not null) throw PSTraceSource.NewArgumentException(nameof(parameterAst)); if (parameterAst is null && argumentAst is null) @@ -199,11 +199,11 @@ internal AstPair(CommandParameterAst parameterAst, ExpressionAst argumentAst) Parameter = parameterAst; ParameterArgumentType = AstParameterArgumentType.AstPair; - ParameterSpecified = parameterAst != null; - ArgumentSpecified = argumentAst != null; - ParameterName = parameterAst != null ? parameterAst.ParameterName : null; - ParameterText = parameterAst != null ? parameterAst.ParameterName : null; - ArgumentType = argumentAst != null ? argumentAst.StaticType : null; + ParameterSpecified = parameterAst is not null; + ArgumentSpecified = argumentAst is not null; + ParameterName = parameterAst is not null ? parameterAst.ParameterName : null; + ParameterText = parameterAst is not null ? parameterAst.ParameterName : null; + ArgumentType = argumentAst is not null ? argumentAst.StaticType : null; ParameterContainsArgument = false; Argument = argumentAst; @@ -211,7 +211,7 @@ internal AstPair(CommandParameterAst parameterAst, ExpressionAst argumentAst) internal AstPair(CommandParameterAst parameterAst, CommandElementAst argumentAst) { - if (parameterAst != null && parameterAst.Argument != null) + if (parameterAst is not null && parameterAst.Argument is not null) throw PSTraceSource.NewArgumentException(nameof(parameterAst)); if (parameterAst is null || argumentAst is null) @@ -293,7 +293,7 @@ public static StaticBindingResult BindCommand(CommandAst commandAst, bool resolv public static StaticBindingResult BindCommand(CommandAst commandAst, bool resolve, string[] desiredParameters) { // If they specified any desired parameters, first quickly check if they are found - if ((desiredParameters != null) && (desiredParameters.Length > 0)) + if ((desiredParameters is not null) && (desiredParameters.Length > 0)) { bool possiblyHadDesiredParameter = false; foreach (CommandParameterAst commandParameter in commandAst.CommandElements.OfType()) @@ -419,7 +419,7 @@ private void CreateBindingResultForSuccessfulBind(CommandAst commandAst, PseudoB } // Add error for duplicate parameters - if (bindingInfo.DuplicateParameters != null) + if (bindingInfo.DuplicateParameters is not null) { foreach (AstParameterArgumentPair duplicateParameter in bindingInfo.DuplicateParameters) { @@ -428,7 +428,7 @@ private void CreateBindingResultForSuccessfulBind(CommandAst commandAst, PseudoB } // Add error for parameters not found - if (bindingInfo.ParametersNotFound != null) + if (bindingInfo.ParametersNotFound is not null) { foreach (CommandParameterAst parameterNotFound in bindingInfo.ParametersNotFound) { @@ -447,7 +447,7 @@ private void CreateBindingResultForSuccessfulBind(CommandAst commandAst, PseudoB } // Add error for ambiguous parameters - if (bindingInfo.AmbiguousParameters != null) + if (bindingInfo.AmbiguousParameters is not null) { foreach (CommandParameterAst ambiguousParameter in bindingInfo.AmbiguousParameters) { @@ -457,7 +457,7 @@ private void CreateBindingResultForSuccessfulBind(CommandAst commandAst, PseudoB } // Add error for unbound positional parameters - if (bindingInfo.UnboundArguments != null) + if (bindingInfo.UnboundArguments is not null) { foreach (AstParameterArgumentPair unboundArgument in bindingInfo.UnboundArguments) { @@ -478,7 +478,7 @@ private void CreateBindingResultForSuccessfulBind(CommandAst commandAst, PseudoB } // Process the bound parameters - if (bindingInfo.BoundParameters != null) + if (bindingInfo.BoundParameters is not null) { foreach (KeyValuePair item in bindingInfo.BoundParameters) { @@ -488,7 +488,7 @@ private void CreateBindingResultForSuccessfulBind(CommandAst commandAst, PseudoB // This is a single argument AstPair argumentAstPair = bindingInfo.BoundArguments[item.Key] as AstPair; - if (argumentAstPair != null) + if (argumentAstPair is not null) { value = argumentAstPair.Argument; } @@ -496,13 +496,13 @@ private void CreateBindingResultForSuccessfulBind(CommandAst commandAst, PseudoB // This is a parameter that took an argument, as well as ValueFromRemainingArguments. // Merge the arguments into a single fake argument. AstArrayPair argumentAstArrayPair = bindingInfo.BoundArguments[item.Key] as AstArrayPair; - if (argumentAstArrayPair != null) + if (argumentAstArrayPair is not null) { List arguments = new List(); foreach (ExpressionAst expression in argumentAstArrayPair.Argument) { ArrayLiteralAst expressionArray = expression as ArrayLiteralAst; - if (expressionArray != null) + if (expressionArray is not null) { foreach (ExpressionAst newExpression in expressionArray.Elements) { @@ -524,7 +524,7 @@ private void CreateBindingResultForSuccessfulBind(CommandAst commandAst, PseudoB // Special handling of switch parameters if (parameter.Type == typeof(SwitchParameter)) { - if ((value != null) && + if ((value is not null) && (string.Equals("$false", value.Extent.Text, StringComparison.OrdinalIgnoreCase))) { continue; @@ -534,7 +534,7 @@ private void CreateBindingResultForSuccessfulBind(CommandAst commandAst, PseudoB } // We got a parameter and a value - if ((value != null) || (constantValue != null)) + if ((value is not null) || (constantValue is not null)) { BoundParameters.Add(item.Key, new ParameterBindingResult(parameter, value, constantValue)); } @@ -616,9 +616,9 @@ private void CreateBindingResultForSyntacticBind(CommandAst commandAst) } CommandParameterAst parameter = commandElement as CommandParameterAst; - if (parameter != null) + if (parameter is not null) { - if (currentParameter != null) + if (currentParameter is not null) { // Assume it was a switch AddSwitch(currentParameter.ParameterName, bindingResult); @@ -630,7 +630,7 @@ private void CreateBindingResultForSyntacticBind(CommandAst commandAst) bindingResult.Value = parameter; // If it's a parameter with argument, add them both to the dictionary - if (parameter.Argument != null) + if (parameter.Argument is not null) { bindingResult.Value = parameter.Argument; @@ -647,7 +647,7 @@ private void CreateBindingResultForSyntacticBind(CommandAst commandAst) else { // This isn't a parameter, it's a value for the previous parameter - if (currentParameter != null) + if (currentParameter is not null) { bindingResult.Value = commandElement; AddBoundParameter(currentParameter, currentParameter.ParameterName, bindingResult); @@ -665,7 +665,7 @@ private void CreateBindingResultForSyntacticBind(CommandAst commandAst) } // Catch any extra parameters at the end of the command - if (currentParameter != null) + if (currentParameter is not null) { // Assume it was a switch AddSwitch(currentParameter.ParameterName, bindingResult); @@ -733,7 +733,7 @@ public object ConstantValue internal set { - if (value != null) + if (value is not null) { _constantValue = value; } @@ -753,7 +753,7 @@ internal set _value = value; ConstantExpressionAst constantValueAst = value as ConstantExpressionAst; - if (constantValueAst != null) + if (constantValueAst is not null) { this.ConstantValue = constantValueAst.Value; } @@ -961,7 +961,7 @@ internal PseudoBindingInfo DoPseudoParameterBinding(CommandAst command, Type pip // analyze the command and reparse the arguments { ExecutionContext executionContext = LocalPipeline.GetExecutionContextFromTLS(); - if (executionContext != null) + if (executionContext is not null) { // WinBlue: 324316. This limits the interaction of pseudoparameterbinder with the actual host. SetTemporaryDefaultHost(executionContext); @@ -990,7 +990,7 @@ internal PseudoBindingInfo DoPseudoParameterBinding(CommandAst command, Type pip } } - if (_bindingEffective && (_isPipelineInputExpected || pipeArgumentType != null)) + if (_bindingEffective && (_isPipelineInputExpected || pipeArgumentType is not null)) { _pipelineInputType = pipeArgumentType; } @@ -1102,7 +1102,7 @@ private void RestoreHost(ExecutionContext executionContext) executionContext.EngineHostInterface.RevertHostRef(); // Re-apply saved host if any. - if (_restoreHost != null) + if (_restoreHost is not null) { executionContext.EngineHostInterface.SetHostRef(_restoreHost); _restoreHost = null; @@ -1199,26 +1199,26 @@ private bool PrepareCommandElements(ExecutionContext context) var commandProcessor = processor as CommandProcessor; var scriptProcessor = processor as ScriptCommandProcessorBase; - bool implementsDynamicParameters = commandProcessor != null && + bool implementsDynamicParameters = commandProcessor is not null && commandProcessor.CommandInfo.ImplementsDynamicParameters; var argumentsToGetDynamicParameters = implementsDynamicParameters ? new List(_commandElements.Count) : null; - if (commandProcessor != null || scriptProcessor != null) + if (commandProcessor is not null || scriptProcessor is not null) { // Pre-processing the arguments -- command arguments for (commandIndex++; commandIndex < _commandElements.Count; commandIndex++) { var parameter = _commandElements[commandIndex] as CommandParameterAst; - if (parameter != null) + if (parameter is not null) { - if (argumentsToGetDynamicParameters != null) + if (argumentsToGetDynamicParameters is not null) { argumentsToGetDynamicParameters.Add(parameter.Extent.Text); } - AstPair parameterArg = parameter.Argument != null + AstPair parameterArg = parameter.Argument is not null ? new AstPair(parameter) : new AstPair(parameter, (ExpressionAst)null); @@ -1227,7 +1227,7 @@ private bool PrepareCommandElements(ExecutionContext context) else { var dash = _commandElements[commandIndex] as StringConstantExpressionAst; - if (dash != null && dash.Value.Trim().Equals("-", StringComparison.OrdinalIgnoreCase)) + if (dash is not null && dash.Value.Trim().Equals("-", StringComparison.OrdinalIgnoreCase)) { // "-" is represented by StringConstantExpressionAst. Most likely the user type a tab here, // and we don't want it be treated as an argument @@ -1235,7 +1235,7 @@ private bool PrepareCommandElements(ExecutionContext context) } var expressionArgument = _commandElements[commandIndex] as ExpressionAst; - if (expressionArgument != null) + if (expressionArgument is not null) { argumentsToGetDynamicParameters?.Add(expressionArgument.Extent.Text); @@ -1245,7 +1245,7 @@ private bool PrepareCommandElements(ExecutionContext context) } } - if (commandProcessor != null) + if (commandProcessor is not null) { _function = false; if (implementsDynamicParameters) @@ -1302,7 +1302,7 @@ private bool PrepareCommandElements(ExecutionContext context) _bindableParameters = commandProcessor.CmdletParameterBinderController.BindableParameters; _defaultParameterSetFlag = commandProcessor.CommandInfo.CommandMetadata.DefaultParameterSetFlag; } - else if (scriptProcessor != null) + else if (scriptProcessor is not null) { _function = true; _commandInfo = scriptProcessor.CommandInfo; @@ -1322,14 +1322,14 @@ private bool PrepareCommandElements(ExecutionContext context) // Check if there is pipeline input CommandBaseAst preCmdBaseAst = null; var pipe = _commandAst.Parent as PipelineAst; - Diagnostics.Assert(pipe != null, "CommandAst should has a PipelineAst parent"); + Diagnostics.Assert(pipe is not null, "CommandAst should has a PipelineAst parent"); if (pipe.PipelineElements.Count > 1) { foreach (CommandBaseAst cmdBase in pipe.PipelineElements) { if (cmdBase.GetHashCode() == _commandAst.GetHashCode()) { - _isPipelineInputExpected = preCmdBaseAst != null; + _isPipelineInputExpected = preCmdBaseAst is not null; if (_isPipelineInputExpected) _pipelineInputType = typeof(object); break; @@ -1347,7 +1347,7 @@ private CommandProcessorBase PrepareFromAst(ExecutionContext context, out string // Analyze the Ast var exportVisitor = new ExportVisitor(forCompletion: true); Ast ast = _commandAst; - while (ast.Parent != null) + while (ast.Parent is not null) { ast = ast.Parent; } @@ -1357,7 +1357,7 @@ private CommandProcessorBase PrepareFromAst(ExecutionContext context, out string CommandProcessorBase commandProcessor = null; resolvedCommandName = _commandAst.GetCommandName(); - if (resolvedCommandName != null) + if (resolvedCommandName is not null) { string alias; int resolvedAliasCount = 0; @@ -1471,7 +1471,7 @@ private bool ParseParameterArguments(CommandParameterAst paramAstAtCursor) { // Testing paramsAstAtCursor ensures we only give up during tab completion, // otherwise we know this is a missing parameter. - if (paramAstAtCursor != null) + if (paramAstAtCursor is not null) { // Do not use the parsed arguments _arguments = null; @@ -1538,7 +1538,7 @@ private bool ParseParameterArguments(CommandParameterAst paramAstAtCursor) { // The next item is a pure argument. AstPair nextArgument = nextArg as AstPair; - Diagnostics.Assert(nextArgument != null, "the next item should be a pure argument here"); + Diagnostics.Assert(nextArgument is not null, "the next item should be a pure argument here"); Diagnostics.Assert(nextArgument.ArgumentSpecified && !nextArgument.ArgumentIsCommandParameterAst, "the next item should be a pure argument here"); AstPair newArg = new AstPair(argument.Parameter, (ExpressionAst)nextArgument.Argument); @@ -1881,7 +1881,7 @@ private Collection BindRemainingParameters(Collection< foreach (AstParameterArgumentPair arg in unboundArguments) { AstPair realArg = arg as AstPair; - Diagnostics.Assert(realArg != null && !realArg.ParameterSpecified && !realArg.ArgumentIsCommandParameterAst, + Diagnostics.Assert(realArg is not null && !realArg.ParameterSpecified && !realArg.ArgumentIsCommandParameterAst, "all unbound arguments left should be pure ExpressionAst arguments"); argList.Add((ExpressionAst)realArg.Argument); } diff --git a/src/System.Management.Automation/engine/CommandDiscovery.cs b/src/System.Management.Automation/engine/CommandDiscovery.cs index fd10f656218..f3bc16f94d1 100644 --- a/src/System.Management.Automation/engine/CommandDiscovery.cs +++ b/src/System.Management.Automation/engine/CommandDiscovery.cs @@ -70,7 +70,7 @@ public ScriptBlock CommandScriptBlock set { _scriptBlock = value; - if (_scriptBlock != null) + if (_scriptBlock is not null) { string dynamicName = "LookupHandlerReplacementFor<<" + CommandName + ">>"; Command = new FunctionInfo(dynamicName, _scriptBlock, _context); @@ -273,7 +273,7 @@ internal CommandProcessorBase LookupCommandProcessor(string commandName, CommandProcessorBase processor = null; CommandInfo commandInfo = LookupCommandInfo(commandName, commandOrigin); - if (commandInfo != null) + if (commandInfo is not null) { processor = LookupCommandProcessor(commandInfo, commandOrigin, useLocalScope, null); // commandInfo.Name might be different than commandName - restore the original invocation name @@ -286,7 +286,7 @@ internal CommandProcessorBase LookupCommandProcessor(string commandName, internal static void VerifyRequiredModules(ExternalScriptInfo scriptInfo, ExecutionContext context) { // Check Required Modules - if (scriptInfo.RequiresModules != null) + if (scriptInfo.RequiresModules is not null) { foreach (var requiredModule in scriptInfo.RequiresModules) { @@ -298,7 +298,7 @@ internal static void VerifyRequiredModules(ExternalScriptInfo scriptInfo, Execut moduleManifestPath: null, manifestProcessingFlags: ModuleCmdletBase.ManifestProcessingFlags.LoadElements | ModuleCmdletBase.ManifestProcessingFlags.WriteErrors, error: out error); - if (error != null) + if (error is not null) { ScriptRequiresException scriptRequiresException = new ScriptRequiresException( @@ -330,11 +330,11 @@ private CommandProcessorBase CreateScriptProcessorForSingleShell(ExternalScriptI VerifyScriptRequirements(scriptInfo, Context); IEnumerable requiresPSSnapIns = scriptInfo.RequiresPSSnapIns; - if (requiresPSSnapIns != null && requiresPSSnapIns.Any()) + if (requiresPSSnapIns is not null && requiresPSSnapIns.Any()) { Collection requiresMissingPSSnapIns = null; VerifyRequiredSnapins(requiresPSSnapIns, context, out requiresMissingPSSnapIns); - if (requiresMissingPSSnapIns != null) + if (requiresMissingPSSnapIns is not null) { ScriptRequiresException scriptRequiresException = new ScriptRequiresException( @@ -369,7 +369,7 @@ private CommandProcessorBase CreateScriptProcessorForSingleShell(ExternalScriptI private static void VerifyRequiredSnapins(IEnumerable requiresPSSnapIns, ExecutionContext context, out Collection requiresMissingPSSnapIns) { requiresMissingPSSnapIns = null; - Dbg.Assert(context.InitialSessionState != null, "PowerShell should be hosted with InitialSessionState"); + Dbg.Assert(context.InitialSessionState is not null, "PowerShell should be hosted with InitialSessionState"); foreach (var requiresPSSnapIn in requiresPSSnapIns) { @@ -388,11 +388,11 @@ private static void VerifyRequiredSnapins(IEnumerable req { // the requires PSSnapin is loaded. now check the PSSnapin version PSSnapInInfo loadedPSSnapIn = loadedPSSnapIns.First(); - Diagnostics.Assert(loadedPSSnapIn.Version != null, + Diagnostics.Assert(loadedPSSnapIn.Version is not null, string.Format( CultureInfo.InvariantCulture, "Version is null for loaded PSSnapin {0}.", loadedPSSnapIn)); - if (requiresPSSnapIn.Version != null) + if (requiresPSSnapIn.Version is not null) { if (!AreInstalledRequiresVersionsCompatible( requiresPSSnapIn.Version, loadedPSSnapIn.Version)) @@ -426,7 +426,7 @@ internal static void VerifyPSVersion(ExternalScriptInfo scriptInfo) { Version requiresPSVersion = scriptInfo.RequiresPSVersion; // in single shell mode - if (requiresPSVersion != null) + if (requiresPSVersion is not null) { if (!Utils.IsPSVersionSupported(requiresPSVersion)) { @@ -443,7 +443,7 @@ internal static void VerifyPSVersion(ExternalScriptInfo scriptInfo) internal static void VerifyPSEdition(ExternalScriptInfo scriptInfo) { - if (scriptInfo.RequiresPSEditions != null) + if (scriptInfo.RequiresPSEditions is not null) { var isCurrentEditionListed = false; var isRequiresPSEditionSpecified = false; @@ -654,7 +654,7 @@ private static CommandProcessorBase CreateCommandProcessorForScript(ScriptInfo s { sessionState = sessionState ?? scriptInfo.ScriptBlock.SessionStateInternal ?? context.EngineSessionState; CommandProcessorBase scriptAsCmdletProcessor = GetScriptAsCmdletProcessor(scriptInfo, context, useNewScope, true, sessionState); - if (scriptAsCmdletProcessor != null) + if (scriptAsCmdletProcessor is not null) { return scriptAsCmdletProcessor; } @@ -666,7 +666,7 @@ private static CommandProcessorBase CreateCommandProcessorForScript(ExternalScri { sessionState = sessionState ?? scriptInfo.ScriptBlock.SessionStateInternal ?? context.EngineSessionState; CommandProcessorBase scriptAsCmdletProcessor = GetScriptAsCmdletProcessor(scriptInfo, context, useNewScope, true, sessionState); - if (scriptAsCmdletProcessor != null) + if (scriptAsCmdletProcessor is not null) { return scriptAsCmdletProcessor; } @@ -678,7 +678,7 @@ internal static CommandProcessorBase CreateCommandProcessorForScript(FunctionInf { sessionState = sessionState ?? functionInfo.ScriptBlock.SessionStateInternal ?? context.EngineSessionState; CommandProcessorBase scriptAsCmdletProcessor = GetScriptAsCmdletProcessor(functionInfo, context, useNewScope, false, sessionState); - if (scriptAsCmdletProcessor != null) + if (scriptAsCmdletProcessor is not null) { return scriptAsCmdletProcessor; } @@ -764,7 +764,7 @@ internal static CommandInfo LookupCommandInfo( CommandLookupEventArgs eventArgs = null; EventHandler preCommandLookupEvent = context.EngineIntrinsics.InvokeCommand.PreCommandLookupAction; - if (preCommandLookupEvent != null) + if (preCommandLookupEvent is not null) { discoveryTracer.WriteLine("Executing PreCommandLookupAction: {0}", commandName); try @@ -795,7 +795,7 @@ internal static CommandInfo LookupCommandInfo( result = TryNormalSearch(commandName, context, commandOrigin, searchResolutionOptions, commandTypes, ref lastError); - if (result != null) + if (result is not null) break; // Try the module-qualified auto-loading (unless module auto-loading has been entirely disabled) @@ -804,7 +804,7 @@ internal static CommandInfo LookupCommandInfo( result = TryModuleAutoLoading(commandName, context, originalCommandName, commandOrigin, ref lastError); } - if (result != null) + if (result is not null) break; // See if the this was not module-qualified. In that case, we should look for the first module @@ -824,17 +824,17 @@ internal static CommandInfo LookupCommandInfo( } else { - if (eventArgs.Command != null) + if (eventArgs.Command is not null) { result = eventArgs.Command; } } // If we resolved a command, give the PostCommandLookup a chance to change it - if (result != null) + if (result is not null) { System.EventHandler postAction = context.EngineIntrinsics.InvokeCommand.PostCommandLookupAction; - if (postAction != null) + if (postAction is not null) { discoveryTracer.WriteLine("Executing PostCommandLookupAction: {0}", originalCommandName); try @@ -845,7 +845,7 @@ internal static CommandInfo LookupCommandInfo( eventArgs.Command = result; postAction.Invoke(originalCommandName, eventArgs); - if (eventArgs != null) + if (eventArgs is not null) { result = eventArgs.Command; discoveryTracer.WriteLine("PreCommandLookupAction returned: {0}", eventArgs.Command); @@ -896,7 +896,7 @@ Because this function does not check the result of a (currently failing) `PSSche { CmdletInfo cmdletInfo = context.SessionState.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\\Import-Module"); if ((commandOrigin == CommandOrigin.Internal) || - ((cmdletInfo != null) && (cmdletInfo.Visibility == SessionStateEntryVisibility.Public))) + ((cmdletInfo is not null) && (cmdletInfo.Visibility == SessionStateEntryVisibility.Public))) { foreach (var module in System.Management.Automation.ExecutionContext.ModulesWithJobSourceAdapters) { @@ -954,7 +954,7 @@ private static CommandInfo InvokeCommandNotFoundHandler(string commandName, Exec CommandInfo result = null; CommandLookupEventArgs eventArgs; System.EventHandler cmdNotFoundHandler = context.EngineIntrinsics.InvokeCommand.CommandNotFoundAction; - if (cmdNotFoundHandler != null) + if (cmdNotFoundHandler is not null) { discoveryTracer.WriteLine("Executing CommandNotFoundAction: {0}", commandName); try @@ -1062,13 +1062,13 @@ private static CommandInfo TryModuleAutoDiscovery(string commandName, CmdletInfo cmdletInfo = context.SessionState.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\\Get-Module"); if ((commandOrigin == CommandOrigin.Internal) || - ((cmdletInfo != null) && (cmdletInfo.Visibility == SessionStateEntryVisibility.Public))) + ((cmdletInfo is not null) && (cmdletInfo.Visibility == SessionStateEntryVisibility.Public))) { // Search for a module with a matching command, as long as the user would have the ability to // import the module. cmdletInfo = context.SessionState.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\\Import-Module"); if (((commandOrigin == CommandOrigin.Internal) || - ((cmdletInfo != null) && (cmdletInfo.Visibility == SessionStateEntryVisibility.Public)))) + ((cmdletInfo is not null) && (cmdletInfo.Visibility == SessionStateEntryVisibility.Public)))) { discoveryTracer.WriteLine("Executing non module-qualified search: {0}", commandName); context.CommandDiscovery.RegisterLookupCommandInfoAction("ActiveModuleSearch", commandName); @@ -1098,7 +1098,7 @@ private static CommandInfo TryModuleAutoDiscovery(string commandName, Exception exception; discoveryTracer.WriteLine("Found in module: {0}", expandedModulePath); Collection matchingModule = AutoloadSpecifiedModule(expandedModulePath, context, - cmdletInfo != null ? cmdletInfo.Visibility : SessionStateEntryVisibility.Private, + cmdletInfo is not null ? cmdletInfo.Visibility : SessionStateEntryVisibility.Private, out exception); lastError = exception; if ((matchingModule is null) || (matchingModule.Count == 0)) @@ -1114,7 +1114,7 @@ private static CommandInfo TryModuleAutoDiscovery(string commandName, result = LookupCommandInfo(commandName, commandTypes, searchResolutionOptions, commandOrigin, context); } - if (result != null) + if (result is not null) { break; } @@ -1122,7 +1122,7 @@ private static CommandInfo TryModuleAutoDiscovery(string commandName, #if !CORECLR // Close the progress pane that may have popped up from analyzing UNC paths. - if (context.CurrentCommandProcessor != null) + if (context.CurrentCommandProcessor is not null) { ProgressRecord analysisProgress = new ProgressRecord(0, Modules.ScriptAnalysisPreparing, " "); analysisProgress.RecordType = ProgressRecordType.Completed; @@ -1201,7 +1201,7 @@ private static CommandInfo TryModuleAutoLoading(string commandName, ExecutionCon // Verify that auto-loading is only done on for internal commands if it's not public CmdletInfo cmdletInfo = context.SessionState.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\\Import-Module"); if ((commandOrigin == CommandOrigin.Internal) || - ((cmdletInfo != null) && (cmdletInfo.Visibility == SessionStateEntryVisibility.Public))) + ((cmdletInfo is not null) && (cmdletInfo.Visibility == SessionStateEntryVisibility.Public))) { List existingModule = context.Modules.GetModules(new string[] { moduleName }, false); PSModuleInfo discoveredModule = null; @@ -1307,9 +1307,9 @@ internal LookupPathCollection GetLookupDirectoryPaths() path); bool isPathCacheValid = - path != null && + path is not null && string.Equals(_pathCacheKey, path, StringComparison.OrdinalIgnoreCase) && - _cachedPath != null; + _cachedPath is not null; if (!isPathCacheValid) { @@ -1320,7 +1320,7 @@ internal LookupPathCollection GetLookupDirectoryPaths() _pathCacheKey = path; - if (_pathCacheKey != null) + if (_pathCacheKey is not null) { string[] tokenizedPath = _pathCacheKey.Split(Utils.Separators.PathSeparator, StringSplitOptions.RemoveEmptyEntries); _cachedPath = new Collection(); @@ -1413,7 +1413,7 @@ private static void InitPathExtCache(string pathExt) { lock (s_lockObject) { - s_cachedPathExtCollection = pathExt != null + s_cachedPathExtCollection = pathExt is not null ? pathExt.Split(Utils.Separators.PathSeparator, StringSplitOptions.RemoveEmptyEntries) : Array.Empty(); s_cachedPathExtCollectionWithPs1 = new string[s_cachedPathExtCollection.Length + 1]; @@ -1519,8 +1519,8 @@ internal IEnumerator GetCmdletInfo(string cmdletName, bool searchAll internal static PSModuleAutoLoadingPreference GetCommandDiscoveryPreference(ExecutionContext context, VariablePath variablePath, string environmentVariable) { - Dbg.Assert(context != null, "context cannot be Null"); - Dbg.Assert(variablePath != null, "variablePath must be non empty"); + Dbg.Assert(context is not null, "context cannot be Null"); + Dbg.Assert(variablePath is not null, "variablePath must be non empty"); Dbg.Assert(!string.IsNullOrEmpty(environmentVariable), "environmentVariable must be non empty"); if (context is null) @@ -1533,7 +1533,7 @@ internal static PSModuleAutoLoadingPreference GetCommandDiscoveryPreference(Exec try { - if (result != null) + if (result is not null) { return LanguagePrimitives.ConvertTo(result); } diff --git a/src/System.Management.Automation/engine/CommandInfo.cs b/src/System.Management.Automation/engine/CommandInfo.cs index a5010521ddc..c75d10e6987 100644 --- a/src/System.Management.Automation/engine/CommandInfo.cs +++ b/src/System.Management.Automation/engine/CommandInfo.cs @@ -198,7 +198,7 @@ public virtual Version Version { if (_version is null) { - if (Module != null) + if (Module is not null) { if (Module.Version.Equals(new Version(0, 0))) { @@ -235,7 +235,7 @@ internal ExecutionContext Context set { _context = value; - if ((value != null) && !this.DefiningLanguageMode.HasValue) + if ((value is not null) && !this.DefiningLanguageMode.HasValue) { this.DefiningLanguageMode = value.LanguageMode; } @@ -324,7 +324,7 @@ public virtual SessionStateEntryVisibility Visibility CopiedCommand.Visibility = value; } - if (value == SessionStateEntryVisibility.Private && Module != null) + if (value == SessionStateEntryVisibility.Private && Module is not null) { Module.ModuleHasPrivateMembers = true; } @@ -362,14 +362,14 @@ public string ModuleName { string moduleName = null; - if (Module != null && !string.IsNullOrEmpty(Module.Name)) + if (Module is not null && !string.IsNullOrEmpty(Module.Name)) { moduleName = Module.Name; } else { CmdletInfo cmdlet = this as CmdletInfo; - if (cmdlet != null && cmdlet.PSSnapIn != null) + if (cmdlet is not null && cmdlet.PSSnapIn is not null) { moduleName = cmdlet.PSSnapInName; } @@ -464,7 +464,7 @@ private MergedCommandParameterMetadata GetMergedCommandParameterMetadataSafely() processInCurrentThread: true, waitForCompletionInCurrentThread: true); - if (eventArgs.Exception != null) + if (eventArgs.Exception is not null) { // An exception happened on a different thread, rethrow it here on the correct thread. eventArgs.Exception.Throw(); @@ -487,7 +487,7 @@ private class GetMergedCommandParameterMetadataSafelyEventArgs : EventArgs private void OnGetMergedCommandParameterMetadataSafelyEventHandler(object sender, PSEventArgs args) { var eventArgs = args.SourceEventArgs as GetMergedCommandParameterMetadataSafelyEventArgs; - if (eventArgs != null) + if (eventArgs is not null) { try { @@ -515,7 +515,7 @@ private void GetMergedCommandParameterMetadata(out MergedCommandParameterMetadat // metadata actually stems from the running of the same cmdlet. In this case, we can just use the current CommandProcessor to // retrieve all bindable parameters, which should include the dynamic parameters that have been discovered already. CommandProcessor processor; - if (Context.CurrentCommandProcessor != null && Context.CurrentCommandProcessor.CommandInfo == this) + if (Context.CurrentCommandProcessor is not null && Context.CurrentCommandProcessor.CommandInfo == this) { // Accessing the parameters within the invocation of the same cmdlet/advanced function. processor = (CommandProcessor)Context.CurrentCommandProcessor; @@ -523,7 +523,7 @@ private void GetMergedCommandParameterMetadata(out MergedCommandParameterMetadat else { IScriptCommandInfo scriptCommand = this as IScriptCommandInfo; - processor = scriptCommand != null + processor = scriptCommand is not null ? new CommandProcessor(scriptCommand, _context, useLocalScope: true, fromScriptFile: false, sessionState: scriptCommand.ScriptBlock.SessionStateInternal ?? Context.EngineSessionState) : new CommandProcessor((CmdletInfo)this, _context) { UseLocalScope = true }; @@ -564,7 +564,7 @@ public virtual Dictionary Parameters { Dictionary result = new Dictionary(StringComparer.OrdinalIgnoreCase); - if (ImplementsDynamicParameters && Context != null) + if (ImplementsDynamicParameters && Context is not null) { MergedCommandParameterMetadata merged = GetMergedCommandParameterMetadataSafely(); @@ -712,7 +712,7 @@ internal static Collection GetParameterMetadata(Command { Collection result = new Collection(); - if (parameterMetadata != null) + if (parameterMetadata is not null) { if (parameterMetadata.ParameterSetCount == 0) { @@ -765,7 +765,7 @@ public class PSTypeName public PSTypeName(Type type) { _type = type; - if (_type != null) + if (_type is not null) { Name = _type.FullName; } @@ -818,14 +818,14 @@ public PSTypeName(ITypeName typeName) } _type = typeName.GetReflectionType(); - if (_type != null) + if (_type is not null) { Name = _type.FullName; } else { var t = typeName as TypeName; - if (t != null && t._typeDefinitionAst != null) + if (t is not null && t._typeDefinitionAst is not null) { TypeDefinitionAst = t._typeDefinitionAst; Name = TypeDefinitionAst.Name; @@ -855,7 +855,7 @@ public Type Type { if (_type is null) { - if (TypeDefinitionAst != null) + if (TypeDefinitionAst is not null) { _type = TypeDefinitionAst.Type; } @@ -868,7 +868,7 @@ public Type Type if (_type is null) { // We ignore the exception. - if (Name != null && + if (Name is not null && Name.StartsWith('[') && Name.EndsWith(']')) { diff --git a/src/System.Management.Automation/engine/CommandMetadata.cs b/src/System.Management.Automation/engine/CommandMetadata.cs index f7a42753e12..0ac15f3341c 100644 --- a/src/System.Management.Automation/engine/CommandMetadata.cs +++ b/src/System.Management.Automation/engine/CommandMetadata.cs @@ -119,17 +119,17 @@ public CommandMetadata(CommandInfo commandInfo, bool shouldGenerateCommonParamet CmdletInfo cmdletInfo; ExternalScriptInfo scriptInfo; FunctionInfo funcInfo; - if ((cmdletInfo = commandInfo as CmdletInfo) != null) + if ((cmdletInfo = commandInfo as CmdletInfo) is not null) { Init(commandInfo.Name, cmdletInfo.FullName, cmdletInfo.ImplementingType, shouldGenerateCommonParameters); } - else if ((scriptInfo = commandInfo as ExternalScriptInfo) != null) + else if ((scriptInfo = commandInfo as ExternalScriptInfo) is not null) { // Accessing the script block property here reads and parses the script Init(scriptInfo.ScriptBlock, scriptInfo.Path, shouldGenerateCommonParameters); _wrappedCommandType = CommandTypes.ExternalScript; } - else if ((funcInfo = commandInfo as FunctionInfo) != null) + else if ((funcInfo = commandInfo as FunctionInfo) is not null) { Init(funcInfo.ScriptBlock, funcInfo.Name, shouldGenerateCommonParameters); _wrappedCommandType = commandInfo.CommandType; @@ -238,7 +238,7 @@ private void Init(string name, string fullyQualifiedName, Type commandType, bool Name = name; this.CommandType = commandType; - if (commandType != null) + if (commandType is not null) { ConstructCmdletMetadataUsingReflection(); _shouldGenerateCommonParameters = shouldGenerateCommonParameters; @@ -263,7 +263,7 @@ private void Init(ScriptBlock scriptBlock, string name, bool shouldGenerateCommo } CmdletBindingAttribute cmdletBindingAttribute = scriptBlock.CmdletBindingAttribute; - if (cmdletBindingAttribute != null) + if (cmdletBindingAttribute is not null) { ProcessCmdletAttribute(cmdletBindingAttribute); } @@ -320,7 +320,7 @@ internal static CommandMetadata Get(string commandName, Type cmdletType, Executi CommandMetadata result = null; - if ((context != null) && (cmdletType != null)) + if ((context is not null) && (cmdletType is not null)) { string cmdletTypeName = cmdletType.AssemblyQualifiedName; s_commandMetadataCache.TryGetValue(cmdletTypeName, out result); @@ -330,7 +330,7 @@ internal static CommandMetadata Get(string commandName, Type cmdletType, Executi { result = new CommandMetadata(commandName, cmdletType, context); - if ((context != null) && (cmdletType != null)) + if ((context is not null) && (cmdletType is not null)) { string cmdletTypeName = cmdletType.AssemblyQualifiedName; s_commandMetadataCache.TryAdd(cmdletTypeName, result); @@ -375,7 +375,7 @@ internal CommandMetadata(string commandName, Type cmdletType, ExecutionContext c Name = commandName; this.CommandType = cmdletType; - if (cmdletType != null) + if (cmdletType is not null) { InternalParameterMetadata parameterMetadata = InternalParameterMetadata.Get(cmdletType, context, false); ConstructCmdletMetadataUsingReflection(); @@ -417,7 +417,7 @@ internal CommandMetadata(ScriptBlock scriptblock, string commandName, ExecutionC CmdletBindingAttribute cmdletBindingAttribute = scriptblock.CmdletBindingAttribute; - if (cmdletBindingAttribute != null) + if (cmdletBindingAttribute is not null) { ProcessCmdletAttribute(cmdletBindingAttribute); } @@ -520,7 +520,7 @@ public RemotingCapability RemotingCapability { RemotingCapability currentRemotingCapability = _remotingCapability; if ((currentRemotingCapability == Automation.RemotingCapability.PowerShell) && - ((this.Parameters != null) && this.Parameters.ContainsKey("ComputerName"))) + ((this.Parameters is not null) && this.Parameters.ContainsKey("ComputerName"))) { _remotingCapability = Automation.RemotingCapability.SupportedByCommand; } @@ -552,7 +552,7 @@ public Dictionary Parameters if (_parameters is null) { // Return parameters for a script block - if (_scriptBlock != null) + if (_scriptBlock is not null) { InternalParameterMetadata parameterMetadata = InternalParameterMetadata.Get(_scriptBlock.RuntimeDefinedParameters, false, _scriptBlock.UsesCmdletBinding); @@ -560,7 +560,7 @@ public Dictionary Parameters MergeParameterMetadata(null, parameterMetadata, _shouldGenerateCommonParameters); _parameters = ParameterMetadata.GetParameterMetadata(mergedCommandParameterMetadata); } - else if (this.CommandType != null) + else if (this.CommandType is not null) { // Construct compiled parameter metadata from this InternalParameterMetadata parameterMetadata = InternalParameterMetadata.Get(this.CommandType, null, false); @@ -675,14 +675,14 @@ internal CommandTypes WrappedCommandType private void ConstructCmdletMetadataUsingReflection() { Diagnostics.Assert( - CommandType != null, + CommandType is not null, "This method should only be called when constructed with the Type"); // Determine if the cmdlet implements dynamic parameters by looking for the interface Type dynamicParametersType = CommandType.GetInterface(typeof(IDynamicParameters).Name, true); - if (dynamicParametersType != null) + if (dynamicParametersType is not null) { _implementsDynamicParameters = true; } @@ -694,7 +694,7 @@ private void ConstructCmdletMetadataUsingReflection() foreach (Attribute attribute in customAttributes) { CmdletAttribute cmdletAttribute = attribute as CmdletAttribute; - if (cmdletAttribute != null) + if (cmdletAttribute is not null) { ProcessCmdletAttribute(cmdletAttribute); this.Name = cmdletAttribute.VerbName + "-" + cmdletAttribute.NounName; @@ -752,7 +752,7 @@ private void ProcessCmdletAttribute(CmdletCommonMetadataAttribute attribute) // Check to see if the cmdlet uses positional binding var cmdletBindingAttribute = attribute as CmdletBindingAttribute; - if (cmdletBindingAttribute != null) + if (cmdletBindingAttribute is not null) { PositionalBinding = cmdletBindingAttribute.PositionalBinding; } @@ -969,7 +969,7 @@ internal string GetParamBlock() foreach (var pair in Parameters) { - if (paramDataPrefix != null) + if (paramDataPrefix is not null) { parameters.Append(paramDataPrefix); } diff --git a/src/System.Management.Automation/engine/CommandParameter.cs b/src/System.Management.Automation/engine/CommandParameter.cs index 0459427242b..6d350150e1a 100644 --- a/src/System.Management.Automation/engine/CommandParameter.cs +++ b/src/System.Management.Automation/engine/CommandParameter.cs @@ -32,9 +32,9 @@ private class Argument internal bool SpaceAfterParameter { get { return _spaceAfterParameter; } } - internal bool ParameterNameSpecified { get { return _parameter != null; } } + internal bool ParameterNameSpecified { get { return _parameter is not null; } } - internal bool ArgumentSpecified { get { return _argument != null; } } + internal bool ArgumentSpecified { get { return _argument is not null; } } internal bool ParameterAndArgumentSpecified { get { return ParameterNameSpecified && ArgumentSpecified; } } @@ -105,7 +105,7 @@ internal IScriptExtent ArgumentExtent /// internal object ArgumentValue { - get { return _argument != null ? _argument.value : UnboundParameter.Value; } + get { return _argument is not null ? _argument.value : UnboundParameter.Value; } } /// @@ -113,7 +113,7 @@ internal object ArgumentValue /// internal bool ArgumentSplatted { - get { return _argument != null ? _argument.splatted : false; } + get { return _argument is not null ? _argument.splatted : false; } } /// diff --git a/src/System.Management.Automation/engine/CommandPathSearch.cs b/src/System.Management.Automation/engine/CommandPathSearch.cs index 7975b41b0ad..82cb404d914 100644 --- a/src/System.Management.Automation/engine/CommandPathSearch.cs +++ b/src/System.Management.Automation/engine/CommandPathSearch.cs @@ -49,7 +49,7 @@ internal CommandPathSearch( { _useFuzzyMatch = useFuzzyMatch; string[] commandPatterns; - if (acceptableCommandNames != null) + if (acceptableCommandNames is not null) { // The name passed in is not a pattern. To minimize enumerating the file system, we // turn the command name into a pattern and then match against extensions in PATHEXT. @@ -106,7 +106,7 @@ private void ResolveCurrentDirectoryInLookupPaths() // Only use the directory if it gets resolved by the FileSystemProvider bool isCurrentDriveValid = - sessionState.CurrentDrive != null && + sessionState.CurrentDrive is not null && sessionState.CurrentDrive.Provider.NameEquals(fileSystemProviderName) && sessionState.IsProviderLoaded(fileSystemProviderName); @@ -178,7 +178,7 @@ private void ResolveCurrentDirectoryInLookupPaths() // If we successfully resolved the path, make sure it is unique. Remove // any duplicates found after the first occurrence of the path. - if (resolvedDirectory != null) + if (resolvedDirectory is not null) { int existingIndex = _lookupPaths.IndexOf(resolvedDirectory); @@ -433,14 +433,14 @@ private void GetNewDirectoryResults(string pattern, string directory) } } - result = _postProcessEnumeratedFiles != null + result = _postProcessEnumeratedFiles is not null ? _postProcessEnumeratedFiles(files.ToArray()) : files; } else { var matchingFiles = Directory.EnumerateFiles(directory, pattern); - result = _postProcessEnumeratedFiles != null + result = _postProcessEnumeratedFiles is not null ? _postProcessEnumeratedFiles(matchingFiles.ToArray()) : matchingFiles; } @@ -481,7 +481,7 @@ private void GetNewDirectoryResults(string pattern, string directory) // Porting note: allow files with executable bit on non-Windows platforms Collection? result = null; - if (baseNames.Length > 0 && _acceptableCommandNames != null) + if (baseNames.Length > 0 && _acceptableCommandNames is not null) { foreach (var name in _acceptableCommandNames) { diff --git a/src/System.Management.Automation/engine/CommandProcessor.cs b/src/System.Management.Automation/engine/CommandProcessor.cs index ced0c85e9d4..bd3e926569c 100644 --- a/src/System.Management.Automation/engine/CommandProcessor.cs +++ b/src/System.Management.Automation/engine/CommandProcessor.cs @@ -109,7 +109,7 @@ internal ParameterBinderController NewParameterBinderController(InternalCommand ParameterBinderBase parameterBinder; IScriptCommandInfo scriptCommandInfo = CommandInfo as IScriptCommandInfo; - if (scriptCommandInfo != null) + if (scriptCommandInfo is not null) { parameterBinder = new ScriptParameterBinder(scriptCommandInfo.ScriptBlock, cmdlet.MyInvocation, this._context, cmdlet, CommandScope); } @@ -167,7 +167,7 @@ internal void BindCommandLineParameters() using (commandRuntime.AllowThisCommandToWrite(false)) { Diagnostics.Assert( - this.CmdletParameterBinderController != null, + this.CmdletParameterBinderController is not null, "A parameter binder controller should always be available"); // Always set the hash table on MyInvocation so it's available for both interpreted cmdlets @@ -210,7 +210,7 @@ internal override void Prepare(IDictionary psDefaultParameterValues) this.CmdletParameterBinderController.DefaultParameterValues = psDefaultParameterValues; Diagnostics.Assert( - this.Command != null, + this.Command is not null, "CommandProcessor did not initialize Command\n" + this.CommandInfo.Name); PSLanguageMode? oldLanguageMode = null; @@ -218,7 +218,7 @@ internal override void Prepare(IDictionary psDefaultParameterValues) try { var scriptCmdletInfo = this.CommandInfo as IScriptCommandInfo; - if (scriptCmdletInfo != null && + if (scriptCmdletInfo is not null && scriptCmdletInfo.ScriptBlock.LanguageMode.HasValue && scriptCmdletInfo.ScriptBlock.LanguageMode != Context.LanguageMode) { @@ -258,7 +258,7 @@ protected override void OnSetCurrentScope() // When dotting a script cmdlet, push the locals of automatic variables to // the 'DottedScopes' of the current scope. PSScriptCmdlet scriptCmdlet = this.Command as PSScriptCmdlet; - if (scriptCmdlet != null && !UseLocalScope) + if (scriptCmdlet is not null && !UseLocalScope) { scriptCmdlet.PushDottedScope(CommandSessionState.CurrentScope); } @@ -269,7 +269,7 @@ protected override void OnRestorePreviousScope() // When dotting a script cmdlet, pop the locals of automatic variables from // the 'DottedScopes' of the current scope. PSScriptCmdlet scriptCmdlet = this.Command as PSScriptCmdlet; - if (scriptCmdlet != null && !UseLocalScope) + if (scriptCmdlet is not null && !UseLocalScope) { scriptCmdlet.PopDottedScope(CommandSessionState.CurrentScope); } @@ -280,7 +280,7 @@ protected override void OnRestorePreviousScope() /// internal override void DoBegin() { - if (!RanBeginAlready && CmdletParameterBinderController.ObsoleteParameterWarningList != null) + if (!RanBeginAlready && CmdletParameterBinderController.ObsoleteParameterWarningList is not null) { using (CommandRuntime.AllowThisCommandToWrite(false)) { @@ -337,7 +337,7 @@ internal override void ProcessRecord() } } - Debug.Assert(this.Command.MyInvocation.PipelineIterationInfo != null); // this should have been allocated when the pipeline was started + Debug.Assert(this.Command.MyInvocation.PipelineIterationInfo is not null); // this should have been allocated when the pipeline was started while (Read()) { @@ -360,7 +360,7 @@ internal override void ProcessRecord() // The RedirectShellErrorOutputPipe flag is used by the V2 hosting API to force the // redirection. // - if (this.RedirectShellErrorOutputPipe || _context.ShellFunctionErrorOutputPipe != null) + if (this.RedirectShellErrorOutputPipe || _context.ShellFunctionErrorOutputPipe is not null) { _context.ShellFunctionErrorOutputPipe = this.commandRuntime.ErrorOutputPipe; } @@ -368,7 +368,7 @@ internal override void ProcessRecord() // NOTICE-2004/06/08-JonN 959638 using (commandRuntime.AllowThisCommandToWrite(true)) { - if (CmdletParameterBinderController.ObsoleteParameterWarningList != null && + if (CmdletParameterBinderController.ObsoleteParameterWarningList is not null && CmdletParameterBinderController.ObsoleteParameterWarningList.Count > 0) { // Write out warning messages for the pipeline-value-bound obsolete parameters. @@ -416,7 +416,7 @@ internal override void ProcessRecord() _context.ShellFunctionErrorOutputPipe = oldErrorOutputPipe; } - if (exceptionToThrow != null) + if (exceptionToThrow is not null) { // This cmdlet threw an exception, so // wrap it and bubble it up. @@ -656,7 +656,7 @@ private bool ProcessInputPipelineObject(object inputObject) // turn it into a shell object if it isn't one already... // we depend on PSObject.AsPSObject() being idempotent - if // it's already a shell object, don't encapsulate it again. - if (inputObject != null) + if (inputObject is not null) { inputToOperateOn = PSObject.AsPSObject(inputObject); } @@ -700,7 +700,7 @@ private static Cmdlet ConstructInstance(Type type) /// private void Init(CmdletInfo cmdletInformation) { - Diagnostics.Assert(cmdletInformation != null, "Constructor should throw exception if LookupCommand returned null."); + Diagnostics.Assert(cmdletInformation is not null, "Constructor should throw exception if LookupCommand returned null."); Cmdlet newCmdlet = null; Exception initError = null; @@ -742,7 +742,7 @@ private void Init(CmdletInfo cmdletInformation) throw commandException; } - if (initError != null) + if (initError is not null) { // Log a command health event MshLog.LogCommandHealthEvent( @@ -828,18 +828,18 @@ private void InitCommon() /// true if user requested help; false otherwise. internal override bool IsHelpRequested(out string helpTarget, out HelpCategory helpCategory) { - if (this.arguments != null) + if (this.arguments is not null) { foreach (CommandParameterInternal parameter in this.arguments) { - Dbg.Assert(parameter != null, "CommandProcessor.arguments shouldn't have any null arguments"); + Dbg.Assert(parameter is not null, "CommandProcessor.arguments shouldn't have any null arguments"); if (parameter.IsDashQuestion()) { helpCategory = HelpCategory.All; // using InvocationName mainly to avoid bogus this.CommandInfo.Name // (when CmdletInfo.Name is initialized from "cmdlet" declaration // of a scriptblock and when "cmdlet" declaration doesn't specify any name) - if ((this.Command != null) && (this.Command.MyInvocation != null) && + if ((this.Command is not null) && (this.Command.MyInvocation is not null) && (!string.IsNullOrEmpty(this.Command.MyInvocation.InvocationName))) { helpTarget = this.Command.MyInvocation.InvocationName; diff --git a/src/System.Management.Automation/engine/CommandProcessorBase.cs b/src/System.Management.Automation/engine/CommandProcessorBase.cs index ed549162683..afcbfb592d4 100644 --- a/src/System.Management.Automation/engine/CommandProcessorBase.cs +++ b/src/System.Management.Automation/engine/CommandProcessorBase.cs @@ -41,7 +41,7 @@ internal CommandProcessorBase(CommandInfo commandInfo) if (commandInfo is IScriptCommandInfo scriptCommand) { ExperimentalAttribute expAttribute = scriptCommand.ScriptBlock.ExperimentalAttribute; - if (expAttribute != null && expAttribute.ToHide) + if (expAttribute is not null && expAttribute.ToHide) { string errorTemplate = expAttribute.ExperimentAction == ExperimentAction.Hide ? DiscoveryExceptions.ScriptDisabledWhenFeatureOn @@ -126,15 +126,15 @@ internal InternalCommand Command set { // The command runtime needs to be set up... - if (value != null) + if (value is not null) { value.commandRuntime = this.commandRuntime; - if (_command != null) + if (_command is not null) value.CommandInfo = _command.CommandInfo; // 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 is null && _context is not null) value.Context = _context; } @@ -367,7 +367,7 @@ internal void RestorePreviousScope() Context.EngineSessionState = _previousCommandSessionState; - if (_previousScope != null) + if (_previousScope is not null) { // Restore the scope but use the same session state instance we // got it from because the command may have changed the execution context @@ -394,7 +394,7 @@ internal void RestorePreviousScope() /// internal void AddParameter(CommandParameterInternal parameter) { - Diagnostics.Assert(parameter != null, "Caller to verify parameter argument"); + Diagnostics.Assert(parameter is not null, "Caller to verify parameter argument"); arguments.Add(parameter); } @@ -442,7 +442,7 @@ internal void DoPrepare(IDictionary psDefaultParameterValues) Prepare(psDefaultParameterValues); // Check obsolete attribute after Prepare so that -WarningAction will be respected for cmdlets - if (ObsoleteAttribute != null) + if (ObsoleteAttribute is not null) { // Obsolete command is rare. Put the IF here to avoid method call overhead HandleObsoleteCommand(ObsoleteAttribute); @@ -504,7 +504,7 @@ internal virtual void DoBegin() // The RedirectShellErrorOutputPipe flag is used by the V2 hosting API to force the // redirection. // - if (this.RedirectShellErrorOutputPipe || _context.ShellFunctionErrorOutputPipe != null) + if (this.RedirectShellErrorOutputPipe || _context.ShellFunctionErrorOutputPipe is not null) { _context.ShellFunctionErrorOutputPipe = this.commandRuntime.ErrorOutputPipe; } @@ -627,7 +627,7 @@ internal void DoComplete() // The RedirectShellErrorOutputPipe flag is used by the V2 hosting API to force the // redirection. // - if (this.RedirectShellErrorOutputPipe || _context.ShellFunctionErrorOutputPipe != null) + if (this.RedirectShellErrorOutputPipe || _context.ShellFunctionErrorOutputPipe is not null) { _context.ShellFunctionErrorOutputPipe = this.commandRuntime.ErrorOutputPipe; } @@ -645,13 +645,13 @@ internal void DoComplete() _context.CurrentCommandProcessor = oldCurrentCommandProcessor; // Destroy the local scope at this point if there is one... - if (_useLocalScope && CommandScope != null) + if (_useLocalScope && CommandScope is not null) { CommandSessionState.RemoveScope(CommandScope); } // and the previous scope... - if (_previousScope != null) + if (_previousScope is not null) { // Restore the scope but use the same session state instance we // got it from because the command may have changed the execution context @@ -660,7 +660,7 @@ internal void DoComplete() } // Restore the previous session state - if (_previousCommandSessionState != null) + if (_previousCommandSessionState is not null) { Context.EngineSessionState = _previousCommandSessionState; } @@ -672,7 +672,7 @@ internal void DoComplete() /// public override string ToString() { - if (CommandInfo != null) + if (CommandInfo is not null) return CommandInfo.ToString(); return ""; // does not require localization } @@ -769,12 +769,12 @@ internal PipelineStoppedException ManageInvocationException(Exception e) { try { - if (Command != null) + if (Command is not null) { do // false loop { ProviderInvocationException pie = e as ProviderInvocationException; - if (pie != null) + if (pie is not null) { // If a ProviderInvocationException occurred, // discard the ProviderInvocationException and @@ -802,7 +802,7 @@ internal PipelineStoppedException ManageInvocationException(Exception e) } RuntimeException rte = e as RuntimeException; - if (rte != null && rte.WasThrownFromThrowStatement) + if (rte is not null && rte.WasThrownFromThrowStatement) { // do not rewrap a script based throw break; @@ -825,7 +825,7 @@ internal PipelineStoppedException ManageInvocationException(Exception e) // exceedingly obtuse. We clarify things here. bool isTimeoutException = false; Exception tempException = e; - while (tempException != null) + while (tempException is not null) { if (tempException is System.TimeoutException) { @@ -890,7 +890,7 @@ internal PipelineStoppedException ManageInvocationException(Exception e) /// internal void ManageScriptException(RuntimeException e) { - if (Command != null && commandRuntime.PipelineProcessor != null) + if (Command is not null && commandRuntime.PipelineProcessor is not null) { commandRuntime.PipelineProcessor.RecordFailure(e, Command); @@ -909,7 +909,7 @@ internal void ManageScriptException(RuntimeException e) /// internal void ForgetScriptException() { - if (Command != null && commandRuntime.PipelineProcessor != null) + if (Command is not null && commandRuntime.PipelineProcessor is not null) { commandRuntime.PipelineProcessor.ForgetFailure(); } @@ -947,7 +947,7 @@ private void Dispose(bool disposing) // whether IDisposable is implemented, in order to avoid // this expensive reflection cast. IDisposable id = Command as IDisposable; - if (id != null) + if (id is not null) { id.Dispose(); } diff --git a/src/System.Management.Automation/engine/CommandSearcher.cs b/src/System.Management.Automation/engine/CommandSearcher.cs index 5bdc134adb0..eb98a04db48 100644 --- a/src/System.Management.Automation/engine/CommandSearcher.cs +++ b/src/System.Management.Automation/engine/CommandSearcher.cs @@ -48,7 +48,7 @@ internal CommandSearcher( CommandTypes commandTypes, ExecutionContext context) { - Diagnostics.Assert(context != null, "caller to verify context is not null"); + Diagnostics.Assert(context is not null, "caller to verify context is not null"); Diagnostics.Assert(!string.IsNullOrEmpty(commandName), "caller to verify commandName is valid"); _commandName = commandName; @@ -91,7 +91,7 @@ public bool MoveNext() _currentMatch = SearchForAliases(); // Why don't we check IsVisible on other scoped items? - if (_currentMatch != null && SessionState.IsVisible(_commandOrigin, _currentMatch)) + if (_currentMatch is not null && SessionState.IsVisible(_commandOrigin, _currentMatch)) { return true; } @@ -108,7 +108,7 @@ public bool MoveNext() _currentMatch = SearchForFunctions(); // Return the alias info only if it is visible. If not, then skip to the next // stage of command resolution... - if (_currentMatch != null) + if (_currentMatch is not null) { return true; } @@ -120,7 +120,7 @@ public bool MoveNext() if (_currentState == SearchState.SearchingCmdlets) { _currentMatch = SearchForCmdlets(); - if (_currentMatch != null) + if (_currentMatch is not null) { return true; } @@ -194,7 +194,7 @@ public bool MoveNext() _currentMatch = ProcessBuiltinScriptState(); - if (_currentMatch != null) + if (_currentMatch is not null) { // Set the current state to QualifiedFileSystemPath since // we want to skip the qualified file system path search @@ -211,7 +211,7 @@ public bool MoveNext() _currentMatch = ProcessPathResolutionState(); - if (_currentMatch != null) + if (_currentMatch is not null) { return true; } @@ -224,7 +224,7 @@ public bool MoveNext() { _currentMatch = ProcessQualifiedFileSystemState(); - if (_currentMatch != null) + if (_currentMatch is not null) { return true; } @@ -236,7 +236,7 @@ public bool MoveNext() _currentMatch = ProcessPathSearchState(); - if (_currentMatch != null) + if (_currentMatch is not null) { return true; } @@ -249,7 +249,7 @@ public bool MoveNext() { CommandInfo? currentMatch = null; - if (_context.EngineSessionState != null && + if (_context.EngineSessionState is not null && (_commandTypes & CommandTypes.Alias) != 0) { currentMatch = GetNextAlias(); @@ -262,7 +262,7 @@ public bool MoveNext() { CommandInfo? currentMatch = null; - if (_context.EngineSessionState != null && + if (_context.EngineSessionState is not null && (_commandTypes & (CommandTypes.Function | CommandTypes.Filter | CommandTypes.Configuration)) != 0) { currentMatch = GetNextFunction(); @@ -289,7 +289,7 @@ public bool MoveNext() // Check to see if the path is qualified - if (_context.EngineSessionState != null && + if (_context.EngineSessionState is not null && _context.EngineSessionState.ProviderCount > 0 && IsQualifiedPSPath(_commandName)) { @@ -364,7 +364,7 @@ public bool MoveNext() { try { - // the previous call to setupPathSearcher ensures _pathSearcher != null + // the previous call to setupPathSearcher ensures _pathSearcher is not null while (currentMatch is null && _pathSearcher!.MoveNext()) { currentMatch = GetInfoFromPath(((IEnumerator)_pathSearcher).Current); @@ -429,7 +429,7 @@ object IEnumerator.Current /// public void Dispose() { - if (_pathSearcher != null) + if (_pathSearcher is not null) { _pathSearcher.Dispose(); _pathSearcher = null; @@ -466,7 +466,7 @@ public void Dispose() { var path = GetNextLiteralPathThatExistsAndHandleExceptions(_commandName, out _); - if (path != null) + if (path is not null) { return GetInfoFromPath(path); } @@ -484,7 +484,7 @@ public void Dispose() { string? path = GetNextLiteralPathThatExistsAndHandleExceptions(_commandName, out _); - if (path != null) + if (path is not null) { return GetInfoFromPath(path); } @@ -714,7 +714,7 @@ private static bool checkPath(string path, string commandName) // Process alias from modules AliasInfo? c = GetAliasFromModules(_commandName); - if (c != null) + if (c is not null) { matchingAliases.Add(c); } @@ -749,7 +749,7 @@ private static bool checkPath(string path, string commandName) result = null; } - if (result != null) + if (result is not null) { CommandDiscovery.discoveryTracer.WriteLine( "Alias found: {0} {1}", @@ -801,7 +801,7 @@ private static bool checkPath(string path, string commandName) // Process functions from modules CommandInfo? cmdInfo = GetFunctionFromModules(_commandName); - if (cmdInfo != null) + if (cmdInfo is not null) { matchingFunction.Add(cmdInfo); } @@ -864,7 +864,7 @@ private bool ShouldSkipCommandResolutionForConstrainedLanguage(CommandInfo? resu if ((result is FunctionInfo) && (executionContext.LanguageMode == PSLanguageMode.ConstrainedLanguage) && (result.DefiningLanguageMode == PSLanguageMode.FullLanguage) && - (executionContext.Debugger != null) && + (executionContext.Debugger is not null) && (executionContext.Debugger.InBreakpoint) && (!(executionContext.TopLevelSessionState.GetFunctionTableAtScope("GLOBAL").ContainsKey(result.Name)))) { @@ -882,7 +882,7 @@ private bool ShouldSkipCommandResolutionForConstrainedLanguage(CommandInfo? resu { // See if it's a module qualified alias... PSSnapinQualifiedName? qualifiedName = PSSnapinQualifiedName.GetInstance(command); - if (qualifiedName != null && !string.IsNullOrEmpty(qualifiedName.PSSnapInName)) + if (qualifiedName is not null && !string.IsNullOrEmpty(qualifiedName.PSSnapInName)) { PSModuleInfo? module = GetImportedModuleByName(qualifiedName.PSSnapInName); @@ -901,7 +901,7 @@ private bool ShouldSkipCommandResolutionForConstrainedLanguage(CommandInfo? resu { // See if it's a module qualified function call... PSSnapinQualifiedName? qualifiedName = PSSnapinQualifiedName.GetInstance(command); - if (qualifiedName != null && !string.IsNullOrEmpty(qualifiedName.PSSnapInName)) + if (qualifiedName is not null && !string.IsNullOrEmpty(qualifiedName.PSSnapInName)) { PSModuleInfo? module = GetImportedModuleByName(qualifiedName.PSSnapInName); @@ -917,7 +917,7 @@ private bool ShouldSkipCommandResolutionForConstrainedLanguage(CommandInfo? resu PSModuleInfo? module = null; List modules = _context.Modules.GetModules(new string[] { moduleName }, false); - if (modules != null && modules.Count > 0) + if (modules is not null && modules.Count > 0) { foreach (PSModuleInfo m in modules) { @@ -951,7 +951,7 @@ private bool ShouldSkipCommandResolutionForConstrainedLanguage(CommandInfo? resu { CommandInfo? result = _context.EngineSessionState.GetFunction(function); - if (result != null) + if (result is not null) { if (result is FilterInfo) { @@ -1011,7 +1011,7 @@ private bool ShouldSkipCommandResolutionForConstrainedLanguage(CommandInfo? resu string? moduleName = PSSnapinQualifiedCommandName?.PSSnapInName; var cmdletShortName = PSSnapinQualifiedCommandName?.ShortName; - WildcardPattern? cmdletMatcher = cmdletShortName != null + WildcardPattern? cmdletMatcher = cmdletShortName is not null ? WildcardPattern.Get(cmdletShortName, WildcardOptions.IgnoreCase) : null; @@ -1021,7 +1021,7 @@ private bool ShouldSkipCommandResolutionForConstrainedLanguage(CommandInfo? resu { foreach (CmdletInfo cmdlet in cmdletList) { - if (cmdletMatcher != null && + if (cmdletMatcher is not null && cmdletMatcher.IsMatch(cmdlet.Name) || (_commandResolutionOptions.HasFlag(SearchResolutionOptions.FuzzyMatch) && FuzzyMatcher.IsFuzzyMatch(cmdlet.Name, _commandName))) @@ -1071,7 +1071,7 @@ private bool ShouldSkipCommandResolutionForConstrainedLanguage(CommandInfo? resu [return: NotNullIfNotNull("result")] private static CmdletInfo? traceResult(CmdletInfo? result) { - if (result != null) + if (result is not null) { CommandDiscovery.discoveryTracer.WriteLine( "Cmdlet found: {0} {1}", @@ -1086,7 +1086,7 @@ private bool ShouldSkipCommandResolutionForConstrainedLanguage(CommandInfo? resu { string? result = null; - if (_context.EngineSessionState != null && + if (_context.EngineSessionState is not null && _context.EngineSessionState.ProviderCount > 0) { // NTRAID#Windows OS Bugs-1009294-2004/02/04-JeffJon @@ -1178,7 +1178,7 @@ private bool ShouldSkipCommandResolutionForConstrainedLanguage(CommandInfo? resu } // Verify the path was resolved to a file system path - if (provider != null && provider.NameEquals(_context.ProviderNames.FileSystem)) + if (provider is not null && provider.NameEquals(_context.ProviderNames.FileSystem)) { result = resolvedPath; @@ -1512,7 +1512,7 @@ private static CanDoPathLookupResult CanDoPathLookup(string possiblePath) private void setupPathSearcher() { // If it's already set up, just return... - if (_pathSearcher != null) + if (_pathSearcher is not null) { return; } diff --git a/src/System.Management.Automation/engine/CommonCommandParameters.cs b/src/System.Management.Automation/engine/CommonCommandParameters.cs index 7cb0a4bb3b4..db140460784 100644 --- a/src/System.Management.Automation/engine/CommonCommandParameters.cs +++ b/src/System.Management.Automation/engine/CommonCommandParameters.cs @@ -241,7 +241,7 @@ internal class ValidateVariableName : ValidateArgumentsAttribute protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics) { string varName = arguments as string; - if (varName != null) + if (varName is not null) { if (varName.StartsWith('+')) { diff --git a/src/System.Management.Automation/engine/CompiledCommandParameter.cs b/src/System.Management.Automation/engine/CompiledCommandParameter.cs index cbbe8856f33..0ed913f1de7 100644 --- a/src/System.Management.Automation/engine/CompiledCommandParameter.cs +++ b/src/System.Management.Automation/engine/CompiledCommandParameter.cs @@ -131,14 +131,14 @@ internal CompiledCommandParameter(MemberInfo member, bool processingDynamicParam this.IsDynamic = processingDynamicParameters; var propertyInfo = member as PropertyInfo; - if (propertyInfo != null) + if (propertyInfo is not null) { this.Type = propertyInfo.PropertyType; } else { var fieldInfo = member as FieldInfo; - if (fieldInfo != null) + if (fieldInfo is not null) { this.Type = fieldInfo.FieldType; } @@ -438,7 +438,7 @@ private void ProcessAttribute( } ValidateArgumentsAttribute validateAttr = attribute as ValidateArgumentsAttribute; - if (validateAttr != null) + if (validateAttr is not null) { if (validationAttributes is null) validationAttributes = new Collection(); @@ -452,7 +452,7 @@ private void ProcessAttribute( } AliasAttribute aliasAttr = attribute as AliasAttribute; - if (aliasAttr != null) + if (aliasAttr is not null) { if (aliases is null) { @@ -471,7 +471,7 @@ private void ProcessAttribute( } ArgumentTransformationAttribute argumentAttr = attribute as ArgumentTransformationAttribute; - if (argumentAttr != null) + if (argumentAttr is not null) { if (argTransformationAttributes is null) argTransformationAttributes = new Collection(); @@ -480,35 +480,35 @@ private void ProcessAttribute( } AllowNullAttribute allowNullAttribute = attribute as AllowNullAttribute; - if (allowNullAttribute != null) + if (allowNullAttribute is not null) { this.AllowsNullArgument = true; return; } AllowEmptyStringAttribute allowEmptyStringAttribute = attribute as AllowEmptyStringAttribute; - if (allowEmptyStringAttribute != null) + if (allowEmptyStringAttribute is not null) { this.AllowsEmptyStringArgument = true; return; } AllowEmptyCollectionAttribute allowEmptyCollectionAttribute = attribute as AllowEmptyCollectionAttribute; - if (allowEmptyCollectionAttribute != null) + if (allowEmptyCollectionAttribute is not null) { this.AllowsEmptyCollectionArgument = true; return; } ObsoleteAttribute obsoleteAttr = attribute as ObsoleteAttribute; - if (obsoleteAttr != null) + if (obsoleteAttr is not null) { ObsoleteAttribute = obsoleteAttr; return; } PSTypeNameAttribute psTypeNameAttribute = attribute as PSTypeNameAttribute; - if (psTypeNameAttribute != null) + if (psTypeNameAttribute is not null) { this.PSTypeName = psTypeNameAttribute.PSTypeName; } @@ -596,7 +596,7 @@ internal class ParameterCollectionTypeInformation internal ParameterCollectionTypeInformation(Type type) { ParameterCollectionType = ParameterCollectionType.NotCollection; - Diagnostics.Assert(type != null, "Caller to verify type argument"); + Diagnostics.Assert(type is not null, "Caller to verify type argument"); // NTRAID#Windows OS Bugs-1009284-2004/05/11-JeffJon // What other collection types should be supported? @@ -625,7 +625,7 @@ internal ParameterCollectionTypeInformation(Type type) return; } - bool implementsIList = (type.GetInterface(typeof(IList).Name) != null); + bool implementsIList = (type.GetInterface(typeof(IList).Name) is not null); // Look for class Collection. Collection implements IList, and also IList // is more efficient to bind than ICollection. This optimization @@ -650,7 +650,7 @@ internal ParameterCollectionTypeInformation(Type type) // but the advantage over plain IList is that we can typecast the elements. Type interfaceICollection = Array.Find(interfaces, i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(ICollection<>)); - if (interfaceICollection != null) + if (interfaceICollection is not null) { // We only deal with the first type for which ICollection is implemented ParameterCollectionType = ParameterCollectionType.ICollectionGeneric; diff --git a/src/System.Management.Automation/engine/ContentCmdletProviderInterfaces.cs b/src/System.Management.Automation/engine/ContentCmdletProviderInterfaces.cs index 11d9e1d2e78..6e56b49a2fc 100644 --- a/src/System.Management.Automation/engine/ContentCmdletProviderInterfaces.cs +++ b/src/System.Management.Automation/engine/ContentCmdletProviderInterfaces.cs @@ -103,7 +103,7 @@ internal ContentCmdletProviderIntrinsics(SessionStateInternal sessionState) public Collection GetReader(string path) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -149,7 +149,7 @@ public Collection GetReader(string path) public Collection GetReader(string[] path, bool force, bool literalPath) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -190,7 +190,7 @@ internal Collection GetReader( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -233,7 +233,7 @@ internal object GetContentReaderDynamicParameters( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -277,7 +277,7 @@ internal object GetContentReaderDynamicParameters( public Collection GetWriter(string path) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -323,7 +323,7 @@ public Collection GetWriter(string path) public Collection GetWriter(string[] path, bool force, bool literalPath) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -364,7 +364,7 @@ internal Collection GetWriter( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -407,7 +407,7 @@ internal object GetContentWriterDynamicParameters( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -448,7 +448,7 @@ internal object GetContentWriterDynamicParameters( public void Clear(string path) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -491,7 +491,7 @@ public void Clear(string path) public void Clear(string[] path, bool force, bool literalPath) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -531,7 +531,7 @@ public void Clear(string[] path, bool force, bool literalPath) internal void Clear(string path, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -572,7 +572,7 @@ internal void Clear(string path, CmdletProviderContext context) internal object ClearContentDynamicParameters(string path, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object diff --git a/src/System.Management.Automation/engine/CoreAdapter.cs b/src/System.Management.Automation/engine/CoreAdapter.cs index 9ecbb7806b9..6f880fb9ad0 100644 --- a/src/System.Management.Automation/engine/CoreAdapter.cs +++ b/src/System.Management.Automation/engine/CoreAdapter.cs @@ -50,7 +50,7 @@ internal abstract class Adapter protected static IEnumerable GetDotNetTypeNameHierarchy(Type type) { - for (; type != null; type = type.BaseType) + for (; type is not null; type = type.BaseType) { yield return type.FullName; } @@ -350,7 +350,7 @@ private static Exception NewException( } Exception ex = e as TargetInvocationException; - if (ex != null) + if (ex is not null) { Exception inner = ex.InnerException ?? ex; newParameters[0] = inner.Message; @@ -991,16 +991,16 @@ private static int CompareOverloadCandidates(OverloadCandidate candidate1, Overl } // Apply tie breaking rules, related to expanded parameters - if (candidate1.expandedParameters != null && candidate2.expandedParameters != null) + if (candidate1.expandedParameters is not null && candidate2.expandedParameters is not null) { // Both are using expanded parameters. The one with more parameters is better return (candidate1.parameters.Length > candidate2.parameters.Length) ? 1 : -1; } - else if (candidate1.expandedParameters != null) + else if (candidate1.expandedParameters is not null) { return -1; } - else if (candidate2.expandedParameters != null) + else if (candidate2.expandedParameters is not null) { return 1; } @@ -1028,7 +1028,7 @@ private static int CompareOverloadCandidates(OverloadCandidate candidate1, Overl private static OverloadCandidate FindBestCandidate(List candidates, object[] arguments) { - Dbg.Assert(candidates != null, "Caller should verify candidates != null"); + Dbg.Assert(candidates is not null, "Caller should verify candidates is not null"); OverloadCandidate bestCandidateSoFar = null; bool multipleBestCandidates = false; @@ -1167,7 +1167,7 @@ private static MethodBase GetGenericMethodDefinitionIfPossible(MethodBase method if (method.IsGenericMethod && !method.IsGenericMethodDefinition) { MethodInfo methodInfo = method as MethodInfo; - if (methodInfo != null) + if (methodInfo is not null) { return methodInfo.GetGenericMethodDefinition(); } @@ -1194,7 +1194,7 @@ internal OverloadCandidate(MethodInformation method, int argCount) private static bool IsInvocationTargetConstraintSatisfied(MethodInformation method, PSMethodInvocationConstraints invocationConstraints) { - Dbg.Assert(method != null, "Caller should verify method != null"); + Dbg.Assert(method is not null, "Caller should verify method is not null"); if (method.method is null) { @@ -1281,19 +1281,19 @@ private static bool IsInvocationTargetConstraintSatisfied(MethodInformation meth private static bool IsInvocationConstraintSatisfied(OverloadCandidate overloadCandidate, PSMethodInvocationConstraints invocationConstraints) { - Dbg.Assert(overloadCandidate != null, "Caller should verify overloadCandidate != null"); + Dbg.Assert(overloadCandidate is not null, "Caller should verify overloadCandidate is not null"); if (invocationConstraints is null) { return true; } - if (invocationConstraints.ParameterTypes != null) + if (invocationConstraints.ParameterTypes is not null) { int parameterIndex = 0; foreach (Type parameterTypeConstraint in invocationConstraints.ParameterTypes) { - if (parameterTypeConstraint != null) + if (parameterTypeConstraint is not null) { if (parameterIndex >= overloadCandidate.parameters.Length) { @@ -1355,10 +1355,10 @@ internal static MethodInformation FindBestMethod( // } // // If we have such information in invocationConstraints then we should call method on the baseClass. - if (invocationConstraints != null && - invocationConstraints.MethodTargetType != null && - methodInfo.method != null && - methodInfo.method.DeclaringType != null) + if (invocationConstraints is not null && + invocationConstraints.MethodTargetType is not null && + methodInfo.method is not null && + methodInfo.method.DeclaringType is not null) { Type targetType = methodInfo.method.DeclaringType; if (targetType != invocationConstraints.MethodTargetType && targetType.IsSubclassOf(invocationConstraints.MethodTargetType)) @@ -1366,7 +1366,7 @@ internal static MethodInformation FindBestMethod( var parameterTypes = methodInfo.method.GetParameters().Select(parameter => parameter.ParameterType).ToArray(); var targetTypeMethod = invocationConstraints.MethodTargetType.GetMethod(methodInfo.method.Name, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, parameterTypes, null); - if (targetTypeMethod != null && (targetTypeMethod.IsPublic || targetTypeMethod.IsFamily || targetTypeMethod.IsFamilyOrAssembly)) + if (targetTypeMethod is not null && (targetTypeMethod.IsPublic || targetTypeMethod.IsFamily || targetTypeMethod.IsFamilyOrAssembly)) { methodInfo = new MethodInformation(targetTypeMethod, 0); callNonVirtually = true; @@ -1410,7 +1410,7 @@ private static MethodInformation FindBestMethodImpl( { MethodInformation method = methods[i]; - if (method.method != null && method.method.DeclaringType.IsGenericTypeDefinition) + if (method.method is not null && method.method.DeclaringType.IsGenericTypeDefinition) { continue; // skip methods defined by an *open* generic type } @@ -1419,12 +1419,12 @@ private static MethodInformation FindBestMethodImpl( { Type[] argumentTypesForTypeInference = new Type[argumentTypes.Length]; Array.Copy(argumentTypes, argumentTypesForTypeInference, argumentTypes.Length); - if (invocationConstraints != null && invocationConstraints.ParameterTypes != null) + if (invocationConstraints is not null && invocationConstraints.ParameterTypes is not null) { int parameterIndex = 0; foreach (Type typeConstraintFromCallSite in invocationConstraints.ParameterTypes) { - if (typeConstraintFromCallSite != null) + if (typeConstraintFromCallSite is not null) { argumentTypesForTypeInference[parameterIndex] = typeConstraintFromCallSite; } @@ -1491,7 +1491,7 @@ private static MethodInformation FindBestMethodImpl( } OverloadCandidate candidate = new OverloadCandidate(method, arguments.Length); - for (int j = 0; candidate != null && j < parameters.Length; j++) + for (int j = 0; candidate is not null && j < parameters.Length; j++) { ParameterInformation parameter = parameters[j]; if (parameter.isOptional && arguments.Length <= j) @@ -1551,7 +1551,7 @@ private static MethodInformation FindBestMethodImpl( } } - if (candidate != null) + if (candidate is not null) { candidate.expandedParameters = ExpandParameters(arguments.Length, parameters, elementType); } @@ -1573,7 +1573,7 @@ private static MethodInformation FindBestMethodImpl( } } - if (candidate != null) + if (candidate is not null) { candidates.Add(candidate); } @@ -1581,7 +1581,7 @@ private static MethodInformation FindBestMethodImpl( if (candidates.Count == 0) { - if ((methods.Length > 0) && (methods.All(m => m.method != null && m.method.DeclaringType.IsGenericTypeDefinition && m.method.IsStatic))) + if ((methods.Length > 0) && (methods.All(m => m.method is not null && m.method.DeclaringType.IsGenericTypeDefinition && m.method.IsStatic))) { errorId = "CannotInvokeStaticMethodOnUninstantiatedGenericType"; errorMsg = string.Format( @@ -1601,9 +1601,9 @@ private static MethodInformation FindBestMethodImpl( OverloadCandidate bestCandidate = candidates.Count == 1 ? candidates[0] : FindBestCandidate(candidates, arguments, invocationConstraints); - if (bestCandidate != null) + if (bestCandidate is not null) { - expandParamsOnBest = bestCandidate.expandedParameters != null; + expandParamsOnBest = bestCandidate.expandedParameters is not null; return bestCandidate.method; } @@ -1614,11 +1614,11 @@ private static MethodInformation FindBestMethodImpl( internal static Type EffectiveArgumentType(object arg) { - if (arg != null) + if (arg is not null) { arg = PSObject.Base(arg); object[] argAsArray = arg as object[]; - if (argAsArray != null && argAsArray.Length > 0 && PSObject.Base(argAsArray[0]) != null) + if (argAsArray is not null && argAsArray.Length > 0 && PSObject.Base(argAsArray[0]) is not null) { Type firstType = PSObject.Base(argAsArray[0]).GetType(); bool allSameType = true; @@ -1881,7 +1881,7 @@ internal static object UnReference(object obj, out bool isArgumentByRef) { isArgumentByRef = false; PSReference reference = obj as PSReference; - if (reference != null) + if (reference is not null) { PSObject.MemberResolution.WriteLine("Parameter was a reference."); isArgumentByRef = true; @@ -1889,12 +1889,12 @@ internal static object UnReference(object obj, out bool isArgumentByRef) } PSObject mshObj = obj as PSObject; - if (mshObj != null) + if (mshObj is not null) { reference = mshObj.BaseObject as PSReference; } - if (reference != null) + if (reference is not null) { PSObject.MemberResolution.WriteLine("Parameter was an PSObject containing a reference."); isArgumentByRef = true; @@ -1915,7 +1915,7 @@ internal static object PropertySetAndMethodArgumentConvertTo(object valueToConve } PSObject mshObj = valueToConvert as PSObject; - if (mshObj != null) + if (mshObj is not null) { if (resultType == typeof(object)) { @@ -2143,7 +2143,7 @@ internal MethodInformation(MethodBase method, int parametersToIgnore) // This inconsistent behavior affects OneCore powershell because we are using the extension method here when compiling // against CoreCLR. So we need to add a null check until this is fixed in CLR. var paramArrayAttrs = lastParameter.GetCustomAttributes(typeof(ParamArrayAttribute), false); - if (paramArrayAttrs != null && paramArrayAttrs.Length > 0) + if (paramArrayAttrs is not null && paramArrayAttrs.Length > 0) { this.hasVarArgs = true; this.parameters[parametersLength - 1].isParamArray = true; @@ -2208,7 +2208,7 @@ internal object Invoke(object target, object[] arguments) _methodInvoker = GetMethodInvoker(methodInfo); } - if (_methodInvoker != null) + if (_methodInvoker is not null) { return _methodInvoker(target, arguments); } @@ -2268,7 +2268,7 @@ private static Type FindInterfaceForMethod(MethodInfo method, out MethodInfo met { Type type = interfaces[i]; MethodInfo methodInfo = type.GetMethod(method.Name, BindingFlags.Instance); - if (methodInfo != null && CompareMethodParameters(methodInfo, method)) + if (methodInfo is not null && CompareMethodParameters(methodInfo, method)) { methodToCall = methodInfo; return type; @@ -2700,7 +2700,7 @@ internal ParameterizedPropertyCacheEntry(List properties) MethodInfo propertyGetter = property.GetGetMethod(); StringBuilder definition = new StringBuilder(); StringBuilder extraDefinition = new StringBuilder(); - if (propertyGetter != null) + if (propertyGetter is not null) { extraDefinition.Append("get;"); definition.Append(DotNetAdapter.GetMethodInfoOverloadDefinition(this.propertyName, propertyGetter, 0)); @@ -2709,7 +2709,7 @@ internal ParameterizedPropertyCacheEntry(List properties) // Get the public setter MethodInfo propertySetter = property.GetSetMethod(); - if (propertySetter != null) + if (propertySetter is not null) { extraDefinition.Append("set;"); if (definition.Length == 0) @@ -2773,7 +2773,7 @@ internal PropertyCacheEntry(PropertyInfo property) // Get the public or protected getter MethodInfo propertyGetter = property.GetGetMethod(true); - if (propertyGetter != null && (propertyGetter.IsPublic || propertyGetter.IsFamily)) + if (propertyGetter is not null && (propertyGetter.IsPublic || propertyGetter.IsFamily)) { this.isStatic = propertyGetter.IsStatic; // Delegate is initialized later to avoid jit if it's not called @@ -2785,7 +2785,7 @@ internal PropertyCacheEntry(PropertyInfo property) // Get the public or protected setter MethodInfo propertySetter = property.GetSetMethod(true); - if (propertySetter != null && (propertySetter.IsPublic || propertySetter.IsFamily)) + if (propertySetter is not null && (propertySetter.IsPublic || propertySetter.IsFamily)) { this.isStatic = propertySetter.IsStatic; } @@ -2821,7 +2821,7 @@ private void InitGetter() Expression instance = null; var field = member as FieldInfo; - if (field != null) + if (field is not null) { var declaringType = field.DeclaringType; if (!field.IsStatic) @@ -2830,7 +2830,7 @@ private void InitGetter() { // I'm not sure we can get here with a Nullable, but if so, // we must use the Value property, see PSGetMemberBinder.GetTargetValue. - instance = Nullable.GetUnderlyingType(declaringType) != null + instance = Nullable.GetUnderlyingType(declaringType) is not null ? (Expression)Expression.Property(parameter, "Value") : Expression.Unbox(parameter, declaringType); } @@ -2882,7 +2882,7 @@ private void InitSetter() Expression instance = null; var field = member as FieldInfo; - if (field != null) + if (field is not null) { var declaringType = field.DeclaringType; if (!field.IsStatic) @@ -2891,7 +2891,7 @@ private void InitSetter() { // I'm not sure we can get here with a Nullable, but if so, // we must use the Value property, see PSGetMemberBinder.GetTargetValue. - instance = Nullable.GetUnderlyingType(declaringType) != null + instance = Nullable.GetUnderlyingType(declaringType) is not null ? (Expression)Expression.Property(parameter, "Value") : Expression.Unbox(parameter, declaringType); } @@ -2917,7 +2917,7 @@ private void InitSetter() errMessage = ParserStrings.PropertyIsReadOnly; } - if (errMessage != null) + if (errMessage is not null) { Expression innerException = Expression.New(CachedReflectionInfo.SetValueException_ctor, Expression.Constant("PropertyAssignmentException"), @@ -3094,7 +3094,7 @@ private static void PopulateMethodReflectionTable(Type type, MethodInfo[] method } } - if (type.BaseType != null) + if (type.BaseType is not null) { PopulateMethodReflectionTable(type.BaseType, methods, typeMethods); } @@ -3137,7 +3137,7 @@ private static void PopulateMethodReflectionTable(Type type, CacheTable typeMeth } // In CoreCLR, "GetFirstPublicParentType" may return null if 'type' is an interface - if (typeToGetMethod != null) + if (typeToGetMethod is not null) { MethodInfo[] methods = typeToGetMethod.GetMethods(bindingFlags); PopulateMethodReflectionTable(typeToGetMethod, methods, typeMethods); @@ -3232,7 +3232,7 @@ private static void PopulateEventReflectionTable(Type type, Dictionary>(StringComparer.OrdinalIgnoreCase); @@ -3320,7 +3320,7 @@ private static void PopulatePropertyReflectionTable(Type type, CacheTable typePr // In CoreCLR, "GetFirstPublicParentType" may return null if 'type' is an interface PropertyInfo[] properties; - if (typeToGetPropertyAndField != null) + if (typeToGetPropertyAndField is not null) { properties = typeToGetPropertyAndField.GetProperties(bindingFlags); for (int i = 0; i < properties.Length; i++) @@ -3360,7 +3360,7 @@ private static void PopulatePropertyReflectionTable(Type type, CacheTable typePr } // In CoreCLR, "GetFirstPublicParentType" may return null if 'type' is an interface - if (typeToGetPropertyAndField != null) + if (typeToGetPropertyAndField is not null) { FieldInfo[] fields = typeToGetPropertyAndField.GetFields(bindingFlags); for (int i = 0; i < fields.Length; i++) @@ -3433,7 +3433,7 @@ internal static bool DisallowPrivateReflection(Type type) } var productAttribute = assembly.GetCustomAttribute(); - if (productAttribute != null && string.Equals(productAttribute.Product, "Microsoft® .NET Framework", StringComparison.OrdinalIgnoreCase)) + if (productAttribute is not null && string.Equals(productAttribute.Product, "Microsoft® .NET Framework", StringComparison.OrdinalIgnoreCase)) { disallowReflection = true; } @@ -3441,7 +3441,7 @@ internal static bool DisallowPrivateReflection(Type type) { // Check for 'DisablePrivateReflectionAttribute'. It's applied at the assembly level, and allow an assembly to opt-out of private/internal reflection. var disablePrivateReflectionAttribute = assembly.GetCustomAttribute(); - disallowReflection = disablePrivateReflectionAttribute != null; + disallowReflection = disablePrivateReflectionAttribute is not null; } s_disallowReflectionCache.TryAdd(assembly.FullName, disallowReflection); @@ -3455,7 +3455,7 @@ internal static Type GetFirstPublicParentType(Type type) { Dbg.Assert(!TypeResolver.IsPublic(type), "type should not be public."); Type parent = type.BaseType; - while (parent != null) + while (parent is not null) { if (parent.IsPublic) { @@ -3588,7 +3588,7 @@ internal IEnumerable GetPropertiesAndMethods(Type type, bool @static) for (int i = 0; i < propertyTable.memberCollection.Count; i++) { var propertyCacheEntry = propertyTable.memberCollection[i] as PropertyCacheEntry; - if (propertyCacheEntry != null) + if (propertyCacheEntry is not null) yield return propertyCacheEntry.member; } @@ -3598,7 +3598,7 @@ internal IEnumerable GetPropertiesAndMethods(Type type, bool @static) for (int i = 0; i < methodTable.memberCollection.Count; i++) { var method = methodTable.memberCollection[i] as MethodCacheEntry; - if (method != null && !method[0].method.IsSpecialName) + if (method is not null && !method[0].method.IsSpecialName) { yield return method; } @@ -3655,7 +3655,7 @@ private T GetDotNetPropertyImpl(object obj, string propertyName, MemberNamePr ? GetStaticPropertyReflectionTable((Type)obj) : GetInstancePropertyReflectionTable(obj.GetType()); - object entry = predicate != null + object entry = predicate is not null ? typeTable.GetFirstOrDefault(predicate) : typeTable[propertyName]; switch (entry) @@ -3685,7 +3685,7 @@ private T GetDotNetMethodImpl(object obj, string methodName, MemberNamePredic ? GetStaticMethodReflectionTable((Type)obj) : GetInstanceMethodReflectionTable(obj.GetType()); - var methods = predicate != null + var methods = predicate is not null ? (MethodCacheEntry)typeTable.GetFirstOrDefault(predicate) : (MethodCacheEntry)typeTable[methodName]; @@ -3926,7 +3926,7 @@ protected override ConsolidatedString GetInternedTypeNameHierarchy(object obj) protected override T GetMember(object obj, string memberName) { T returnValue = GetDotNetProperty(obj, memberName); - if (returnValue != null) return returnValue; + if (returnValue is not null) return returnValue; return GetDotNetMethod(obj, memberName); } @@ -4032,7 +4032,7 @@ protected override object PropertyGet(PSProperty property) } PropertyInfo propertyInfo = adapterData.member as PropertyInfo; - if (propertyInfo != null) + if (propertyInfo is not null) { if (adapterData.writeOnly) { @@ -4094,7 +4094,7 @@ protected override void PropertySet(PSProperty property, object setValue, bool c } PropertyInfo propertyInfo = adapterData.member as PropertyInfo; - if (propertyInfo != null) + if (propertyInfo is not null) { if (convertIfPossible) { @@ -4275,7 +4275,7 @@ internal static object AuxiliaryMethodInvoke(object target, object[] arguments, SetReferences(arguments, methodInformation, originalArguments); MethodInfo methodInfo = methodInformation.method as MethodInfo; - if (methodInfo != null && methodInfo.ReturnType != typeof(void)) + if (methodInfo is not null && methodInfo.ReturnType != typeof(void)) return result; return AutomationNull.Value; } @@ -4412,7 +4412,7 @@ internal static string GetMethodInfoOverloadDefinition(string memberName, Method } MethodInfo method = methodEntry as MethodInfo; - if (method != null) + if (method is not null) { builder.Append(ToStringCodeMethods.Type(method.ReturnType)); builder.Append(" "); @@ -4420,7 +4420,7 @@ internal static string GetMethodInfoOverloadDefinition(string memberName, Method else { ConstructorInfo ctorInfo = methodEntry as ConstructorInfo; - if (ctorInfo != null) + if (ctorInfo is not null) { builder.Append(ToStringCodeMethods.Type(ctorInfo.DeclaringType)); builder.Append(" "); @@ -4473,7 +4473,7 @@ internal static string GetMethodInfoOverloadDefinition(string memberName, Method // This inconsistent behavior affects OneCore powershell because we are using the extension method here when compiling // against CoreCLR. So we need to add a null check until this is fixed in CLR. var paramArrayAttrs = parameter.GetCustomAttributes(typeof(ParamArrayAttribute), false); - if (paramArrayAttrs != null && paramArrayAttrs.Length > 0) + if (paramArrayAttrs is not null && paramArrayAttrs.Length > 0) builder.Append("Params "); } @@ -4671,7 +4671,7 @@ protected override PSMemberInfoInternalCollection GetMembers(object obj) protected override T GetMember(object obj, string memberName) { PSProperty property = base.GetDotNetProperty(obj, memberName); - if (typeof(T).IsAssignableFrom(typeof(PSProperty)) && (property != null)) + if (typeof(T).IsAssignableFrom(typeof(PSProperty)) && (property is not null)) { return property as T; } @@ -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 is not null && property is 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 is not null && property is null) { return parameterizedProperty as T; } @@ -4712,7 +4712,7 @@ protected override T GetMember(object obj, string memberName) protected override T GetFirstMemberOrDefault(object obj, MemberNamePredicate predicate) { PSProperty property = base.GetFirstDotNetPropertyOrDefault(obj, predicate); - if (typeof(T).IsAssignableFrom(typeof(PSProperty)) && property != null) + if (typeof(T).IsAssignableFrom(typeof(PSProperty)) && property is not null) { return property 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 is not null && property is 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 is not null && property is null) { return parameterizedProperty as T; } @@ -4765,7 +4765,7 @@ internal DotNetAdapterWithComTypeName(ComTypeInfo comTypeInfo) protected override IEnumerable GetTypeNameHierarchy(object obj) { - for (Type type = obj.GetType(); type != null; type = type.BaseType) + for (Type type = obj.GetType(); type is not null; type = type.BaseType) { if (type.FullName.Equals("System.__ComObject")) { @@ -4957,7 +4957,7 @@ protected override PSMemberInfoInternalCollection GetMembers(object obj) foreach (PSMemberInfo member in mshObj.Members) { T memberAsT = member as T; - if (memberAsT != null) + if (memberAsT is not null) { returnValue.Add(memberAsT); } @@ -5032,7 +5032,7 @@ protected override PSMemberInfoInternalCollection GetMembers(object obj) foreach (PSMemberInfo member in ((PSMemberSet)obj).Members) { T memberAsT = member as T; - if (memberAsT != null) + if (memberAsT is not null) { returnValue.Add(memberAsT); } @@ -5110,7 +5110,7 @@ protected override T GetMember(object obj, string memberName) { PSProperty property = DoGetProperty(obj, memberName); - if (typeof(T).IsAssignableFrom(typeof(PSProperty)) && property != null) + if (typeof(T).IsAssignableFrom(typeof(PSProperty)) && property is not null) { return property 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 is not null && property is 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 is not null && property is 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 is not null && property is 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 is not null && property is null) { return parameterizedProperty as T; } @@ -5279,7 +5279,7 @@ protected override void DoAddAllProperties(object obj, PSMemberInfoInternalCo Dictionary> nodeArrays = new Dictionary>(StringComparer.OrdinalIgnoreCase); - if (node.Attributes != null) + if (node.Attributes is not null) { foreach (XmlNode attribute in node.Attributes) { @@ -5294,7 +5294,7 @@ protected override void DoAddAllProperties(object obj, PSMemberInfoInternalCo } } - if (node.ChildNodes != null) + if (node.ChildNodes is not null) { foreach (XmlNode childNode in node.ChildNodes) { @@ -5371,7 +5371,7 @@ protected override bool PropertyIsSettable(PSProperty property) } XmlAttributeCollection nodeAttributes = node.Attributes; - if ((nodeAttributes != null) && (nodeAttributes.Count != 0)) + if ((nodeAttributes is not null) && (nodeAttributes.Count != 0)) { return false; } @@ -5403,7 +5403,7 @@ protected override bool PropertyIsGettable(PSProperty property) private static object GetNodeObject(XmlNode node) { XmlText text = node as XmlText; - if (text != null) + if (text is not null) { return text.InnerText; } @@ -5411,7 +5411,7 @@ private static object GetNodeObject(XmlNode node) XmlAttributeCollection nodeAttributes = node.Attributes; // A node with attributes should not be simplified - if ((nodeAttributes != null) && (nodeAttributes.Count != 0)) + if ((nodeAttributes is not null) && (nodeAttributes.Count != 0)) { return node; } @@ -5430,7 +5430,7 @@ private static object GetNodeObject(XmlNode node) } XmlAttribute attribute = node as XmlAttribute; - if (attribute != null) + if (attribute is not null) { return attribute.Value; } @@ -5482,7 +5482,7 @@ protected override void PropertySet(PSProperty property, object setValue, bool c XmlNode node = nodes[0]; XmlText text = node as XmlText; - if (text != null) + if (text is not null) { text.InnerText = valueString; return; @@ -5490,7 +5490,7 @@ protected override void PropertySet(PSProperty property, object setValue, bool c XmlAttributeCollection nodeAttributes = node.Attributes; // A node with attributes cannot be set - if ((nodeAttributes != null) && (nodeAttributes.Count != 0)) + if ((nodeAttributes is not null) && (nodeAttributes.Count != 0)) { throw new SetValueException("XmlNodeSetRestrictionsNodeWithAttributes", null, @@ -5512,7 +5512,7 @@ protected override void PropertySet(PSProperty property, object setValue, bool c } XmlAttribute attribute = node as XmlAttribute; - if (attribute != null) + if (attribute is not null) { attribute.Value = valueString; return; @@ -5559,7 +5559,7 @@ private static XmlNode[] FindNodes(object obj, string propertyName, StringCompar List retValue = new List(); XmlNode node = (XmlNode)obj; - if (node.Attributes != null) + if (node.Attributes is not null) { foreach (XmlNode attribute in node.Attributes) { @@ -5591,7 +5591,7 @@ private static XmlNode FindNode(object obj, MemberNamePredicate predicate) { var node = (XmlNode)obj; - if (node.Attributes != null) + if (node.Attributes is not null) { foreach (XmlNode attribute in node.Attributes) { @@ -5874,8 +5874,8 @@ internal class TypeInference internal static MethodInformation Infer(MethodInformation genericMethod, Type[] argumentTypes) { - Dbg.Assert(genericMethod != null, "Caller should verify that genericMethod != null"); - Dbg.Assert(argumentTypes != null, "Caller should verify that arguments != null"); + Dbg.Assert(genericMethod is not null, "Caller should verify that genericMethod is not null"); + Dbg.Assert(argumentTypes is not null, "Caller should verify that arguments is not null"); // the cast is safe, because // 1) only ConstructorInfo and MethodInfo derive from MethodBase @@ -5883,7 +5883,7 @@ internal static MethodInformation Infer(MethodInformation genericMethod, Type[] MethodInfo originalMethod = (MethodInfo)genericMethod.method; MethodInfo inferredMethod = TypeInference.Infer(originalMethod, argumentTypes, genericMethod.hasVarArgs); - if (inferredMethod != null) + if (inferredMethod is not null) { return new MethodInformation(inferredMethod, 0); } @@ -5895,8 +5895,8 @@ internal static MethodInformation Infer(MethodInformation genericMethod, Type[] private static MethodInfo Infer(MethodInfo genericMethod, Type[] typesOfMethodArguments, bool hasVarArgs) { - Dbg.Assert(genericMethod != null, "Caller should verify that genericMethod != null"); - Dbg.Assert(typesOfMethodArguments != null, "Caller should verify that arguments != null"); + Dbg.Assert(genericMethod is not null, "Caller should verify that genericMethod is not null"); + Dbg.Assert(typesOfMethodArguments is not null, "Caller should verify that arguments is not null"); if (!genericMethod.ContainsGenericParameters) { @@ -5934,10 +5934,10 @@ private static MethodInfo Infer(MethodInfo genericMethod, Type[] typesOfMethodAr private static MethodInfo Infer(MethodInfo genericMethod, ICollection typeParameters, IEnumerable typesOfMethodParameters, IEnumerable typesOfMethodArguments) { - Dbg.Assert(genericMethod != null, "Caller should verify that genericMethod != null"); - Dbg.Assert(typeParameters != null, "Caller should verify that typeParameters != null"); - Dbg.Assert(typesOfMethodParameters != null, "Caller should verify that typesOfMethodParameters != null"); - Dbg.Assert(typesOfMethodArguments != null, "Caller should verify that typesOfMethodArguments != null"); + Dbg.Assert(genericMethod is not null, "Caller should verify that genericMethod is not null"); + Dbg.Assert(typeParameters is not null, "Caller should verify that typeParameters is not null"); + Dbg.Assert(typesOfMethodParameters is not null, "Caller should verify that typesOfMethodParameters is not null"); + Dbg.Assert(typesOfMethodArguments is not null, "Caller should verify that typesOfMethodArguments is not null"); using (s_tracer.TraceScope("Inferring type parameters for the following method: {0}", genericMethod)) { @@ -5984,7 +5984,7 @@ private static MethodInfo Infer(MethodInfo genericMethod, ICollection type internal TypeInference(ICollection typeParameters) { #if DEBUG - Dbg.Assert(typeParameters != null, "Caller should verify that typeParameters != null"); + Dbg.Assert(typeParameters is not null, "Caller should verify that typeParameters is not null"); Dbg.Assert( typeParameters.All(t => t.IsGenericParameter), "Caller should verify that typeParameters are really generic type parameters"); @@ -6014,7 +6014,7 @@ internal TypeInference(ICollection typeParameters) internal Type GetInferredType(Type typeParameter) { #if DEBUG - Dbg.Assert(typeParameter != null, "Caller should verify typeParameter != null"); + Dbg.Assert(typeParameter is not null, "Caller should verify typeParameter is not null"); Dbg.Assert( _typeParametersOfTheMethod.Contains(typeParameter), "Caller should verify that typeParameter is actually a generic type parameter of the method"); @@ -6023,10 +6023,10 @@ internal Type GetInferredType(Type typeParameter) ICollection inferenceCandidates = _typeParameterIndexToSetOfInferenceCandidates[typeParameter.GenericParameterPosition]; - if ((inferenceCandidates != null) && (inferenceCandidates.Any(t => t == typeof(LanguagePrimitives.Null)))) + if ((inferenceCandidates is not null) && (inferenceCandidates.Any(t => t == typeof(LanguagePrimitives.Null)))) { Type firstValueType = inferenceCandidates.FirstOrDefault(t => t.IsValueType); - if (firstValueType != null) + if (firstValueType is not null) { s_tracer.WriteLine("Cannot reconcile null and {0} (a value type)", firstValueType); inferenceCandidates = null; @@ -6043,7 +6043,7 @@ internal Type GetInferredType(Type typeParameter) } } - if ((inferenceCandidates != null) && (inferenceCandidates.Count > 1)) + if ((inferenceCandidates is not null) && (inferenceCandidates.Count > 1)) { // "base class" assignability-wise (to account for interfaces) Type commonBaseClass = inferenceCandidates.FirstOrDefault( @@ -6053,7 +6053,7 @@ internal Type GetInferredType(Type typeParameter) otherCandidate == potentiallyCommonBaseClass || potentiallyCommonBaseClass.IsAssignableFrom(otherCandidate))); - if (commonBaseClass != null) + if (commonBaseClass is not null) { inferenceCandidates.Clear(); inferenceCandidates.Add(commonBaseClass); @@ -6213,7 +6213,7 @@ private bool UnifyConstructedType(Type parameterType, Type argumentType) } Type baseType = argumentType.BaseType; - while (baseType != null) + while (baseType is not null) { if (IsEqualGenericTypeDefinition(parameterType, baseType)) { diff --git a/src/System.Management.Automation/engine/Credential.cs b/src/System.Management.Automation/engine/Credential.cs index 8cb159fea5e..4274bb09157 100644 --- a/src/System.Management.Automation/engine/Credential.cs +++ b/src/System.Management.Automation/engine/Credential.cs @@ -119,11 +119,11 @@ public void GetObjectData(SerializationInfo info, StreamingContext context) // serialize the secure string string safePassword = string.Empty; - if (_password != null && _password.Length > 0) + if (_password is not null && _password.Length > 0) { byte[] key; byte[] iv; - if (s_delegate != null && s_delegate(context, out key, out iv)) + if (s_delegate is not null && s_delegate(context, out key, out iv)) { safePassword = SecureStringHelper.Encrypt(_password, key, iv).EncryptedData; } @@ -166,7 +166,7 @@ private PSCredential(SerializationInfo info, StreamingContext context) { byte[] key; byte[] iv; - if (s_delegate != null && s_delegate(context, out key, out iv)) + if (s_delegate is not null && s_delegate(context, out key, out iv)) { _password = SecureStringHelper.Decrypt(safePassword, key, iv); } @@ -221,11 +221,11 @@ public PSCredential(PSObject pso) if (pso is null) throw PSTraceSource.NewArgumentNullException(nameof(pso)); - if (pso.Properties["UserName"] != null) + if (pso.Properties["UserName"] is not null) { _userName = (string)pso.Properties["UserName"].Value; - if (pso.Properties["Password"] != null) + if (pso.Properties["Password"] is not null) _password = (SecureString)pso.Properties["Password"].Value; } } diff --git a/src/System.Management.Automation/engine/DataStoreAdapter.cs b/src/System.Management.Automation/engine/DataStoreAdapter.cs index 8c5eb927bb5..324a23a82b9 100644 --- a/src/System.Management.Automation/engine/DataStoreAdapter.cs +++ b/src/System.Management.Automation/engine/DataStoreAdapter.cs @@ -346,7 +346,7 @@ public PSDriveInfo( _root = root; Description = description; - if (credential != null) + if (credential is not null) { Credential = credential; } @@ -357,7 +357,7 @@ public PSDriveInfo( _currentWorkingDirectory = string.Empty; Dbg.Diagnostics.Assert( - _currentWorkingDirectory != null, + _currentWorkingDirectory is not null, "The currentWorkingDirectory cannot be null"); // Trace out the fields @@ -548,35 +548,35 @@ internal void Trace() s_tracer.WriteLine( "A drive was found:"); - if (Name != null) + if (Name is not null) { s_tracer.WriteLine( "\tName: {0}", Name); } - if (Provider != null) + if (Provider is not null) { s_tracer.WriteLine( "\tProvider: {0}", Provider); } - if (Root != null) + if (Root is not null) { s_tracer.WriteLine( "\tRoot: {0}", Root); } - if (CurrentLocation != null) + if (CurrentLocation is not null) { s_tracer.WriteLine( "\tCWD: {0}", CurrentLocation); } - if (Description != null) + if (Description is not null) { s_tracer.WriteLine( "\tDescription: {0}", @@ -695,7 +695,7 @@ public bool Equals(PSDriveInfo drive) if ((drive1Object is null) == (drive2Object is null)) { - if (drive1Object != null) + if (drive1Object is not null) { return drive1.Equals(drive2); } @@ -747,7 +747,7 @@ public bool Equals(PSDriveInfo drive) if (drive1Object is null) { - return (drive2Object != null); + return (drive2Object is not null); } else { diff --git a/src/System.Management.Automation/engine/DataStoreAdapterProvider.cs b/src/System.Management.Automation/engine/DataStoreAdapterProvider.cs index 751af63626a..9a2e1ff2ec0 100644 --- a/src/System.Management.Automation/engine/DataStoreAdapterProvider.cs +++ b/src/System.Management.Automation/engine/DataStoreAdapterProvider.cs @@ -78,7 +78,7 @@ string GetFullName(string name, string psSnapInName, string moduleName) return result; } - if (_fullName != null && ModuleName.Equals(_cachedModuleName, StringComparison.Ordinal)) + if (_fullName is not null && ModuleName.Equals(_cachedModuleName, StringComparison.Ordinal)) { return _fullName; } @@ -101,7 +101,7 @@ internal string PSSnapInName get { string result = null; - if (PSSnapIn != null) + if (PSSnapIn is not null) { result = PSSnapIn.Name; } @@ -135,9 +135,9 @@ public string ModuleName { get { - if (PSSnapIn != null) + if (PSSnapIn is not null) return PSSnapIn.Name; - if (Module != null) + if (Module is not null) return Module.Name; return string.Empty; } @@ -452,7 +452,7 @@ internal bool NameEquals(string providerName) PSSnapinQualifiedName qualifiedProviderName = PSSnapinQualifiedName.GetInstance(providerName); bool result = false; - if (qualifiedProviderName != null) + if (qualifiedProviderName is not null) { // If the pssnapin name and provider name are specified, then both must match do // false loop @@ -485,7 +485,7 @@ internal bool IsMatch(string providerName) WildcardPattern namePattern = null; - if (psSnapinQualifiedName != null && WildcardPattern.ContainsWildcardCharacters(psSnapinQualifiedName.ShortName)) + if (psSnapinQualifiedName is not null && WildcardPattern.ContainsWildcardCharacters(psSnapinQualifiedName.ShortName)) { namePattern = WildcardPattern.Get(psSnapinQualifiedName.ShortName, WildcardOptions.IgnoreCase); } @@ -602,7 +602,7 @@ internal Provider.CmdletProvider CreateInstance() { ProviderNotFoundException e = null; - if (invocationException != null) + if (invocationException is not null) { e = new ProviderNotFoundException( @@ -630,7 +630,7 @@ internal Provider.CmdletProvider CreateInstance() AltItemSeparator = result.AltItemSeparator; Dbg.Diagnostics.Assert( - result != null, + result is not null, "DiscoverProvider should verify that the class is derived from CmdletProvider so this is just validation of that"); result.SetProviderInformation(this); diff --git a/src/System.Management.Automation/engine/DefaultCommandRuntime.cs b/src/System.Management.Automation/engine/DefaultCommandRuntime.cs index 7402e32294b..1d1b39115d7 100644 --- a/src/System.Management.Automation/engine/DefaultCommandRuntime.cs +++ b/src/System.Management.Automation/engine/DefaultCommandRuntime.cs @@ -46,7 +46,7 @@ public void WriteDebug(string text) { } /// Error record instance to process. public void WriteError(ErrorRecord errorRecord) { - if (errorRecord.Exception != null) + if (errorRecord.Exception is not null) throw errorRecord.Exception; else throw new InvalidOperationException(errorRecord.ToString()); @@ -231,7 +231,7 @@ public PSTransactionContext CurrentPSTransaction /// The error record to throw. public void ThrowTerminatingError(ErrorRecord errorRecord) { - if (errorRecord.Exception != null) + if (errorRecord.Exception is not null) { throw errorRecord.Exception; } diff --git a/src/System.Management.Automation/engine/DriveInterfaces.cs b/src/System.Management.Automation/engine/DriveInterfaces.cs index c79c624ee37..1674693af5a 100644 --- a/src/System.Management.Automation/engine/DriveInterfaces.cs +++ b/src/System.Management.Automation/engine/DriveInterfaces.cs @@ -60,7 +60,7 @@ public PSDriveInfo Current get { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); return _sessionState.CurrentDrive; @@ -104,7 +104,7 @@ public PSDriveInfo Current public PSDriveInfo New(PSDriveInfo drive, string scope) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -153,7 +153,7 @@ internal void New( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -186,7 +186,7 @@ internal object NewDriveDynamicParameters( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -216,7 +216,7 @@ internal object NewDriveDynamicParameters( public void Remove(string driveName, bool force, string scope) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -249,7 +249,7 @@ internal void Remove( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -279,7 +279,7 @@ internal void Remove( public PSDriveInfo Get(string driveName) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -316,7 +316,7 @@ public PSDriveInfo Get(string driveName) public PSDriveInfo GetAtScope(string driveName, string scope) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -330,7 +330,7 @@ public PSDriveInfo GetAtScope(string driveName, string scope) public Collection GetAll() { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); return _sessionState.Drives(null); @@ -354,7 +354,7 @@ public Collection GetAll() public Collection GetAllAtScope(string scope) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); return _sessionState.Drives(scope); @@ -372,7 +372,7 @@ public Collection GetAllAtScope(string scope) public Collection GetAllForProvider(string providerName) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object diff --git a/src/System.Management.Automation/engine/DscResourceInfo.cs b/src/System.Management.Automation/engine/DscResourceInfo.cs index 93f7be37323..5e3c9d8106e 100644 --- a/src/System.Management.Automation/engine/DscResourceInfo.cs +++ b/src/System.Management.Automation/engine/DscResourceInfo.cs @@ -104,7 +104,7 @@ internal DscResourceInfo(string name, string friendlyName, string path, string p /// Updated properties. public void UpdateProperties(IList properties) { - if (properties != null) + if (properties is not null) this.Properties = new ReadOnlyCollection(properties); } @@ -156,7 +156,7 @@ internal DscResourcePropertyInfo() internal void UpdateValues(IList values) { - if (values != null) + if (values is not null) this.Values = new ReadOnlyCollection(values); } } diff --git a/src/System.Management.Automation/engine/DscResourceSearcher.cs b/src/System.Management.Automation/engine/DscResourceSearcher.cs index b675e007680..32516c0964d 100644 --- a/src/System.Management.Automation/engine/DscResourceSearcher.cs +++ b/src/System.Management.Automation/engine/DscResourceSearcher.cs @@ -18,7 +18,7 @@ internal DscResourceSearcher( string resourceName, ExecutionContext context) { - Diagnostics.Assert(context != null, "caller to verify context is not null"); + Diagnostics.Assert(context is not null, "caller to verify context is not null"); Diagnostics.Assert(!string.IsNullOrEmpty(resourceName), "caller to verify commandName is valid"); _resourceName = resourceName; @@ -81,7 +81,7 @@ public bool MoveNext() { _currentMatch = GetNextDscResource(); - if (_currentMatch != null) + if (_currentMatch is not null) return true; return false; @@ -134,7 +134,7 @@ private DscResourceInfo GetNextDscResource() foreach (dynamic resource in psObjs) { - if (resource.Name != null) + if (resource.Name is not null) { string resourceName = resource.Name; @@ -153,10 +153,10 @@ private DscResourceInfo GetNextDscResource() PSModuleInfo psMod = resource.Module as PSModuleInfo; - if (psMod != null) + if (psMod is not null) resourceInfo.Module = psMod; - if (resource.ImplementedAs != null) + if (resource.ImplementedAs is not null) { ImplementedAsType impType; if (Enum.TryParse(resource.ImplementedAs.ToString(), out impType)) @@ -165,7 +165,7 @@ private DscResourceInfo GetNextDscResource() var properties = resource.Properties as IList; - if (properties != null) + if (properties is not null) { List propertyList = new List(); diff --git a/src/System.Management.Automation/engine/EngineIntrinsics.cs b/src/System.Management.Automation/engine/EngineIntrinsics.cs index 65c1da34470..f71ab0517b6 100644 --- a/src/System.Management.Automation/engine/EngineIntrinsics.cs +++ b/src/System.Management.Automation/engine/EngineIntrinsics.cs @@ -56,7 +56,7 @@ public PSHost Host get { Dbg.Diagnostics.Assert( - _host != null, + _host is not null, "The only constructor for this class should always set the host field"); return _host; diff --git a/src/System.Management.Automation/engine/ErrorPackage.cs b/src/System.Management.Automation/engine/ErrorPackage.cs index da96fa1ff76..32bd947d2f3 100644 --- a/src/System.Management.Automation/engine/ErrorPackage.cs +++ b/src/System.Management.Automation/engine/ErrorPackage.cs @@ -230,7 +230,7 @@ public string Activity return _errorRecord._activityOverride; } - if (_errorRecord.InvocationInfo != null + if (_errorRecord.InvocationInfo is not null && (_errorRecord.InvocationInfo.MyCommand is CmdletInfo || _errorRecord.InvocationInfo.MyCommand is IScriptCommandInfo) && !string.IsNullOrEmpty(_errorRecord.InvocationInfo.MyCommand.Name) ) @@ -266,7 +266,7 @@ public string Reason return _errorRecord._reasonOverride; } - if (_errorRecord.Exception != null) + if (_errorRecord.Exception is not null) { _reasonIsExceptionType = true; return _errorRecord.Exception.GetType().Name; @@ -302,7 +302,7 @@ public string TargetName return _errorRecord._targetNameOverride; } - if (_errorRecord.TargetObject != null) + if (_errorRecord.TargetObject is not null) { string targetInString; try @@ -345,7 +345,7 @@ public string TargetType return _errorRecord._targetTypeOverride; } - if (_errorRecord.TargetObject != null) + if (_errorRecord.TargetObject is not null) { return _errorRecord.TargetObject.GetType().Name; } @@ -723,7 +723,7 @@ protected ErrorDetails(SerializationInfo info, [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info != null) + if (info is not null) { info.AddValue("ErrorDetails_Message", _message); info.AddValue("ErrorDetails_RecommendedAction", @@ -1080,7 +1080,7 @@ protected ErrorRecord(SerializationInfo info, [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info != null) + if (info is not null) { PSObject psObject = RemotingEncoder.CreateEmptyPSObject(); @@ -1183,10 +1183,10 @@ private void PopulateProperties( _targetNameOverride = errorCategory_TargetName; _targetTypeOverride = errorCategory_TargetType; _serializedErrorCategoryMessageOverride = errorCategory_Message; - if (errorDetails_Message != null) + if (errorDetails_Message is not null) { ErrorDetails = new ErrorDetails(errorDetails_Message); - if (errorDetails_RecommendedAction != null) + if (errorDetails_RecommendedAction is not null) { ErrorDetails.RecommendedAction = errorDetails_RecommendedAction; } @@ -1217,7 +1217,7 @@ private void ToPSObjectForRemoting(PSObject dest, bool serializeExtInfo) RemotingEncoder.AddNoteProperty(dest, "ErrorCategory_TargetType", delegate () { return CategoryInfo.TargetType; }); RemotingEncoder.AddNoteProperty(dest, "ErrorCategory_Message", delegate () { return CategoryInfo.GetMessage(CultureInfo.CurrentCulture); }); - if (ErrorDetails != null) + if (ErrorDetails is not null) { RemotingEncoder.AddNoteProperty(dest, "ErrorDetails_Message", delegate () { return ErrorDetails.Message; }); RemotingEncoder.AddNoteProperty(dest, "ErrorDetails_RecommendedAction", delegate () { return ErrorDetails.RecommendedAction; }); @@ -1299,10 +1299,10 @@ private void ConstructFromPSObjectForRemoting(PSObject serializedErrorRecord) object targetObject = RemotingDecoder.GetPropertyValue(serializedErrorRecord, "TargetObject"); string exceptionMessage = null; - if (serializedException != null) + if (serializedException is not null) { PSPropertyInfo messageProperty = serializedException.Properties["Message"] as PSPropertyInfo; - if (messageProperty != null) + if (messageProperty is not null) { exceptionMessage = messageProperty.Value as string; } @@ -1368,7 +1368,7 @@ private void ConstructFromPSObjectForRemoting(PSObject serializedErrorRecord) _invocationInfo = new InvocationInfo(serializedErrorRecord); ArrayList iterationInfo = RemotingDecoder.GetPropertyValue(serializedErrorRecord, "PipelineIterationInfo"); - if (iterationInfo != null) + if (iterationInfo is not null) { _pipelineIterationInfo = new ReadOnlyCollection((int[])iterationInfo.ToArray(typeof(Int32))); } @@ -1399,7 +1399,7 @@ public ErrorRecord(ErrorRecord errorRecord, throw new PSArgumentNullException(nameof(errorRecord)); } - if (replaceParentContainsErrorRecordException != null + if (replaceParentContainsErrorRecordException is not null && (errorRecord.Exception is ParentContainsErrorRecordException)) { _error = replaceParentContainsErrorRecordException; @@ -1416,7 +1416,7 @@ public ErrorRecord(ErrorRecord errorRecord, _reasonOverride = errorRecord._reasonOverride; _targetNameOverride = errorRecord._targetNameOverride; _targetTypeOverride = errorRecord._targetTypeOverride; - if (errorRecord.ErrorDetails != null) + if (errorRecord.ErrorDetails is not null) { ErrorDetails = new ErrorDetails(errorRecord.ErrorDetails); } @@ -1456,7 +1456,7 @@ public Exception Exception { get { - Diagnostics.Assert(_error != null, "_error is null"); + Diagnostics.Assert(_error is not null, "_error is null"); return _error; } } @@ -1501,7 +1501,7 @@ public string FullyQualifiedErrorId { get { - if (_serializedFullyQualifiedErrorId != null) + if (_serializedFullyQualifiedErrorId is not null) { return _serializedFullyQualifiedErrorId; } @@ -1539,13 +1539,13 @@ internal void SetInvocationInfo(InvocationInfo invocationInfo) { // Save the DisplayScriptPosition, if set IScriptExtent savedDisplayScriptPosition = null; - if (_invocationInfo != null) + if (_invocationInfo is not null) { savedDisplayScriptPosition = _invocationInfo.DisplayScriptPosition; } // Assign the invocationInfo - if (invocationInfo != null) + if (invocationInfo is not null) { _invocationInfo = new InvocationInfo(invocationInfo.MyCommand, invocationInfo.ScriptPosition); _invocationInfo.InvocationName = invocationInfo.InvocationName; @@ -1558,7 +1558,7 @@ internal void SetInvocationInfo(InvocationInfo invocationInfo) } // Restore the DisplayScriptPosition - if (savedDisplayScriptPosition != null) + if (savedDisplayScriptPosition is not null) { _invocationInfo.DisplayScriptPosition = savedDisplayScriptPosition; } @@ -1568,7 +1568,7 @@ internal void SetInvocationInfo(InvocationInfo invocationInfo) // // Copy a snapshot of the PipelinePositionInfo from the InvocationInfo to this ErrorRecord // - if (invocationInfo != null && invocationInfo.PipelineIterationInfo != null) + if (invocationInfo is not null && invocationInfo.PipelineIterationInfo is not null) { int[] snapshot = (int[])invocationInfo.PipelineIterationInfo.Clone(); @@ -1588,13 +1588,13 @@ internal void SetInvocationInfo(InvocationInfo invocationInfo) internal void LockScriptStackTrace() { - if (_scriptStackTrace != null) + if (_scriptStackTrace is not null) { return; } var context = LocalPipeline.GetExecutionContextFromTLS(); - if (context != null) + if (context is not null) { StringBuilder sb = new StringBuilder(); var callstack = context.Debugger.GetCallStack(); @@ -1663,7 +1663,7 @@ private string GetInvocationTypeName() } IScriptCommandInfo scriptInfo = commandInfo as IScriptCommandInfo; - if (scriptInfo != null) + if (scriptInfo is not null) { return commandInfo.Name; } @@ -1686,12 +1686,12 @@ private string GetInvocationTypeName() /// Developer-readable identifier. public override string ToString() { - if (ErrorDetails != null && !string.IsNullOrEmpty(ErrorDetails.Message)) + if (ErrorDetails is not null && !string.IsNullOrEmpty(ErrorDetails.Message)) { return ErrorDetails.Message; } - if (Exception != null) + if (Exception is not null) { if (!string.IsNullOrEmpty(Exception.Message)) { diff --git a/src/System.Management.Automation/engine/EventManager.cs b/src/System.Management.Automation/engine/EventManager.cs index b6d3dc27909..18a18f8ecf9 100644 --- a/src/System.Management.Automation/engine/EventManager.cs +++ b/src/System.Management.Automation/engine/EventManager.cs @@ -658,11 +658,11 @@ private void ProcessNewSubscriber(PSEventSubscriber subscriber, object source, s bool isOnIdleEvent = false; // If we are subscribing to an event on an object, generate the supporting delegate // for that object. - if (source != null) + if (source is not null) { // If the identifier starts with "PowerShell.", then it will collide with engine // events - if ((sourceIdentifier != null) && + if ((sourceIdentifier is not null) && (sourceIdentifier.StartsWith("PowerShell.", StringComparison.OrdinalIgnoreCase))) { string errorMessage = StringUtil.Format(EventingResources.ReservedIdentifier, sourceIdentifier); @@ -692,7 +692,7 @@ private void ProcessNewSubscriber(PSEventSubscriber subscriber, object source, s // Try to set the EnableRaisingEvents property if it defines one PropertyInfo eventProperty = sourceType.GetProperty("EnableRaisingEvents"); - if (eventProperty != null && eventProperty.CanWrite) + if (eventProperty is not null && eventProperty.CanWrite) { try { @@ -701,7 +701,7 @@ private void ProcessNewSubscriber(PSEventSubscriber subscriber, object source, s } catch (TargetInvocationException e) { - if (e.InnerException != null) + if (e.InnerException is not null) { throw e.InnerException; } @@ -834,7 +834,7 @@ private void UnsubscribeEvent(PSEventSubscriber subscriber, bool skipDraining) subscriber.IsBeingUnsubscribed = true; } - if ((existingSubscriber != null) && (subscriber.SourceObject != null)) + if ((existingSubscriber is not null) && (subscriber.SourceObject is not null)) { // Fire the unregistration handler subscriber.OnPSEventUnsubscribed(subscriber.SourceObject, @@ -847,7 +847,7 @@ private void UnsubscribeEvent(PSEventSubscriber subscriber, bool skipDraining) BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase; eventInfo = sourceType.GetEvent(subscriber.EventName, bindingFlags); - if ((eventInfo != null) && (existingSubscriber != null)) + if ((eventInfo is not null) && (existingSubscriber is not null)) { eventInfo.RemoveEventHandler(subscriber.SourceObject, existingSubscriber); } @@ -862,7 +862,7 @@ private void UnsubscribeEvent(PSEventSubscriber subscriber, bool skipDraining) } // Stop the job - if (subscriber.Action != null) + if (subscriber.Action is not null) { subscriber.Action.NotifyJobStopped(); } @@ -929,7 +929,7 @@ protected internal override void ProcessNewEvent(PSEventArgs newEvent, { ProcessNewEventImplementation(newEvent, true); ManualResetEventSlim waitHandle = newEvent.EventProcessed; - if (waitHandle != null) + if (waitHandle is not null) { // Win8: 738767 In Win7, the processInCurrentThread parameter was used to be // called processSynchronously. Even though the parameter was called "processSynchronously", @@ -975,12 +975,12 @@ private void ProcessNewEventImplementation(PSEventArgs newEvent, bool processSyn newEvent.ForwardEvent = subscriber.ForwardEvent; // If we found a subscriber and it has an action, queue it up - if (subscriber.Action != null) + if (subscriber.Action is not null) { AddAction(new EventAction(subscriber, newEvent), processSynchronously); capturedEvent = true; } - else if (subscriber.HandlerDelegate != null) + else if (subscriber.HandlerDelegate is not null) { if (subscriber.ShouldProcessInExecutionThread) { @@ -1238,7 +1238,7 @@ private void InvokeAction(EventAction nextAction, out bool addActionBack) // Invoke the action in its own session state SessionStateInternal oldSessionState = _context.EngineSessionState; - if (nextAction.Sender.Action != null) + if (nextAction.Sender.Action is not null) { _context.EngineSessionState = nextAction.Sender.Action.ScriptBlock.SessionStateInternal; } @@ -1252,7 +1252,7 @@ private void InvokeAction(EventAction nextAction, out bool addActionBack) // scriptblock will execute under, so that scriptblocks will stay in the same // runspace they were invoked from. Runspace.DefaultRunspace = _context.CurrentRunspace; - if (nextAction.Sender.Action != null) + if (nextAction.Sender.Action is not null) { nextAction.Sender.Action.Invoke(nextAction.Sender, nextAction.Args); } @@ -1278,7 +1278,7 @@ private void InvokeAction(EventAction nextAction, out bool addActionBack) finally { var eventProcessed = nextAction.Args.EventProcessed; - if (!addActionBack && eventProcessed != null) + if (!addActionBack && eventProcessed is not null) { eventProcessed.Set(); } @@ -1292,7 +1292,7 @@ private void InvokeAction(EventAction nextAction, out bool addActionBack) internal bool IsExecutingEventAction { - get { return (_processingAction != null); } + get { return (_processingAction is not null); } } /// @@ -1513,7 +1513,7 @@ protected virtual void OnForwardEvent(PSEventArgs e) { EventHandler eh = ForwardEvent; - if (eh != null) + if (eh is not null) { eh(this, e); } @@ -1549,7 +1549,7 @@ public void Dispose(bool disposing) { lock (_eventSubscribers) { - if (_timer != null) + if (_timer is not null) { _timer.Dispose(); } @@ -1826,7 +1826,7 @@ protected virtual void OnForwardEvent(PSEventArgs e) { EventHandler eh = ForwardEvent; - if (eh != null) + if (eh is not null) { eh(this, e); } @@ -1914,7 +1914,7 @@ internal PSEventSubscriber(ExecutionContext context, int id, object source, this(context, id, source, eventName, sourceIdentifier, supportEvent, forwardEvent, maxTriggerCount) { // Create the bound scriptblock, and job. - if (action != null) + if (action is not null) { ScriptBlock newAction = CreateBoundScriptBlock(action); Action = new PSEventJob(context.Events, this, newAction, sourceIdentifier); @@ -1926,7 +1926,7 @@ internal void RegisterJob() // Add this event subscriber to the job repository if it's not a support event. if (!SupportEvent) { - if (this.Action != null) + if (this.Action is not null) { JobRepository jobRepository = ((LocalRunspace)_context.CurrentRunspace).JobRepository; jobRepository.Add(Action); @@ -2067,7 +2067,7 @@ public override int GetHashCode() internal void OnPSEventUnsubscribed(object sender, PSEventUnsubscribedEventArgs e) { - if (Unsubscribed != null) + if (Unsubscribed is not null) { Unsubscribed(sender, e); } @@ -2214,12 +2214,12 @@ public class PSEventArgs : EventArgs internal PSEventArgs(string computerName, Guid runspaceId, int eventIdentifier, string sourceIdentifier, object sender, object[] originalArgs, PSObject additionalData) { // Capture the first EventArgs as SourceEventArgs - if (originalArgs != null) + if (originalArgs is not null) { foreach (object argument in originalArgs) { EventArgs sourceEventArgs = argument as EventArgs; - if (sourceEventArgs != null) + if (sourceEventArgs is not null) { SourceEventArgs = sourceEventArgs; break; @@ -2405,7 +2405,7 @@ public PSEventArgs this[int index] private void OnPSEventReceived(object sender, PSEventArgs e) { PSEventReceivedEventHandler eventHandler = PSEventReceived; - if (eventHandler != null) + if (eventHandler is not null) { eventHandler(sender, e); } diff --git a/src/System.Management.Automation/engine/ExecutionContext.cs b/src/System.Management.Automation/engine/ExecutionContext.cs index 70dec4a3f4e..02def640077 100644 --- a/src/System.Management.Automation/engine/ExecutionContext.cs +++ b/src/System.Management.Automation/engine/ExecutionContext.cs @@ -53,18 +53,18 @@ internal ScriptDebugger Debugger /// internal void ResetManagers() { - if (_debugger != null) + if (_debugger is not null) { _debugger.ResetDebugger(); } - if (Events != null) + if (Events is not null) { Events.Dispose(); } Events = new PSLocalEventManager(this); - if (this.transactionManager != null) + if (this.transactionManager is not null) { this.transactionManager.Dispose(); } @@ -113,7 +113,7 @@ internal static bool IsStrictVersion(ExecutionContext context, int majorVersion) context = LocalPipeline.GetExecutionContextFromTLS(); } - return (context != null) + return (context is not null) ? context.IsStrictVersion(majorVersion) : false; } @@ -126,10 +126,10 @@ internal static bool IsStrictVersion(ExecutionContext context, int majorVersion) internal bool IsStrictVersion(int majorVersion) { SessionStateScope scope = EngineSessionState.CurrentScope; - while (scope != null) + while (scope is not null) { // If StrictModeVersion is null, we haven't seen set-strictmode, so check the parent scope. - if (scope.StrictModeVersion != null) + if (scope.StrictModeVersion is not null) { // If StrictModeVersion is not null, just check the major version. A version of 0 // is the same as off to make this a simple check. @@ -219,7 +219,7 @@ internal void ReleaseResponsibilityForModuleAnalysisAppDomain() { Diagnostics.Assert(_responsibilityForModuleAnalysisAppDomainOwned, "Invalid module analysis app domain state"); - if (AppDomainForModuleAnalysis != null) + if (AppDomainForModuleAnalysis is not null) { AppDomain.Unload(AppDomainForModuleAnalysis); AppDomainForModuleAnalysis = null; @@ -407,7 +407,7 @@ internal static bool IsMarkedAsUntrusted(object value) { bool result = false; var baseValue = PSObject.Base(value); - if (baseValue != null && baseValue != NullString.Value) + if (baseValue is not null && baseValue != NullString.Value) { object unused; result = UntrustedObjects.TryGetValue(baseValue, out unused); @@ -423,7 +423,7 @@ internal static void MarkObjectAsUntrusted(object value) { // If the value is a PSObject, then we mark its base object untrusted var baseValue = PSObject.Base(value); - if (baseValue != null && baseValue != NullString.Value) + if (baseValue is not null && baseValue != NullString.Value) { // It's actually setting a key value pair when the key doesn't exist UntrustedObjects.GetValue(baseValue, key => null); @@ -435,7 +435,7 @@ internal static void MarkObjectAsUntrusted(object value) // marked before making a recursive call. The additional check adds extra overhead for handling PSReference object, but it should // be rare in practice. var psRef = baseValue as PSReference; - if (psRef != null && !IsMarkedAsUntrusted(psRef.Value)) + if (psRef is not null && !IsMarkedAsUntrusted(psRef.Value)) { MarkObjectAsUntrusted(psRef.Value); } @@ -455,7 +455,7 @@ 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 - (sessionState.Module != null && // it's running in a module AND + (sessionState.Module is not 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) { // We are setting value for either a 'Global:' variable, or a 'Script:' variable within a module in 'ConstrainedLanguage' mode. @@ -488,7 +488,7 @@ internal bool UseFullLanguageModeInDebugger { get { - return InitialSessionState != null ? InitialSessionState.UseFullLanguageModeInDebugger : false; + return InitialSessionState is not null ? InitialSessionState.UseFullLanguageModeInDebugger : false; } } @@ -587,12 +587,12 @@ internal T GetEnumPreference(VariablePath preferenceVariablePath, T defaultPr defaultUsed = true; T result = defaultPref; - if (val != null) + if (val is not null) { try { string valString = val as string; - if (valString != null) + if (valString is not null) { result = (T)Enum.Parse(typeof(T), valString, true); defaultUsed = false; @@ -693,7 +693,7 @@ internal CommandProcessorBase CreateCommand(string command, bool dotSource) CommandProcessorBase commandProcessor = CommandDiscovery.LookupCommandProcessor(command, commandOrigin, !dotSource); // Reset the command origin for script commands... // BUGBUG - dotting can get around command origin checks??? - if (commandProcessor != null && commandProcessor is ScriptCommandProcessorBase) + if (commandProcessor is not null && commandProcessor is ScriptCommandProcessorBase) { commandProcessor.Command.CommandOriginInternal = CommandOrigin.Internal; } @@ -899,7 +899,7 @@ internal void AppendDollarError(object obj) // otherwise check the exception members of the error records... ErrorRecord er1 = arraylist[0] as ErrorRecord; - if (er1 != null && objAsErrorRecord != null && er1.Exception == objAsErrorRecord.Exception) + if (er1 is not null && objAsErrorRecord is not null && er1.Exception == objAsErrorRecord.Exception) return; } @@ -1204,18 +1204,18 @@ internal void RunspaceClosingNotification() { EngineSessionState.RunspaceClosingNotification(); - if (_debugger != null) + if (_debugger is not null) { _debugger.Dispose(); } - if (Events != null) + if (Events is not null) { Events.Dispose(); } Events = null; - if (this.transactionManager != null) + if (this.transactionManager is not null) { this.transactionManager.Dispose(); } @@ -1242,7 +1242,7 @@ internal TypeTable TypeTable set { _typeTable = value; - _typeTableWeakReference = (value != null) ? new WeakReference(value) : null; + _typeTableWeakReference = (value is not null) ? new WeakReference(value) : null; } } @@ -1278,7 +1278,7 @@ internal TypeInfoDataBaseManager FormatDBManager // create and initialize an empty one. _formatDBManager = new TypeInfoDataBaseManager(); _formatDBManager.Update(this.AuthorizationManager, this.EngineHostInterface); - if (this.InitialSessionState != null) + if (this.InitialSessionState is not null) { // Win8:418011: Set DisableFormatTableUpdates only after performing the initial update. Otherwise, formatDBManager will be // in bad state. @@ -1340,7 +1340,7 @@ internal Assembly AddAssembly(string name, string filename, out Exception error) internal void RemoveAssembly(string name) { Assembly loadedAssembly; - if (AssemblyCache.TryGetValue(name, out loadedAssembly) && loadedAssembly != null) + if (AssemblyCache.TryGetValue(name, out loadedAssembly) && loadedAssembly is not null) { AssemblyCache.Remove(name); @@ -1419,7 +1419,7 @@ internal static Assembly LoadAssembly(string name, string filename, out Exceptio } // If the assembly is loaded, we ignore error as it may come from the filepath loading. - if (loadedAssembly != null) + if (loadedAssembly is not null) { error = null; } @@ -1502,7 +1502,7 @@ internal void ReportEngineStartupError(Exception e) ErrorRecord error = null; var rte = e as RuntimeException; - error = rte != null + error = rte is not null ? new ErrorRecord(rte.ErrorRecord, rte) : new ErrorRecord(e, errorId, ErrorCategory.OperationStopped, null); @@ -1555,7 +1555,7 @@ private bool IsModuleCommandCurrentlyRunning(out Cmdlet command, out string erro command = null; errorId = null; bool result = false; - if (this.CurrentCommandProcessor != null) + if (this.CurrentCommandProcessor is not null) { CommandInfo cmdletInfo = this.CurrentCommandProcessor.CommandInfo; if ((string.Equals(cmdletInfo.Name, "Import-Module", StringComparison.OrdinalIgnoreCase) || @@ -1654,9 +1654,9 @@ private void InitializeCommon(AutomationEngine engine, PSHost hostInterface) private static Assembly PowerShellAssemblyResolveHandler(object sender, ResolveEventArgs args) { ExecutionContext ecFromTLS = Runspaces.LocalPipeline.GetExecutionContextFromTLS(); - if (ecFromTLS != null) + if (ecFromTLS is not null) { - if (ecFromTLS.AssemblyCache != null) + if (ecFromTLS.AssemblyCache is not null) { Assembly assembly; ecFromTLS.AssemblyCache.TryGetValue(args.Name, out assembly); diff --git a/src/System.Management.Automation/engine/ExperimentalFeature/GetExperimentalFeatureCommand.cs b/src/System.Management.Automation/engine/ExperimentalFeature/GetExperimentalFeatureCommand.cs index ff1c964fc4c..20f93609c3a 100644 --- a/src/System.Management.Automation/engine/ExperimentalFeature/GetExperimentalFeatureCommand.cs +++ b/src/System.Management.Automation/engine/ExperimentalFeature/GetExperimentalFeatureCommand.cs @@ -94,7 +94,7 @@ private IEnumerable GetValidModuleFiles(HashSet moduleNamesToFin // We only care about module manifest files because that's where experimental features are declared. if (!moduleFile.EndsWith(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase)) { continue; } - if (moduleNamesToFind != null) + if (moduleNamesToFind is not null) { string currentModuleName = ModuleIntrinsics.GetModuleName(moduleFile); if (!moduleNamesToFind.Contains(currentModuleName)) { continue; } diff --git a/src/System.Management.Automation/engine/ExternalScriptInfo.cs b/src/System.Management.Automation/engine/ExternalScriptInfo.cs index e2119fb70b1..c0b54b5faa8 100644 --- a/src/System.Management.Automation/engine/ExternalScriptInfo.cs +++ b/src/System.Management.Automation/engine/ExternalScriptInfo.cs @@ -224,7 +224,7 @@ public ScriptBlock ScriptBlock private set { _scriptBlock = value; - if (value != null) + if (value is not null) { _scriptBlock.LanguageMode = this.DefiningLanguageMode; } @@ -242,7 +242,7 @@ private static ScriptBlock ParseScriptContents(Parser parser, string fileName, s if (definingLanguageMode.HasValue && (definingLanguageMode == PSLanguageMode.FullLanguage)) { var context = LocalPipeline.GetExecutionContextFromTLS(); - if ((context != null) && (context.LanguageMode == PSLanguageMode.ConstrainedLanguage)) + if ((context is not null) && (context.LanguageMode == PSLanguageMode.ConstrainedLanguage)) { context.LanguageMode = PSLanguageMode.FullLanguage; try @@ -267,7 +267,7 @@ internal ScriptBlockAst GetScriptBlockAst() this.ScriptBlock = ScriptBlock.TryGetCachedScriptBlock(_path, scriptContents); } - if (_scriptBlock != null) + if (_scriptBlock is not null) { return (ScriptBlockAst)_scriptBlock.Ast; } @@ -281,7 +281,7 @@ internal ScriptBlockAst GetScriptBlockAst() // to parse the script contents in FullLanguage mode context. Otherwise we will get bogus parsing errors // such as "Configuration or Class keyword not allowed". var context = LocalPipeline.GetExecutionContextFromTLS(); - if (context != null && context.LanguageMode == PSLanguageMode.ConstrainedLanguage && + if (context is not null && context.LanguageMode == PSLanguageMode.ConstrainedLanguage && DefiningLanguageMode == PSLanguageMode.FullLanguage) { context.LanguageMode = PSLanguageMode.FullLanguage; @@ -326,7 +326,7 @@ public void ValidateScriptInfo(Host.PSHost host) // to get the CommandMetadata for a script (either to prepopulate the metadata // or creating a proxy). If context can be null under any other circumstances, // we need to make sure it's acceptable if the parser is invoked on unsigned scripts. - if (context != null) + if (context is not null) { CommandDiscovery.ShouldRun(context, host, this, CommandOrigin.Internal); _signatureChecked = true; @@ -536,7 +536,7 @@ private void ReadScriptContents() } else { - if (this.Context != null) + if (this.Context is not null) { this.DefiningLanguageMode = this.Context.LanguageMode; } diff --git a/src/System.Management.Automation/engine/ExtraAdapter.cs b/src/System.Management.Automation/engine/ExtraAdapter.cs index 5fe3eb984cf..af398a21f7b 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 is null) || ((collection.Value is null) && (invokeGetValue is not null))) { valueToTake = invokeGetValue; } @@ -84,7 +84,7 @@ protected override T GetMember(object obj, string memberName) property = null; } - if (typeof(T).IsAssignableFrom(typeof(PSProperty)) && property != null) + if (typeof(T).IsAssignableFrom(typeof(PSProperty)) && property is not null) { return property as T; } @@ -193,7 +193,7 @@ protected override void PropertySet(PSProperty property, object setValue, bool c { PropertyValueCollection values = property.adapterData as PropertyValueCollection; - if (values != null) + if (values is not null) { // This means GetMember returned PropertyValueCollection try @@ -228,7 +228,7 @@ protected override void PropertySet(PSProperty property, object setValue, bool c { // This means GetMember returned the value from InvokeGet..So set the value using InvokeSet. DirectoryEntry entry = (DirectoryEntry)property.baseObject; - Diagnostics.Assert(entry != null, "Object should be of type DirectoryEntry in DirectoryEntry adapter."); + Diagnostics.Assert(entry is not null, "Object should be of type DirectoryEntry in DirectoryEntry adapter."); List setValues = new List(); IEnumerable enumValues = LanguagePrimitives.GetEnumerable(setValue); @@ -355,7 +355,7 @@ protected override object MethodInvoke(PSMethod method, object[] arguments) // this code is reached only on exception // check if there is a dotnet method, invoke the dotnet method if available PSMethod dotNetmethod = s_dotNetAdapter.GetDotNetMethod(method.baseObject, method.name); - if (dotNetmethod != null) + if (dotNetmethod is not null) { return dotNetmethod.Invoke(arguments); } diff --git a/src/System.Management.Automation/engine/GetCommandCommand.cs b/src/System.Management.Automation/engine/GetCommandCommand.cs index 7c31186d6ed..26dea7b9f0f 100644 --- a/src/System.Management.Automation/engine/GetCommandCommand.cs +++ b/src/System.Management.Automation/engine/GetCommandCommand.cs @@ -50,7 +50,7 @@ public string[] Name _nameContainsWildcard = false; _names = value; - if (value != null) + if (value is not null) { foreach (string commandName in value) { @@ -160,7 +160,7 @@ public ModuleSpecification[] FullyQualifiedModule set { - if (value != null) + if (value is not null) { _moduleSpecifications = value; } @@ -330,7 +330,7 @@ public PSTypeName[] ParameterType continue; } - if ((i != 0) && (ptn.Type != null) && (ptn.Type.Equals(typeof(object)))) + if ((i != 0) && (ptn.Type is not null) && (ptn.Type.Equals(typeof(object)))) { continue; } @@ -455,7 +455,7 @@ protected override void EndProcessing() } // report not-found errors for ParameterName and ParameterType if needed - if ((_matchedParameterNames != null) && (ParameterName != null)) + if ((_matchedParameterNames is not null) && (ParameterName is not null)) { foreach (string requestedParameterName in ParameterName) { @@ -490,7 +490,7 @@ protected override void EndProcessing() OutputResultsHelper(_accumulatedResults); object pssenderInfo = Context.GetVariableValue(SpecialVariables.PSSenderInfoVarPath); - if ((pssenderInfo != null) && (pssenderInfo is System.Management.Automation.Remoting.PSSenderInfo)) + if ((pssenderInfo is not null) && (pssenderInfo is System.Management.Automation.Remoting.PSSenderInfo)) { // Win8: 593295. Exchange has around 1000 cmdlets. During Import-PSSession, // Get-Command | select-object ..,HelpURI,... is run. HelpURI is a script property @@ -562,7 +562,7 @@ private void OutputResultsHelper(IEnumerable results) // what sort of commands people expect but either don't exist, or maybe should be installed by default. // The StartsWith is to avoid logging telemetry when suggestion mode checks the // current directory for scripts/exes in the current directory and '.' is not in the path. - if (count == 0 && Name != null && Name.Length > 0 && !Name[0].StartsWith(".\\", StringComparison.OrdinalIgnoreCase)) + if (count == 0 && Name is not null && Name.Length > 0 && !Name[0].StartsWith(".\\", StringComparison.OrdinalIgnoreCase)) { Telemetry.Internal.TelemetryAPI.ReportGetCommandFailed(Name, _timer.ElapsedMilliseconds); } @@ -588,7 +588,7 @@ private PSObject GetSyntaxObject(CommandInfo command) // So if a user runs Get-Command -Name del -Syntax the code will find del and the command it resolves to as Remove-Item // and attempt to return that, but as the user specified del we want to fiddle with the output a bit to make it clear // that's an alias but still give the Remove-Item syntax. - if (this.Name != null && !Array.Exists(this.Name, name => name.Equals(command.Name, StringComparison.InvariantCultureIgnoreCase))) + if (this.Name is not null && !Array.Exists(this.Name, name => name.Equals(command.Name, StringComparison.InvariantCultureIgnoreCase))) { string aliasName = _nameContainsWildcard ? command.Name : this.Name[0]; @@ -727,7 +727,7 @@ private bool IsNounVerbMatch(CommandInfo command) string verb; string noun; CmdletInfo cmdlet = command as CmdletInfo; - if (cmdlet != null) + if (cmdlet is not null) { verb = cmdlet.Verb; noun = cmdlet.Noun; @@ -808,7 +808,7 @@ private void AccumulateMatchingCommands(IEnumerable commandNames) // available modules for the command. string moduleName; string plainCommandName = Utils.ParseCommandName(commandName, out moduleName); - bool isModuleQualified = (moduleName != null); + bool isModuleQualified = (moduleName is not null); // If they've specified a module name, we can do some smarter filtering. // Otherwise, we have to filter everything. @@ -1039,7 +1039,7 @@ private bool FindCommandForName(SearchResolutionOptions options, string commandN _accumulatedResults.Add(current); - if (ArgumentList != null) + if (ArgumentList is not null) { // Don't iterate the enumerator any more. If -arguments was specified, then we stop at the first match break; @@ -1106,35 +1106,35 @@ private bool IsDuplicate(CommandInfo info) do // false loop { ApplicationInfo appInfo = info as ApplicationInfo; - if (appInfo != null) + if (appInfo is not null) { key = appInfo.Path; break; } CmdletInfo cmdletInfo = info as CmdletInfo; - if (cmdletInfo != null) + if (cmdletInfo is not null) { key = cmdletInfo.FullName; break; } ScriptInfo scriptInfo = info as ScriptInfo; - if (scriptInfo != null) + if (scriptInfo is not null) { key = scriptInfo.Definition; break; } ExternalScriptInfo externalScriptInfo = info as ExternalScriptInfo; - if (externalScriptInfo != null) + if (externalScriptInfo is not null) { key = externalScriptInfo.Path; break; } } while (false); - if (key != null) + if (key is not null) { if (_commandsWritten.ContainsKey(key)) { @@ -1165,7 +1165,7 @@ private bool IsParameterMatch(CommandInfo commandInfo) try { IDictionary tmp = commandInfo.Parameters; - if (tmp != null) + if (tmp is not null) { commandParameters = tmp.Values; } @@ -1234,7 +1234,7 @@ private bool IsParameterMatch(ParameterMetadata parameterMetadata) else { typeIsMatching = false; - if (_parameterTypes != null && + if (_parameterTypes is not null && _parameterTypes.Length > 0) { typeIsMatching |= _parameterTypes.Any(parameterMetadata.IsMatchingType); @@ -1291,7 +1291,7 @@ private bool IsCommandMatch(ref CommandInfo current, out bool isDuplicate) isCommandMatch = false; } } - else if (_modulePatterns != null && _modulePatterns.Count > 0) + else if (_modulePatterns is not null && _modulePatterns.Count > 0) { if (!SessionStateUtilities.MatchesAnyWildcardPattern(current.ModuleName, _modulePatterns, true)) { @@ -1320,7 +1320,7 @@ private bool IsCommandMatch(ref CommandInfo current, out bool isDuplicate) } } - if (ArgumentList != null && !(current is CmdletInfo || current is IScriptCommandInfo)) + if (ArgumentList is not null && !(current is CmdletInfo || current is IScriptCommandInfo)) { // If current is not a cmdlet or script, we need to throw a terminating error. ThrowTerminatingError( @@ -1361,7 +1361,7 @@ private bool IsCommandMatch(ref CommandInfo current, out bool isDuplicate) { CommandInfo newCurrent = current.CreateGetCommandCopy(ArgumentList); - if (ArgumentList != null) + if (ArgumentList is not null) { // We need to prepopulate the parameter metadata in the CmdletInfo to // ensure there are no errors. Getting the ParameterSets property @@ -1439,7 +1439,7 @@ private IEnumerable GetMatchingCommandsFromModules(string commandNa if (isModuleMatch) { - if (module.SessionState != null) + if (module.SessionState is not null) { // Look in function table if ((this.CommandType & (CommandTypes.Function | CommandTypes.Filter | CommandTypes.Configuration)) != 0) @@ -1487,7 +1487,7 @@ private IEnumerable GetMatchingCommandsFromModules(string commandNa private bool IsCommandInResult(CommandInfo command) { bool isPresent = false; - bool commandHasModule = command.Module != null; + bool commandHasModule = command.Module is not null; foreach (CommandInfo commandInfo in _accumulatedResults) { if ((command.CommandType == commandInfo.CommandType && @@ -1495,7 +1495,7 @@ private bool IsCommandInResult(CommandInfo command) // If the command has been imported with a prefix, then just checking the names for duplication will not be enough. // Hence, an additional check is done with the prefix information string.Equals(ModuleCmdletBase.RemovePrefixFromCommandName(commandInfo.Name, commandInfo.Prefix), command.Name, StringComparison.OrdinalIgnoreCase)) - ) && commandInfo.Module != null && commandHasModule && + ) && commandInfo.Module is not null && commandHasModule && ( // We do reference equal comparison if both command are imported. If either one is not imported, we compare the module path (commandInfo.IsImported && command.IsImported && commandInfo.Module.Equals(command.Module)) || ((!commandInfo.IsImported || !command.IsImported) && commandInfo.Module.Path.Equals(command.Module.Path, StringComparison.OrdinalIgnoreCase)) @@ -1547,7 +1547,7 @@ private static PSObject ConvertToShowCommandInfo(CommandInfo cmdInfo) private static PSObject GetModuleInfo(CommandInfo cmdInfo) { PSObject moduleInfo = new PSObject(); - string moduleName = (cmdInfo.Module != null) ? cmdInfo.Module.Name : string.Empty; + string moduleName = (cmdInfo.Module is not null) ? cmdInfo.Module.Name : string.Empty; moduleInfo.Properties.Add(new PSNoteProperty("Name", moduleName)); return moduleInfo; @@ -1558,7 +1558,7 @@ private static PSObject[] GetParameterSets(CommandInfo cmdInfo) ReadOnlyCollection parameterSets = null; try { - if (cmdInfo.ParameterSets != null) + if (cmdInfo.ParameterSets is not null) { parameterSets = cmdInfo.ParameterSets; } @@ -1602,7 +1602,7 @@ private static PSObject[] GetParameterInfo(ReadOnlyCollection validValues = new List(); var validateSetAttribute = parameter.Attributes.OfType().LastOrDefault(); - if (validateSetAttribute != null) + if (validateSetAttribute is not null) { hasParameterSet = true; validValues = validateSetAttribute.ValidValues; diff --git a/src/System.Management.Automation/engine/InformationRecord.cs b/src/System.Management.Automation/engine/InformationRecord.cs index e8ade610f0a..08fa9cec827 100644 --- a/src/System.Management.Automation/engine/InformationRecord.cs +++ b/src/System.Management.Automation/engine/InformationRecord.cs @@ -166,7 +166,7 @@ public uint ProcessId /// public override string ToString() { - if (MessageData != null) + if (MessageData is not null) { return MessageData.ToString(); } diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs index 8f1c39922a8..279ea5ccfca 100644 --- a/src/System.Management.Automation/engine/InitialSessionState.cs +++ b/src/System.Management.Automation/engine/InitialSessionState.cs @@ -233,11 +233,11 @@ public SessionStateTypeEntry(TypeData typeData, bool isRemove) public override InitialSessionStateEntry Clone() { SessionStateTypeEntry entry; - if (FileName != null) + if (FileName is not null) { entry = new SessionStateTypeEntry(FileName); } - else if (TypeTable != null) + else if (TypeTable is not null) { entry = new SessionStateTypeEntry(TypeTable); } @@ -339,11 +339,11 @@ public override InitialSessionStateEntry Clone() { SessionStateFormatEntry entry; - if (FileName != null) + if (FileName is not null) { entry = new SessionStateFormatEntry(FileName); } - else if (Formattable != null) + else if (Formattable is not null) { entry = new SessionStateFormatEntry(Formattable); } @@ -924,7 +924,7 @@ public override InitialSessionStateEntry Clone() { // Copy the attribute collection if necessary... Collection attrs = null; - if (_attributes != null && _attributes.Count > 0) + if (_attributes is not null && _attributes.Count > 0) { attrs = new Collection(_attributes); } @@ -1160,7 +1160,7 @@ public void Remove(string name, object type) { Type objType = null; - if (type != null) + if (type is not null) { objType = type as Type ?? type.GetType(); } @@ -1294,7 +1294,7 @@ private static void MakeDisallowedEntriesPrivate(InitialSessionStateEntryColl // Aliases to allowed commands are OK SessionStateAliasEntry aliasEntry = entry as SessionStateAliasEntry; - if (aliasEntry != null) + if (aliasEntry is not null) { if (allowedNames.Exists(allowedName => allowedName.Equals(aliasEntry.Definition, StringComparison.OrdinalIgnoreCase))) { @@ -1425,7 +1425,7 @@ private static InitialSessionState CreateRestrictedForRemoteServer() // make the cmdlet private Collection originalCmdlet = iss.Commands[commandName]; - Diagnostics.Assert(originalCmdlet != null, "Proxied cmdlets should be imported at this point"); + Diagnostics.Assert(originalCmdlet is not null, "Proxied cmdlets should be imported at this point"); Diagnostics.Assert(originalCmdlet.Count == 1, "Exactly one cmdlet with a given name"); originalCmdlet[0].Visibility = SessionStateEntryVisibility.Private; @@ -1527,7 +1527,7 @@ public static InitialSessionState CreateDefault() // in debug mode and is not intended to be a feature. // July 31 2008 - brucepay // Only load the core snapins at this point... - if (Environment.GetEnvironmentVariable("PowerShellMinimal") != null) + if (Environment.GetEnvironmentVariable("PowerShellMinimal") is not null) { if (si.Name.Equals("Microsoft.PowerShell.Host", StringComparison.OrdinalIgnoreCase)) break; @@ -2341,7 +2341,7 @@ private void Bind_BindCommands(PSModuleInfo module, bool noClobber, bool local, } SessionStateCmdletEntry ssce = cmd as SessionStateCmdletEntry; - if (ssce != null) + if (ssce is not null) { if (noClobber && ModuleCmdletBase.CommandFound(ssce.Name, ss)) { @@ -2358,21 +2358,21 @@ private void Bind_BindCommands(PSModuleInfo module, bool noClobber, bool local, cmd.SetModule(module); SessionStateFunctionEntry ssfe = cmd as SessionStateFunctionEntry; - if (ssfe != null) + if (ssfe is not null) { ss.AddSessionStateEntry(ssfe); continue; } SessionStateAliasEntry ssae = cmd as SessionStateAliasEntry; - if (ssae != null) + if (ssae is not null) { ss.AddSessionStateEntry(ssae, StringLiterals.Local); continue; } SessionStateApplicationEntry ssappe = cmd as SessionStateApplicationEntry; - if (ssappe != null) + if (ssappe is not null) { if (ssappe.Visibility == SessionStateEntryVisibility.Public) { @@ -2383,7 +2383,7 @@ private void Bind_BindCommands(PSModuleInfo module, bool noClobber, bool local, } SessionStateScriptEntry ssse = cmd as SessionStateScriptEntry; - if (ssse != null) + if (ssse is not null) { if (ssse.Visibility == SessionStateEntryVisibility.Public) { @@ -2420,7 +2420,7 @@ 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 is null || error is not null) { // If no module was found but there was no specific error, then // create a not found error. @@ -2470,7 +2470,7 @@ internal Exception BindRunspace(Runspace initializedRunspace, PSTraceSource runs HashSet publicCommands = null; HashSet GetPublicCommands() { - if (publicCommands != null) + if (publicCommands is not null) { return publicCommands; } @@ -2507,7 +2507,7 @@ HashSet GetPublicCommands() if (ModuleSpecificationsToImport.Count > 0 || unresolvedCmdsToExpose.Count > 0) { Exception moduleImportException = ProcessModulesToImport(initializedRunspace, ModuleSpecificationsToImport, string.Empty, GetPublicCommands(), unresolvedCmdsToExpose); - if (moduleImportException != null) + if (moduleImportException is not null) { runspaceInitTracer.WriteLine( "Runspace open failed while loading module: First error {1}", @@ -2543,7 +2543,7 @@ HashSet GetPublicCommands() if (UserDriveEnabled) { Exception userDriveException = ProcessUserDrive(initializedRunspace); - if (userDriveException != null) + if (userDriveException is not null) { runspaceInitTracer.WriteLine( "Runspace open failed while processing user drive with error {1}", @@ -2558,7 +2558,7 @@ HashSet GetPublicCommands() if (StartupScripts.Count > 0) { Exception startupScriptException = ProcessStartupScripts(initializedRunspace); - if (startupScriptException != null) + if (startupScriptException is not null) { runspaceInitTracer.WriteLine( "Runspace open failed while running startup script: First error {1}", @@ -2576,7 +2576,7 @@ HashSet GetPublicCommands() { psToInvoke.AddCommand(new Command("Start-Transcript")).AddParameter("OutputDirectory", TranscriptDirectory); Exception exceptionToReturn = ProcessPowerShellCommand(psToInvoke, initializedRunspace); - if (exceptionToReturn != null) + if (exceptionToReturn is not null) { // ThrowOnRunspaceOpenError handling is done by ProcessPowerShellCommand return exceptionToReturn; @@ -2629,7 +2629,7 @@ private string[] GetModulesForUnResolvedCommands(IEnumerable unresolvedC string expandedModulePath = IO.Path.GetFullPath(modulePath); var exportedCommands = AnalysisCache.GetExportedCommands(expandedModulePath, false, context); - if (exportedCommands != null && exportedCommands.ContainsKey(unresolvedCommand)) + if (exportedCommands is not null && exportedCommands.ContainsKey(unresolvedCommand)) { modulesToImport.Add(System.IO.Path.GetFileNameWithoutExtension(expandedModulePath)); break; @@ -2664,7 +2664,7 @@ private void ProcessCommandModifications(Runspace initializedRunspace) // If we are wrapping a function, rename it. FunctionInfo commandAsFunction = existingCommand as FunctionInfo; - if (commandAsFunction != null) + if (commandAsFunction is not null) { string newCommandName = commandAsFunction.Name + "_" + Guid.NewGuid().ToString("N"); commandAsFunction.Rename(newCommandName); @@ -2760,7 +2760,7 @@ private Exception ProcessDynamicVariables(Runspace initializedRunspace) string name = variable["Name"].ToString(); ScriptBlock sb = variable["Value"] as ScriptBlock; - if (!string.IsNullOrEmpty(name) && (sb != null)) + if (!string.IsNullOrEmpty(name) && (sb is not null)) { sb.SessionStateInternal = initializedRunspace.ExecutionContext.EngineSessionState; @@ -2770,7 +2770,7 @@ private Exception ProcessDynamicVariables(Runspace initializedRunspace) psToInvoke.AddCommand(new Command("Set-Variable")).AddParameter("Name", name); Exception exceptionToReturn = ProcessPowerShellCommand(psToInvoke, initializedRunspace); - if (exceptionToReturn != null) + if (exceptionToReturn is not null) { // ThrowOnRunspaceOpenError handling is done by ProcessPowerShellCommand return exceptionToReturn; @@ -2864,7 +2864,7 @@ private Exception ProcessStartupScripts(Runspace initializedRunspace) psToInvoke.AddCommand(new Command(startupScript, false, false)); Exception exceptionToReturn = ProcessPowerShellCommand(psToInvoke, initializedRunspace); - if (exceptionToReturn != null) + if (exceptionToReturn is not null) { // ThrowOnRunspaceOpenError handling is done by ProcessPowerShellCommand return exceptionToReturn; @@ -2919,14 +2919,14 @@ private Exception ProcessPowerShellCommand(PowerShell psToInvoke, Runspace initi if (errorList.Count > 0) { ErrorRecord lastErrorRecord = errorList[0] as ErrorRecord; - if (lastErrorRecord != null) + if (lastErrorRecord is not null) { return new Exception(lastErrorRecord.ToString()); } else { Exception lastException = errorList[0] as Exception; - if (lastException != null) + if (lastException is not null) { return lastException; } @@ -2953,14 +2953,14 @@ private RunspaceOpenModuleLoadException ProcessModulesToImport( foreach (object module in moduleList) { string moduleName = module as string; - if (moduleName != null) + if (moduleName is not null) { exceptionToReturn = ProcessOneModule(initializedRunspace, moduleName, null, path, publicCommands); } else { ModuleSpecification moduleSpecification = module as ModuleSpecification; - if (moduleSpecification != null) + if (moduleSpecification is not null) { if ((moduleSpecification.RequiredVersion is null) && (moduleSpecification.Version is null) && (moduleSpecification.MaximumVersion is null) && (moduleSpecification.Guid is null)) { @@ -2972,7 +2972,7 @@ private RunspaceOpenModuleLoadException ProcessModulesToImport( { Collection moduleInfos = ModuleCmdletBase.GetModuleIfAvailable(moduleSpecification, initializedRunspace); - if (moduleInfos != null && moduleInfos.Count > 0) + if (moduleInfos is not null && moduleInfos.Count > 0) { exceptionToReturn = ProcessOneModule(initializedRunspace, moduleSpecification.Name, moduleInfos[0], path, publicCommands); } @@ -2980,19 +2980,19 @@ private RunspaceOpenModuleLoadException ProcessModulesToImport( { var version = "0.0.0.0"; - if (moduleSpecification.RequiredVersion != null) + if (moduleSpecification.RequiredVersion is not null) { version = moduleSpecification.RequiredVersion.ToString(); } - else if (moduleSpecification.Version != null) + else if (moduleSpecification.Version is not null) { version = moduleSpecification.Version.ToString(); - if (moduleSpecification.MaximumVersion != null) + if (moduleSpecification.MaximumVersion is not null) { version = version + " - " + moduleSpecification.MaximumVersion; } } - else if (moduleSpecification.MaximumVersion != null) + else if (moduleSpecification.MaximumVersion is not null) { version = moduleSpecification.MaximumVersion; } @@ -3134,7 +3134,7 @@ private RunspaceOpenModuleLoadException ProcessOneModule(Runspace initializedRun { CommandInfo c = new CmdletInfo("Import-Module", typeof(ImportModuleCommand), null, null, initializedRunspace.ExecutionContext); Command cmd = new Command(c); - if (moduleInfoToLoad != null) + if (moduleInfoToLoad is not null) { cmd.Parameters.Add("ModuleInfo", moduleInfoToLoad); name = moduleInfoToLoad.Name; @@ -3217,7 +3217,7 @@ private RunspaceOpenModuleLoadException ValidateAndReturnRunspaceOpenModuleLoadE if (ThrowOnRunspaceOpenError) { RunspaceOpenModuleLoadException rome = null; - if (exception != null) + if (exception is not null) { rome = exception; } @@ -3237,7 +3237,7 @@ private RunspaceOpenModuleLoadException ValidateAndReturnRunspaceOpenModuleLoadE rome = new RunspaceOpenModuleLoadException(moduleName, mergedErrors); } - if (rome != null) + if (rome is not null) { return rome; } @@ -3326,7 +3326,7 @@ internal static void SetSessionStateDrive(ExecutionContext context, bool setLoca ProviderInfo fsProvider = context.EngineSessionState.GetSingleProvider(context.ProviderNames.FileSystem); Collection fsDrives = fsProvider.Drives; - if (fsDrives != null && fsDrives.Count > 0) + if (fsDrives is not null && fsDrives.Count > 0) { context.EngineSessionState.CurrentDrive = fsDrives[0]; fsDriveSet = true; @@ -3340,7 +3340,7 @@ internal static void SetSessionStateDrive(ExecutionContext context, bool setLoca { Collection allDrives = context.EngineSessionState.Drives(null); - if (allDrives != null && allDrives.Count > 0) + if (allDrives is not null && allDrives.Count > 0) { context.EngineSessionState.CurrentDrive = allDrives[0]; } @@ -3410,7 +3410,7 @@ internal void Unbind(ExecutionContext context) foreach (SessionStateCommandEntry cmd in Commands) { SessionStateCmdletEntry ssce = cmd as SessionStateCmdletEntry; - if (ssce != null) + if (ssce is not null) { List matches; if (context.TopLevelSessionState.GetCmdletTable().TryGetValue(ssce.Name, out matches)) @@ -3437,7 +3437,7 @@ internal void Unbind(ExecutionContext context) } // Remove all of the providers from the top-level provider table. - if (_providers != null && _providers.Count > 0) + if (_providers is not null && _providers.Count > 0) { Dictionary> providerTable = context.TopLevelSessionState.Providers; @@ -3446,7 +3446,7 @@ internal void Unbind(ExecutionContext context) List pl; if (providerTable.TryGetValue(sspe.Name, out pl)) { - Diagnostics.Assert(pl != null, "There should never be a null list of entries in the provider table"); + Diagnostics.Assert(pl is not null, "There should never be a null list of entries in the provider table"); // For each provider with the same name... for (int i = pl.Count - 1; i >= 0; i--) { @@ -3470,13 +3470,13 @@ internal void Unbind(ExecutionContext context) } List formatFilesToRemove = new List(); - if (this.Formats != null) + if (this.Formats is not null) { formatFilesToRemove.AddRange(this.Formats.Select(f => f.FileName)); } List typeFilesToRemove = new List(); - if (this.Types != null) + if (this.Types is not null) { typeFilesToRemove.AddRange(this.Types.Select(t => t.FileName)); } @@ -3490,7 +3490,7 @@ internal static void RemoveTypesAndFormats(ExecutionContext context, IList 0) + if (formatFilesToRemove is not null && formatFilesToRemove.Count > 0) { var newFormats = new InitialSessionStateEntryCollection(); HashSet formatFilesToRemoveSet = new HashSet(formatFilesToRemove, StringComparer.OrdinalIgnoreCase); @@ -3507,7 +3507,7 @@ internal static void RemoveTypesAndFormats(ExecutionContext context, IList 0) + if (typeFilesToRemove is not null && typeFilesToRemove.Count > 0) { // The types table has the same issue as the format table - we need to rebuild the entire table. var newTypes = new InitialSessionStateEntryCollection(); @@ -3561,7 +3561,7 @@ internal void UpdateTypes(ExecutionContext context, bool updateOnly) if (Types.Count == 1) { TypeTable typeTable = Types[0].TypeTable; - if (typeTable != null) + if (typeTable is not null) { // reuse the TypeTable instance specified in the sste. // this essentially allows for TypeTable sharing across @@ -3593,12 +3593,12 @@ internal void UpdateTypes(ExecutionContext context, bool updateOnly) sste => { // foreach (var sste in Types) - if (sste.FileName != null) + if (sste.FileName is not null) { if (filesProcessed.TryAdd(sste.FileName, null)) { string moduleName = string.Empty; - if (sste.PSSnapIn != null && !string.IsNullOrEmpty(sste.PSSnapIn.Name)) + if (sste.PSSnapIn is not null && !string.IsNullOrEmpty(sste.PSSnapIn.Name)) { moduleName = sste.PSSnapIn.Name; } @@ -3607,7 +3607,7 @@ internal void UpdateTypes(ExecutionContext context, bool updateOnly) context.TypeTable.Update(moduleName, sste.FileName, errors, context.AuthorizationManager, context.EngineHostInterface, out unused); } } - else if (sste.TypeTable != null) + else if (sste.TypeTable is not null) { // We get here only if it's NOT updating the existing type table // because we cannot do the update with a type table instance @@ -3681,7 +3681,7 @@ internal void UpdateFormats(ExecutionContext context, bool update) // If we're just updating the current runspace, then we'll add our entries // to the current list otherwise, we'll build a new list... - if (update && context.InitialSessionState != null) + if (update && context.InitialSessionState is not null) { formatsToLoad = context.InitialSessionState.Formats; formatsToLoad.Add(this.Formats); @@ -3696,12 +3696,12 @@ internal void UpdateFormats(ExecutionContext context, bool update) { string name = ssfe.FileName; PSSnapInInfo snapin = ssfe.PSSnapIn; - if (snapin != null && !string.IsNullOrEmpty(snapin.Name)) + if (snapin is not null && !string.IsNullOrEmpty(snapin.Name)) { name = snapin.Name; } - if (ssfe.Formattable != null) + if (ssfe.Formattable is not null) { if (formatsToLoad.Count == 1) { @@ -3714,7 +3714,7 @@ internal void UpdateFormats(ExecutionContext context, bool update) throw PSTraceSource.NewInvalidOperationException(FormatAndOutXmlLoadingStrings.FormatTableCannotCoExist); } } - else if (ssfe.FormatData != null) + else if (ssfe.FormatData is not null) { entries.Add(new PSSnapInTypeAndFormatErrors(name, ssfe.FormatData)); } @@ -3739,7 +3739,7 @@ internal void UpdateFormats(ExecutionContext context, bool update) // if this is the case... foreach (PSSnapInTypeAndFormatErrors entry in entries) { - if (entry.Errors != null && entry.Errors.Count > 0) + if (entry.Errors is not null && entry.Errors.Count > 0) { foreach (string error in entry.Errors) { @@ -3808,7 +3808,7 @@ public PSSnapInInfo ImportPSSnapIn(string name, out PSSnapInException warning) // Now actually load the snapin... PSSnapInInfo snapin = ImportPSSnapIn(newPSSnapIn, out warning); - if (snapin != null) + if (snapin is not null) { ImportedSnapins.Add(snapin.Name, snapin); } @@ -3843,7 +3843,7 @@ internal PSSnapInInfo ImportPSSnapIn(PSSnapInInfo psSnapInInfo, out PSSnapInExce foreach (SessionStateAssemblyEntry ae in this.Assemblies) { PSSnapInInfo loadedPSSnapInInfo = ae.PSSnapIn; - if (loadedPSSnapInInfo != null) + if (loadedPSSnapInInfo is not null) { // See if the assembly-qualified names match and return the existing PSSnapInInfo // if they do. @@ -3943,7 +3943,7 @@ internal PSSnapInInfo ImportPSSnapIn(PSSnapInInfo psSnapInInfo, out PSSnapInExce this.Assemblies.Add(assemblyEntry); } - if (cmdlets != null) + if (cmdlets is not null) { foreach (SessionStateCmdletEntry cmdlet in cmdlets.Values) { @@ -3954,7 +3954,7 @@ internal PSSnapInInfo ImportPSSnapIn(PSSnapInInfo psSnapInInfo, out PSSnapInExce } } - if (aliases != null) + if (aliases is not null) { foreach (var cmdletAliasesEntry in aliases.Values) { @@ -3966,7 +3966,7 @@ internal PSSnapInInfo ImportPSSnapIn(PSSnapInInfo psSnapInInfo, out PSSnapInExce } } - if (providers != null) + if (providers is not null) { foreach (SessionStateProviderEntry provider in providers.Values) { @@ -4065,7 +4065,7 @@ internal void ImportCmdletsFromAssembly(Assembly assembly, PSModuleInfo module) this.Assemblies.Add(assemblyEntry); } - if (cmdlets != null) + if (cmdlets is not null) { foreach (SessionStateCmdletEntry cmdlet in cmdlets.Values) { @@ -4073,7 +4073,7 @@ internal void ImportCmdletsFromAssembly(Assembly assembly, PSModuleInfo module) } } - if (aliases != null) + if (aliases is not null) { foreach (var cmdletAliasesEntry in aliases.Values) { @@ -4084,7 +4084,7 @@ internal void ImportCmdletsFromAssembly(Assembly assembly, PSModuleInfo module) } } - if (providers != null) + if (providers is not null) { foreach (SessionStateProviderEntry provider in providers.Values) { @@ -4937,7 +4937,7 @@ internal static Assembly LoadPSSnapInAssembly(PSSnapInInfo psSnapInInfo) s_PSSnapInTracer.TraceWarning("Not able to load assembly {0}: {1}", psSnapInInfo.AssemblyName, e.Message); } - if (assembly != null) + if (assembly is not null) { return assembly; } @@ -4980,7 +4980,7 @@ private static bool TryGetCustomAttribute(Type decoratedType, out T attribute { var attributes = decoratedType.GetCustomAttributes(inherit: false); attribute = attributes.FirstOrDefault(); - return attribute != null; + return attribute is not null; } internal static void AnalyzePSSnapInAssembly( @@ -5015,31 +5015,31 @@ internal static void AnalyzePSSnapInAssembly( { var key = pair.Key; var entry = pair.Value; - if (entry.Item1.PSSnapIn is null && psSnapInInfo != null) + if (entry.Item1.PSSnapIn is null && psSnapInInfo is not null) { entry.Item1.SetPSSnapIn(psSnapInInfo); } var newEntry = (SessionStateCmdletEntry)entry.Item1.Clone(); - if (newEntry.PSSnapIn != null && psSnapInInfo is null) + if (newEntry.PSSnapIn is not null && psSnapInInfo is null) { newEntry.SetPSSnapIn(null); } cmdlets[key] = newEntry; - if (entry.Item2 != null) + if (entry.Item2 is not null) { var aliasList = new List(); foreach (var alias in entry.Item2) { - if (alias.PSSnapIn is null && psSnapInInfo != null) + if (alias.PSSnapIn is null && psSnapInInfo is not null) { alias.SetPSSnapIn(psSnapInInfo); } var newAliasEntry = (SessionStateAliasEntry)alias.Clone(); - if (newAliasEntry.PSSnapIn != null && psSnapInInfo is null) + if (newAliasEntry.PSSnapIn is not null && psSnapInInfo is 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 is null && psSnapInInfo is not null) { entry.SetPSSnapIn(psSnapInInfo); } var newEntry = (SessionStateProviderEntry)entry.Clone(); - if (newEntry.PSSnapIn != null && psSnapInInfo is null) + if (newEntry.PSSnapIn is not null && psSnapInInfo is null) { newEntry.SetPSSnapIn(null); } @@ -5076,7 +5076,7 @@ internal static void AnalyzePSSnapInAssembly( } string assemblyPath = assembly.Location; - if (cmdlets != null || providers != null) + if (cmdlets is not null || providers is not null) { if (!s_assembliesWithModuleInitializerCache.Value.ContainsKey(assembly)) { @@ -5095,7 +5095,7 @@ internal static void AnalyzePSSnapInAssembly( s_PSSnapInTracer.WriteLine("Analyzing assembly {0} for cmdlet and providers", assemblyPath); helpFile = GetHelpFile(assemblyPath); - if (psSnapInInfo != null && psSnapInInfo.Name.Equals(InitialSessionState.CoreSnapin, StringComparison.OrdinalIgnoreCase)) + if (psSnapInInfo is not null && psSnapInInfo.Name.Equals(InitialSessionState.CoreSnapin, StringComparison.OrdinalIgnoreCase)) { InitializeCoreCmdletsAndProviders(psSnapInInfo, out cmdlets, out providers, helpFile); @@ -5160,7 +5160,7 @@ internal static void AnalyzePSSnapInAssembly( // across runspaces. When these entries are hit in the cache, // copies will be returned to ensure that the cache is never tied to a runspace. - if (cmdlets != null) + if (cmdlets is not null) { var clone = new Dictionary>>(cmdlets.Count, StringComparer.OrdinalIgnoreCase); List aliasesCloneList = null; @@ -5168,7 +5168,7 @@ internal static void AnalyzePSSnapInAssembly( foreach (var entry in cmdlets) { List aliasEntries; - if (aliases != null && aliases.TryGetValue(entry.Key, out aliasEntries)) + if (aliases is not null && aliases.TryGetValue(entry.Key, out aliasEntries)) { aliasesCloneList = new List(aliases.Count); foreach (var aliasEntry in aliasEntries) @@ -5183,7 +5183,7 @@ internal static void AnalyzePSSnapInAssembly( s_cmdletCache.Value[assembly] = clone; } - if (providers != null) + if (providers is not null) { var clone = new Dictionary(providers.Count, StringComparer.OrdinalIgnoreCase); foreach (var entry in providers) @@ -5226,7 +5226,7 @@ private static void AnalyzeModuleAssemblyWithReflection( } string cmdletName = cmdletAttribute.VerbName + "-" + cmdletAttribute.NounName; - if (cmdlets != null && cmdlets.ContainsKey(cmdletName)) + if (cmdlets is not null && cmdlets.ContainsKey(cmdletName)) { string message = StringUtil.Format(ConsoleInfoErrorStrings.PSSnapInDuplicateCmdlets, cmdletName, name); s_PSSnapInTracer.TraceError(message); @@ -5234,12 +5234,12 @@ private static void AnalyzeModuleAssemblyWithReflection( } SessionStateCmdletEntry cmdlet = new SessionStateCmdletEntry(cmdletName, type, helpFile); - if (psSnapInInfo != null) + if (psSnapInInfo is not null) { cmdlet.SetPSSnapIn(psSnapInInfo); } - if (moduleInfo != null) + if (moduleInfo is not null) { cmdlet.SetModule(moduleInfo); } @@ -5258,9 +5258,9 @@ private static void AnalyzeModuleAssemblyWithReflection( // the users of the cmdlet, instead of the author, should have control of what options applied to an alias // ('ScopedItemOptions.ReadOnly' and/or 'ScopedItemOptions.AllScopes'). var aliasEntry = new SessionStateAliasEntry(alias, cmdletName, description: string.Empty, ScopedItemOptions.None); - if (psSnapInInfo != null) { aliasEntry.SetPSSnapIn(psSnapInInfo); } + if (psSnapInInfo is not null) { aliasEntry.SetPSSnapIn(psSnapInInfo); } - if (moduleInfo != null) + if (moduleInfo is not null) { aliasEntry.SetModule(moduleInfo); } @@ -5284,7 +5284,7 @@ private static void AnalyzeModuleAssemblyWithReflection( } string providerName = providerAttribute.ProviderName; - if (providers != null && providers.ContainsKey(providerName)) + if (providers is not null && providers.ContainsKey(providerName)) { string message = StringUtil.Format(ConsoleInfoErrorStrings.PSSnapInDuplicateProviders, providerName, psSnapInInfo.Name); s_PSSnapInTracer.TraceError(message); @@ -5292,12 +5292,12 @@ private static void AnalyzeModuleAssemblyWithReflection( } SessionStateProviderEntry provider = new SessionStateProviderEntry(providerName, type, helpFile); - if (psSnapInInfo != null) + if (psSnapInInfo is not null) { provider.SetPSSnapIn(psSnapInInfo); } - if (moduleInfo != null) + if (moduleInfo is not null) { provider.SetModule(moduleInfo); } @@ -5437,7 +5437,7 @@ internal static IEnumerable GetAssemblyTypes(Assembly assembly, string nam catch (ReflectionTypeLoadException e) { string message = e.Message + "\nLoader Exceptions: \n"; - if (e.LoaderExceptions != null) + if (e.LoaderExceptions is not null) { foreach (Exception exception in e.LoaderExceptions) { diff --git a/src/System.Management.Automation/engine/InternalCommands.cs b/src/System.Management.Automation/engine/InternalCommands.cs index 72bb825cde9..99647009a2a 100644 --- a/src/System.Management.Automation/engine/InternalCommands.cs +++ b/src/System.Management.Automation/engine/InternalCommands.cs @@ -524,7 +524,7 @@ private void InitParallelParameterSet() private void ProcessParallelParameterSet() { // Validate piped InputObject - if (_inputObject != null && + if (_inputObject is not null && _inputObject.BaseObject is ScriptBlock) { WriteError( @@ -596,7 +596,7 @@ private void EndParallelParameterSet() // Check for an unexpected error from the _taskCollection handler thread and report here. var ex = _taskCollectionException; - if (ex != null) + if (ex is not null) { var msg = string.Format(CultureInfo.InvariantCulture, InternalCommandStrings.ParallelPipedInputProcessingError, ex); WriteError( @@ -640,7 +640,7 @@ private void ProcessPropertyAndMethodParameterSet() if (LanguagePrimitives.IsNull(InputObject)) { - if (_arguments != null && _arguments.Length > 0) + if (_arguments is not null && _arguments.Length > 0) { WriteError(GenerateNameParameterError("InputObject", ParserStrings.InvokeMethodOnNull, "InvokeMethodOnNull", _inputObject)); @@ -679,7 +679,7 @@ private void ProcessPropertyAndMethodParameterSet() ErrorRecord errorRecord = null; // if args exist, this is explicitly a method invocation - if (_arguments != null && _arguments.Length > 0) + if (_arguments is not null && _arguments.Length > 0) { MethodCallWithArguments(); } @@ -695,7 +695,7 @@ private void ProcessPropertyAndMethodParameterSet() // get the matched member(s) ReadOnlyPSMemberInfoCollection members = _inputObject.Members.Match(_propertyOrMethodName, PSMemberTypes.All); - Dbg.Assert(members != null, "The return value of Members.Match should never be null"); + Dbg.Assert(members is not null, "The return value of Members.Match should never be null"); if (members.Count > 1) { @@ -727,7 +727,7 @@ private void ProcessPropertyAndMethodParameterSet() { // first we check if the member is a ParameterizedProperty PSParameterizedProperty targetParameterizedProperty = member as PSParameterizedProperty; - if (targetParameterizedProperty != null) + if (targetParameterizedProperty is not null) { // should process string propertyAction = string.Format(CultureInfo.InvariantCulture, @@ -743,7 +743,7 @@ private void ProcessPropertyAndMethodParameterSet() } PSMethodInfo targetMethod = member as PSMethodInfo; - Dbg.Assert(targetMethod != null, "targetMethod should not be null here."); + Dbg.Assert(targetMethod is not null, "targetMethod should not be null here."); try { // should process @@ -767,7 +767,7 @@ private void ProcessPropertyAndMethodParameterSet() catch (Exception ex) { MethodException mex = ex as MethodException; - if (mex != null && mex.ErrorRecord != null && mex.ErrorRecord.FullyQualifiedErrorId == "MethodCountCouldNotFindBest") + if (mex is not null && mex.ErrorRecord is not null && mex.ErrorRecord.FullyQualifiedErrorId == "MethodCountCouldNotFindBest") { WriteObject(targetMethod.Value); } @@ -887,7 +887,7 @@ private void ProcessPropertyAndMethodParameterSet() } } - if (errorRecord != null) + if (errorRecord is not null) { string propertyAction = string.Format(CultureInfo.InvariantCulture, InternalCommandStrings.ForEachObjectPropertyAction, _propertyOrMethodName); @@ -922,7 +922,7 @@ private void ProcessScriptBlockParameterSet() // because it allows you to parameterize a command - for example you might allow // for actions before and after the main processing script. They could be null // by default and therefore ignored then filled in later... - if (_scripts[i] != null) + if (_scripts[i] is not null) { _scripts[i].InvokeUsingCmdlet( contextCmdlet: this, @@ -945,7 +945,7 @@ private void InitScriptBlockParameterSet() // Not using MshCommandRuntime, as those variables will be affected by ScriptCmdlet // infrastructure (wherein ScriptCmdlet modifies the global preferences). Dictionary psBoundParameters = this.MyInvocation.BoundParameters; - if (psBoundParameters != null) + if (psBoundParameters is not null) { SwitchParameter whatIf = false; SwitchParameter confirm = false; @@ -1017,7 +1017,7 @@ private void MethodCallWithArguments() _propertyOrMethodName, PSMemberTypes.Methods | PSMemberTypes.ParameterizedProperty); - Dbg.Assert(methods != null, "The return value of Members.Match should never be null."); + Dbg.Assert(methods is not null, "The return value of Members.Match should never be null."); if (methods.Count > 1) { // write error record: method ambiguous @@ -1048,7 +1048,7 @@ private void MethodCallWithArguments() else { PSMethodInfo targetMethod = methods[0] as PSMethodInfo; - Dbg.Assert(targetMethod != null, "targetMethod should not be null here."); + Dbg.Assert(targetMethod is not null, "targetMethod should not be null here."); // should process StringBuilder arglist = new StringBuilder(GetStringRepresentation(_arguments[0])); @@ -1105,7 +1105,7 @@ private static string GetStringRepresentation(object obj) if (string.IsNullOrEmpty(objInString)) { var psobj = obj as PSObject; - objInString = psobj != null ? psobj.BaseObject.GetType().FullName : obj.GetType().FullName; + objInString = psobj is not null ? psobj.BaseObject.GetType().FullName : obj.GetType().FullName; } return objInString; @@ -1123,7 +1123,7 @@ private bool GetValueFromIDictionaryInput() try { - if (hash != null && hash.Contains(_propertyOrMethodName)) + if (hash is not null && hash.Contains(_propertyOrMethodName)) { string keyAction = string.Format( CultureInfo.InvariantCulture, @@ -1155,7 +1155,7 @@ private bool GetValueFromIDictionaryInput() private void WriteToPipelineWithUnrolling(object obj) { IEnumerator objAsEnumerator = LanguagePrimitives.GetEnumerator(obj); - if (objAsEnumerator != null) + if (objAsEnumerator is not null) { WriteOutIEnumerator(objAsEnumerator); } @@ -1171,7 +1171,7 @@ private void WriteToPipelineWithUnrolling(object obj) /// Source list. private void WriteOutIEnumerator(IEnumerator list) { - if (list != null) + if (list is not null) { while (ParserOps.MoveNext(this.Context, null, list)) { @@ -2023,7 +2023,7 @@ private object GetLikeRHSOperand(object operand) /// protected override void BeginProcessing() { - if (_script != null) + if (_script is not null) { return; } @@ -2196,7 +2196,7 @@ protected override void BeginProcessing() case TokenKind.IsNot: // users might input [int], [string] as they do when using scripts var strValue = _convertedValue as string; - if (strValue != null) + if (strValue is not null) { var typeLength = strValue.Length; if (typeLength > 2 && strValue[0] == '[' && strValue[typeLength - 1] == ']') @@ -2228,7 +2228,7 @@ protected override void ProcessRecord() return; } - if (_script != null) + if (_script is not null) { object result = _script.DoInvokeReturnAsIs( useLocalScope: false, @@ -2341,7 +2341,7 @@ private object GetValue(ref bool error) IDictionary hash = target as IDictionary; try { - if (hash != null && hash.Contains(_property)) + if (hash is not null && hash.Contains(_property)) { return hash[_property]; } @@ -2474,7 +2474,7 @@ private ReadOnlyPSMemberInfoCollection GetMatchMembers() { PSMemberInfoInternalCollection results = new PSMemberInfoInternalCollection(); PSMemberInfo member = _inputObject.Members[_property]; - if (member != null) + if (member is not null) { results.Add(member); } @@ -2483,7 +2483,7 @@ private ReadOnlyPSMemberInfoCollection GetMatchMembers() } ReadOnlyPSMemberInfoCollection members = _inputObject.Members.Match(_property, PSMemberTypes.All); - Dbg.Assert(members != null, "The return value of Members.Match should never be null."); + Dbg.Assert(members is not null, "The return value of Members.Match should never be null."); return members; } } @@ -2584,13 +2584,13 @@ protected override void BeginProcessing() } else { - if (_trace >= 0 || _step != null) + if (_trace >= 0 || _step is not null) { Context.Debugger.EnableTracing(_trace, _step); } // Version 0 is the same as off - if (_strict != null) + if (_strict is not null) { Context.EngineSessionState.GlobalScope.StrictModeVersion = new Version((bool)_strict ? 1 : 0, 0); } @@ -2652,7 +2652,7 @@ public override object Transform(EngineIntrinsics engineIntrinsics, object input object version = PSObject.Base(inputData); string versionStr = version as string; - if (versionStr != null) + if (versionStr is not null) { if (versionStr.Equals("latest", StringComparison.OrdinalIgnoreCase)) { diff --git a/src/System.Management.Automation/engine/InvocationInfo.cs b/src/System.Management.Automation/engine/InvocationInfo.cs index 1871ae3c9cd..bf1bd721e42 100644 --- a/src/System.Management.Automation/engine/InvocationInfo.cs +++ b/src/System.Management.Automation/engine/InvocationInfo.cs @@ -64,20 +64,20 @@ internal InvocationInfo(CommandInfo commandInfo, IScriptExtent scriptPosition, E _scriptPosition = scriptPosition; ExecutionContext contextToUse = null; - if ((commandInfo != null) && (commandInfo.Context != null)) + if ((commandInfo is not null) && (commandInfo.Context is not null)) { contextToUse = commandInfo.Context; } - else if (context != null) + else if (context is not null) { contextToUse = context; } // Populate the history ID of this command - if (contextToUse != null) + if (contextToUse is not null) { Runspaces.LocalRunspace localRunspace = contextToUse.CurrentRunspace as Runspaces.LocalRunspace; - if (localRunspace != null && localRunspace.History != null) + if (localRunspace is not null && localRunspace.History is not null) { HistoryId = localRunspace.History.GetNextHistoryId(); } @@ -122,7 +122,7 @@ internal InvocationInfo(PSObject psObject) // object into an int[] before assigning to pipelineIterationInfo. // var list = (ArrayList)SerializationUtilities.GetPsObjectPropertyBaseObject(psObject, "InvocationInfo_PipelineIterationInfo"); - if (list != null) + if (list is not null) { PipelineIterationInfo = (int[])list.ToArray(typeof(int)); } @@ -139,7 +139,7 @@ internal InvocationInfo(PSObject psObject) Dictionary dictionary = new Dictionary(); - if (hashtable != null) + if (hashtable is not null) { foreach (DictionaryEntry entry in hashtable) { @@ -156,7 +156,7 @@ internal InvocationInfo(PSObject psObject) _unboundArguments = new List(); - if (unboundArguments != null) + if (unboundArguments is not null) { foreach (object o in unboundArguments) { @@ -167,7 +167,7 @@ internal InvocationInfo(PSObject psObject) object value = SerializationUtilities.GetPropertyValue(psObject, "SerializeExtent"); bool serializeExtent = false; - if (value != null) + if (value is not null) serializeExtent = (bool)value; if (serializeExtent) @@ -260,7 +260,7 @@ public string Line { get { - if (ScriptPosition.StartScriptPosition != null) + if (ScriptPosition.StartScriptPosition is not null) { return ScriptPosition.StartScriptPosition.Line; } @@ -372,7 +372,7 @@ internal IScriptExtent ScriptPosition { get { - if (DisplayScriptPosition != null) + if (DisplayScriptPosition is not null) { return DisplayScriptPosition; } @@ -390,7 +390,7 @@ internal IScriptExtent ScriptPosition /// internal string GetFullScript() { - return (ScriptPosition != null) && (ScriptPosition.StartScriptPosition != null) ? + return (ScriptPosition is not null) && (ScriptPosition.StartScriptPosition is not null) ? ScriptPosition.StartScriptPosition.GetFullScript() : null; } @@ -432,7 +432,7 @@ internal void ToPSObjectForRemoting(PSObject psObject) RemotingEncoder.AddNoteProperty(psObject, "InvocationInfo_UnboundArguments", () => this.UnboundArguments); ScriptExtent extent = DisplayScriptPosition as ScriptExtent; - if (extent != null) + if (extent is not null) { extent.ToPSObjectForRemoting(psObject); RemotingEncoder.AddNoteProperty(psObject, "SerializeExtent", () => true); @@ -475,7 +475,7 @@ internal static RemoteCommandInfo FromPSObjectForRemoting(PSObject psObject) object ctype = SerializationUtilities.GetPsObjectPropertyBaseObject(psObject, "CommandInfo_CommandType"); - if (ctype != null) + if (ctype is not null) { CommandTypes type = RemotingDecoder.GetPropertyValue(psObject, "CommandInfo_CommandType"); string name = RemotingDecoder.GetPropertyValue(psObject, "CommandInfo_Name"); @@ -498,7 +498,7 @@ internal static RemoteCommandInfo FromPSObjectForRemoting(PSObject psObject) /// internal static void ToPSObjectForRemoting(CommandInfo commandInfo, PSObject psObject) { - if (commandInfo != null) + if (commandInfo is not null) { RemotingEncoder.AddNoteProperty(psObject, "CommandInfo_CommandType", () => commandInfo.CommandType); RemotingEncoder.AddNoteProperty(psObject, "CommandInfo_Definition", () => commandInfo.Definition); diff --git a/src/System.Management.Automation/engine/ItemCmdletProviderInterfaces.cs b/src/System.Management.Automation/engine/ItemCmdletProviderInterfaces.cs index 80eaae1383f..28e4db3e99a 100644 --- a/src/System.Management.Automation/engine/ItemCmdletProviderInterfaces.cs +++ b/src/System.Management.Automation/engine/ItemCmdletProviderInterfaces.cs @@ -103,7 +103,7 @@ internal ItemCmdletProviderIntrinsics(SessionStateInternal sessionState) public Collection Get(string path) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -150,7 +150,7 @@ public Collection Get(string path) public Collection Get(string[] path, bool force, bool literalPath) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -194,7 +194,7 @@ public Collection Get(string[] path, bool force, bool literalPath) internal void Get(string path, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -235,7 +235,7 @@ internal void Get(string path, CmdletProviderContext context) internal object GetItemDynamicParameters(string path, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -283,7 +283,7 @@ internal object GetItemDynamicParameters(string path, CmdletProviderContext cont public Collection Set(string path, object value) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -333,7 +333,7 @@ public Collection Set(string path, object value) public Collection Set(string[] path, object value, bool force, bool literalPath) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -380,7 +380,7 @@ public Collection Set(string[] path, object value, bool force, bool li internal void Set(string path, object value, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -427,7 +427,7 @@ internal object SetItemDynamicParameters( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -472,7 +472,7 @@ internal object SetItemDynamicParameters( public Collection Clear(string path) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -519,7 +519,7 @@ public Collection Clear(string path) public Collection Clear(string[] path, bool force, bool literalPath) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -563,7 +563,7 @@ public Collection Clear(string[] path, bool force, bool literalPath) internal void Clear(string path, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -604,7 +604,7 @@ internal void Clear(string path, CmdletProviderContext context) internal object ClearItemDynamicParameters(string path, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -646,7 +646,7 @@ internal object ClearItemDynamicParameters(string path, CmdletProviderContext co public void Invoke(string path) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -687,7 +687,7 @@ public void Invoke(string path) public void Invoke(string[] path, bool literalPath) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -728,7 +728,7 @@ public void Invoke(string[] path, bool literalPath) internal void Invoke(string path, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -769,7 +769,7 @@ internal void Invoke(string path, CmdletProviderContext context) internal object InvokeItemDynamicParameters(string path, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -817,7 +817,7 @@ internal object InvokeItemDynamicParameters(string path, CmdletProviderContext c public Collection Rename(string path, string newName) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -864,7 +864,7 @@ public Collection Rename(string path, string newName) public Collection Rename(string path, string newName, bool force) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -914,7 +914,7 @@ internal void Rename( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -961,7 +961,7 @@ internal object RenameItemDynamicParameters( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1019,7 +1019,7 @@ public Collection New( object content) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1077,7 +1077,7 @@ public Collection New( bool force) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1135,7 +1135,7 @@ internal void New( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1186,7 +1186,7 @@ internal object NewItemDynamicParameters( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1233,7 +1233,7 @@ internal object NewItemDynamicParameters( public void Remove(string path, bool recurse) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1282,7 +1282,7 @@ public void Remove(string path, bool recurse) public void Remove(string[] path, bool recurse, bool force, bool literalPath) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1328,7 +1328,7 @@ internal void Remove( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1377,7 +1377,7 @@ internal object RemoveItemDynamicParameters( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1436,7 +1436,7 @@ public Collection Copy( CopyContainers copyContainers) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1499,7 +1499,7 @@ public Collection Copy( bool literalPath) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1558,7 +1558,7 @@ internal void Copy( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1610,7 +1610,7 @@ internal object CopyItemDynamicParameters( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1666,7 +1666,7 @@ internal object CopyItemDynamicParameters( public Collection Move(string path, string destination) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1724,7 +1724,7 @@ public Collection Move(string path, string destination) public Collection Move(string[] path, string destination, bool force, bool literalPath) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1773,7 +1773,7 @@ internal void Move( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1820,7 +1820,7 @@ internal object MoveItemDynamicParameters( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1861,7 +1861,7 @@ internal object MoveItemDynamicParameters( public bool Exists(string path) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1904,7 +1904,7 @@ public bool Exists(string path) public bool Exists(string path, bool force, bool literalPath) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1946,7 +1946,7 @@ internal bool Exists( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1988,7 +1988,7 @@ internal object ItemExistsDynamicParameters( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -2027,7 +2027,7 @@ internal object ItemExistsDynamicParameters( public bool IsContainer(string path) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -2068,7 +2068,7 @@ internal bool IsContainer( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object diff --git a/src/System.Management.Automation/engine/LanguagePrimitives.cs b/src/System.Management.Automation/engine/LanguagePrimitives.cs index 60d9e4531ef..fa9135b4156 100644 --- a/src/System.Management.Automation/engine/LanguagePrimitives.cs +++ b/src/System.Management.Automation/engine/LanguagePrimitives.cs @@ -509,7 +509,7 @@ private static IEnumerable TypicalEnumerable(object obj) catch (Exception innerException) { e = GetEnumerableFromIEnumerableT(obj); - if (e != null) + if (e is not null) { return e; } @@ -568,10 +568,10 @@ public static IEnumerator GetEnumerator(object obj) public static PSDataCollection GetPSDataCollection(object inputValue) { PSDataCollection result = new PSDataCollection(); - if (inputValue != null) + if (inputValue is not null) { IEnumerator e = GetEnumerator(inputValue); - if (e != null) + if (e is not null) { while (e.MoveNext()) { @@ -658,7 +658,7 @@ public static bool Equals(object first, object second, bool ignoreCase, IFormatP string firstString = first as string; string secondString; - if (firstString != null) + if (firstString is not null) { secondString = second as string ?? (string)LanguagePrimitives.ConvertTo(second, typeof(string), culture); return (culture.CompareInfo.Compare(firstString, secondString, @@ -679,7 +679,7 @@ public static bool Equals(object first, object second, bool ignoreCase, IFormatP if (firstType == typeof(char) && ignoreCase) { secondString = second as string; - if (secondString != null && secondString.Length == 1) + if (secondString is not null && secondString.Length == 1) { char firstAsUpper = culture.TextInfo.ToUpper((char)first); char secondAsUpper = culture.TextInfo.ToUpper(secondString[0]); @@ -1017,7 +1017,7 @@ public static bool IsTrue(object obj) return ((SwitchParameter)obj).ToBool(); IList objectArray = obj as IList; - if (objectArray != null) + if (objectArray is not null) { return IsTrue(objectArray); } @@ -1326,7 +1326,7 @@ internal static bool IsCimIntrinsicScalarType(TypeCode typeCode) internal static bool IsCimIntrinsicScalarType(Type type) { - Dbg.Assert(type != null, "Caller should verify type != null"); + Dbg.Assert(type is not null, "Caller should verify type is not null"); // using type code we can cover all intrinsic types from the table // on page 11 of DSP0004, except: @@ -1472,21 +1472,21 @@ internal static object GetConverter(Type type, TypeTable backupTypeTable) { object typesXmlConverter = null; ExecutionContext ecFromTLS = LocalPipeline.GetExecutionContextFromTLS(); - if (ecFromTLS != null) + if (ecFromTLS is not null) { - s_tracer.WriteLine("ecFromTLS != null"); + s_tracer.WriteLine("ecFromTLS is not null"); typesXmlConverter = ecFromTLS.TypeTable.GetTypeConverter(type.FullName); } - if ((typesXmlConverter is null) && (backupTypeTable != null)) + if ((typesXmlConverter is null) && (backupTypeTable is not null)) { s_tracer.WriteLine("Using provided TypeTable to get the type converter"); typesXmlConverter = backupTypeTable.GetTypeConverter(type.FullName); } - if (typesXmlConverter != null) + if (typesXmlConverter is not null) { - s_tracer.WriteLine("typesXmlConverter != null"); + s_tracer.WriteLine("typesXmlConverter is not null"); return typesXmlConverter; } @@ -1750,7 +1750,7 @@ public static object ConvertTo(object valueToConvert, Type resultType, IFormatPr /// Converted value. public static object ConvertPSObjectToType(PSObject valueToConvert, Type resultType, bool recursion, IFormatProvider formatProvider, bool ignoreUnknownMembers) { - if (valueToConvert != null) + if (valueToConvert is not null) { ConstructorInfo toConstructor = resultType.GetConstructor(Type.EmptyTypes); ConvertViaNoArgumentConstructor noArgumentConstructorConverter = new ConvertViaNoArgumentConstructor(toConstructor, resultType); @@ -2094,7 +2094,7 @@ public override object ConvertFrom(object sourceValue, Type destinationType, IFo protected static object BaseConvertFrom(object sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase, bool multipleValues) { - Diagnostics.Assert(sourceValue != null, "the type converter has a special case for null source values"); + Diagnostics.Assert(sourceValue is not null, "the type converter has a special case for null source values"); string sourceValueString = sourceValue as string; if (sourceValueString is null) { @@ -2196,7 +2196,7 @@ protected static object BaseConvertFrom(object sourceValue, Type destinationType { string name = names[j]; - if (fromValuePattern != null) + if (fromValuePattern is not null) { if (!fromValuePattern.IsMatch(name)) continue; @@ -2585,10 +2585,10 @@ private static bool IsCustomTypeConversion(object valueToConvert, // first using ConvertTo for the original type object valueConverter = GetConverter(originalType, backupTypeTable); - if ((valueConverter != null)) + if ((valueConverter is not null)) { TypeConverter valueTypeConverter = valueConverter as TypeConverter; - if (valueTypeConverter != null) + if (valueTypeConverter is not null) { typeConversion.WriteLine("Original type's converter is TypeConverter."); if (valueTypeConverter.CanConvertTo(resultType)) @@ -2614,7 +2614,7 @@ private static bool IsCustomTypeConversion(object valueToConvert, } PSTypeConverter valuePSTypeConverter = valueConverter as PSTypeConverter; - if (valuePSTypeConverter != null) + if (valuePSTypeConverter is not null) { typeConversion.WriteLine("Original type's converter is PSTypeConverter."); PSObject psValueToConvert = PSObject.AsPSObject(valueToConvert); @@ -2645,10 +2645,10 @@ private static bool IsCustomTypeConversion(object valueToConvert, // now ConvertFrom for the destination type valueConverter = GetConverter(resultType, backupTypeTable); - if (valueConverter != null) + if (valueConverter is not null) { TypeConverter valueTypeConverter = valueConverter as TypeConverter; - if (valueTypeConverter != null) + if (valueTypeConverter is not null) { typeConversion.WriteLine("Destination type's converter is TypeConverter that can convert from originalType."); if (valueTypeConverter.CanConvertFrom(originalType)) @@ -2674,7 +2674,7 @@ private static bool IsCustomTypeConversion(object valueToConvert, } PSTypeConverter valuePSTypeConverter = valueConverter as PSTypeConverter; - if (valuePSTypeConverter != null) + if (valuePSTypeConverter is not null) { typeConversion.WriteLine("Destination type's converter is PSTypeConverter."); PSObject psValueToConvert = PSObject.AsPSObject(valueToConvert); @@ -2901,7 +2901,7 @@ private static object ConvertStringToInteger(object valueToConvert, TypeTable backupTable) { var strToConvert = valueToConvert as string; - Diagnostics.Assert(strToConvert != null, "Value to convert must be a string"); + Diagnostics.Assert(strToConvert is not null, "Value to convert must be a string"); Diagnostics.Assert(IsNumeric(GetTypeCode(resultType)), "Result type must be numeric"); if (strToConvert.Length == 0) @@ -2928,7 +2928,7 @@ private static object ConvertStringToInteger(object valueToConvert, { // This catch has one extra reason to be generic (Exception e). // integerConverter.ConvertFrom warps its exceptions in a System.Exception. - if (e.InnerException != null) + if (e.InnerException is not null) { e = e.InnerException; } @@ -3085,7 +3085,7 @@ private static bool ConvertClassToBool(object valueToConvert, TypeTable backupTable) { typeConversion.WriteLine("Converting ref to boolean."); - return valueToConvert != null; + return valueToConvert is not null; } private static bool ConvertValueToBool(object valueToConvert, @@ -3281,7 +3281,7 @@ private static string ConvertNumericToString(object valueToConvert, IFormatProvider formatProvider, TypeTable backupTable) { - if (originalValueToConvert != null && originalValueToConvert.TokenText != null) + if (originalValueToConvert is not null && originalValueToConvert.TokenText is not null) { return originalValueToConvert.TokenText; } @@ -3358,7 +3358,7 @@ private static PSReference ConvertToPSReference(object valueToConvert, { typeConversion.WriteLine("Converting to PSReference."); - Dbg.Assert(valueToConvert != null, "[ref]$null cast should be handler earlier with a separate ConvertNullToPSReference method"); + Dbg.Assert(valueToConvert is not null, "[ref]$null cast should be handler earlier with a separate ConvertNullToPSReference method"); return PSReference.CreateInstance(valueToConvert, valueToConvert.GetType()); } @@ -3483,7 +3483,7 @@ private static object ConvertScalarToArray(object valueToConvert, { typeConversion.WriteLine("Value to convert is scalar."); - if (originalValueToConvert != null && originalValueToConvert.TokenText != null) + if (originalValueToConvert is not null && originalValueToConvert.TokenText is not null) { valueToConvert = originalValueToConvert; } @@ -3625,7 +3625,7 @@ private static object ConvertEnumerableToEnum(object valueToConvert, // then convert the enum back to a string and finally append it to the string builder to // preserve consistent semantics between quoted and unquoted lists... object tempResult = ConvertTo(e.Current, resultType, recursion, formatProvider, backupTable); - if (tempResult != null) + if (tempResult is not null) { sbResult.Append(tempResult.ToString()); } @@ -3842,7 +3842,7 @@ internal object Convert(object valueToConvert, { // typeof(Array).IsAssignableFrom(typeof(object[])) == true array = valueToConvert as Array; - listSize = array != null ? array.Length : 1; + listSize = array is not null ? array.Length : 1; } resultAsList = ListCtorLambda(listSize); @@ -3912,7 +3912,7 @@ private class ConvertViaNoArgumentConstructor internal ConvertViaNoArgumentConstructor(ConstructorInfo constructor, Type type) { - var newExpr = (constructor != null) ? Expression.New(constructor) : Expression.New(type); + var newExpr = (constructor is not null) ? Expression.New(constructor) : Expression.New(type); _constructor = Expression.Lambda>(newExpr.Cast(typeof(object))).Compile(); } @@ -3947,7 +3947,7 @@ internal object Convert(object valueToConvert, { result = _constructor(); var psobject = valueToConvert as PSObject; - if (psobject != null) + if (psobject is not null) { // Use PSObject properties to perform conversion. SetObjectProperties(result, psobject, resultType, CreateMemberNotFoundError, CreateMemberSetValueError, formatProvider, recursion, ignoreUnknownMembers); @@ -4073,7 +4073,7 @@ private static object ConvertNumericIConvertible(object valueToConvert, { // If the original object was a number, then try and do a conversion on the string // equivalent of that number... - if (originalValueToConvert != null && originalValueToConvert.TokenText != null) + if (originalValueToConvert is not null && originalValueToConvert.TokenText is not null) { return LanguagePrimitives.ConvertTo(originalValueToConvert.TokenText, resultType, recursion, formatProvider, backupTable); @@ -4103,7 +4103,7 @@ internal object Convert(object valueToConvert, { object result = null; - if (tryfirstConverter != null) + if (tryfirstConverter is not null) { try { @@ -4120,7 +4120,7 @@ internal object Convert(object valueToConvert, return result; } - if (fallbackConverter != null) + if (fallbackConverter is not null) { return fallbackConverter(valueToConvert, resultType, recursion, originalValueToConvert, formatProvider, backupTable); } @@ -4551,7 +4551,7 @@ internal static PSObject SetObjectProperties(object o, PSObject psObject, Type r { object baseObj = PSObject.Base(psObject); var dictionary = baseObj as IDictionary; - if (dictionary != null) + if (dictionary is not null) { // Win8:649519 return SetObjectProperties(o, dictionary, resultType, memberNotFoundErrorAction, memberSetValueErrorAction, enableMethodCall: false); @@ -4560,7 +4560,7 @@ internal static PSObject SetObjectProperties(object o, PSObject psObject, Type r { // Support PSObject to Strong type conversion. PSObject psBaseObject = baseObj as PSObject; - if (psBaseObject != null) + if (psBaseObject is not null) { Dictionary properties = new Dictionary(); foreach (var item in psBaseObject.Properties) @@ -4595,24 +4595,24 @@ internal static PSObject SetObjectProperties(object o, IDictionary properties, T internal static PSObject SetObjectProperties(object o, IDictionary properties, Type resultType, MemberNotFoundError memberNotFoundErrorAction, MemberSetValueError memberSetValueErrorAction, bool enableMethodCall, IFormatProvider formatProvider, bool recursion = false, bool ignoreUnknownMembers = false) { PSObject pso = PSObject.AsPSObject(o); - if (properties != null) + if (properties is not null) { foreach (DictionaryEntry prop in properties) { PSMethodInfo method = enableMethodCall ? pso.Methods[prop.Key.ToString()] : null; try { - if (method != null) + if (method is not null) { method.Invoke(new object[] { prop.Value }); } else { PSPropertyInfo property = pso.Properties[prop.Key.ToString()]; - if (property != null) + if (property is not null) { object propValue = prop.Value; - if (recursion && prop.Value != null) + if (recursion && prop.Value is not null) { Type propType; if (TypeResolver.TryResolveType(property.TypeNameOfValue, out propType)) @@ -4622,7 +4622,7 @@ internal static PSObject SetObjectProperties(object o, IDictionary properties, T try { PSObject propertyValue = prop.Value as PSObject; - if (propertyValue != null) + if (propertyValue is not null) { propValue = LanguagePrimitives.ConvertPSObjectToType(propertyValue, propType, recursion, formatProvider, ignoreUnknownMembers); } @@ -4650,7 +4650,7 @@ internal static PSObject SetObjectProperties(object o, IDictionary properties, T { var key = prop.Key as string; var value = prop.Value as string; - if (key != null && value != null && key.Equals("PSTypeName", StringComparison.OrdinalIgnoreCase)) + if (key is not null && value is not null && key.Equals("PSTypeName", StringComparison.OrdinalIgnoreCase)) { pso.TypeNames.Insert(0, value); } @@ -4684,7 +4684,7 @@ private static string GetAvailableProperties(PSObject pso) StringBuilder availableProperties = new StringBuilder(); bool first = true; - if (pso != null && pso.Properties != null) + if (pso is not null && pso.Properties is not null) { foreach (PSPropertyInfo p in pso.Properties) { @@ -4727,7 +4727,7 @@ internal static IConversionData FigureConversion(object valueToConvert, Type res return data; } - if (valueAsPsObj != null) + if (valueAsPsObj is not null) { debase = true; @@ -4868,7 +4868,7 @@ private static IConversionData FigureLanguageConversion(Type fromType, Type toTy valueDependentRank = ConversionRank.None; Type underlyingType = Nullable.GetUnderlyingType(toType); - if (underlyingType != null) + if (underlyingType is not null) { IConversionData nullableConversion = FigureConversion(fromType, underlyingType); if (nullableConversion.Rank != ConversionRank.None) @@ -5199,7 +5199,7 @@ private static PSConverter FigureParseConversion(Type fromType, Type toT typeConversion.WriteLine("Exception finding Parse method with CultureInfo: \"{0}\".", e.Message); } - if (parse != null) + if (parse is not null) { ConvertViaParseMethod converter = new ConvertViaParseMethod(); converter.parse = parse; @@ -5219,7 +5219,7 @@ private static PSConverter FigureParseConversion(Type fromType, Type toT typeConversion.WriteLine("Exception finding Parse method: \"{0}\".", e.Message); } - if (parse != null) + if (parse is not null) { ConvertViaParseMethod converter = new ConvertViaParseMethod(); converter.parse = parse; @@ -5272,7 +5272,7 @@ internal static Tuple, ConversionRank> FigureIEnumerableCons if (typeof(Array) == fromType || typeof(object[]) == fromType || elementType.IsAssignableFrom(fromType) || // WinBlue: 423899 : To support scenario like [list[int]]"4" - (FigureConversion(fromType, elementType) != null)) + (FigureConversion(fromType, elementType) is not null)) { isScalar = elementType.IsAssignableFrom(fromType); ConstructorInfo[] ctors = toType.GetConstructors(); @@ -5489,7 +5489,7 @@ internal static PSConverter FigureCastConversion(Type fromType, Type toT } } - if (castOperator != null) + if (castOperator is not null) { rank = castOperator.Name.Equals("op_Implicit", StringComparison.OrdinalIgnoreCase) ? ConversionRank.ImplicitCast : ConversionRank.ExplicitCast; @@ -5538,7 +5538,7 @@ internal class InternalPSObject : PSObject { } internal static IConversionData FigureConversion(Type fromType, Type toType) { IConversionData data = GetConversionData(fromType, toType); - if (data != null) + if (data is not null) { return data; } @@ -5582,7 +5582,7 @@ internal static IConversionData FigureConversion(Type fromType, Type toType) { var context = LocalPipeline.GetExecutionContextFromTLS(); - if ((context != null) && (context.LanguageMode == PSLanguageMode.ConstrainedLanguage)) + if ((context is not null) && (context.LanguageMode == PSLanguageMode.ConstrainedLanguage)) { if ((toType != typeof(object)) && (toType != typeof(object[])) && @@ -5607,12 +5607,12 @@ internal static IConversionData FigureConversion(Type fromType, Type toType) PSConverter valueDependentConversion = null; ConversionRank valueDependentRank = ConversionRank.None; IConversionData conversionData = FigureLanguageConversion(fromType, toType, out valueDependentConversion, out valueDependentRank); - if (conversionData != null) + if (conversionData is not null) { return conversionData; } - rank = valueDependentConversion != null ? ConversionRank.Language : ConversionRank.None; + rank = valueDependentConversion is not null ? ConversionRank.Language : ConversionRank.None; converter = FigureParseConversion(fromType, toType); if (converter is null) { @@ -5655,7 +5655,7 @@ internal static IConversionData FigureConversion(Type fromType, Type toType) // So, we need to check only for the first condition ConstructorInfo resultConstructor = toType.GetConstructor(Type.EmptyTypes); - if (resultConstructor != null || (toType.IsValueType && !toType.IsPrimitive)) + if (resultConstructor is not null || (toType.IsValueType && !toType.IsPrimitive)) { ConvertViaNoArgumentConstructor noArgumentConstructorConverter = new ConvertViaNoArgumentConstructor(resultConstructor, toType); converter = noArgumentConstructorConverter.Convert; @@ -5682,7 +5682,7 @@ internal static IConversionData FigureConversion(Type fromType, Type toType) if (converter is null) { var tuple = FigureIEnumerableConstructorConversion(fromType, toType); - if (tuple != null) + if (tuple is not null) { converter = tuple.Item1; rank = tuple.Item2; @@ -5695,7 +5695,7 @@ internal static IConversionData FigureConversion(Type fromType, Type toType) } if (TypeConverterPossiblyExists(fromType) || TypeConverterPossiblyExists(toType) - || (converter != null && valueDependentConversion != null)) + || (converter is not null && valueDependentConversion is not null)) { ConvertCheckingForCustomConverter customConverter = new ConvertCheckingForCustomConverter(); customConverter.tryfirstConverter = valueDependentConversion; @@ -5710,7 +5710,7 @@ internal static IConversionData FigureConversion(Type fromType, Type toType) rank = ConversionRank.Custom; } } - else if (valueDependentConversion != null) + else if (valueDependentConversion is not null) { converter = valueDependentConversion; rank = valueDependentRank; @@ -5730,12 +5730,12 @@ internal class Null { }; private static IConversionData FigureConversionFromNull(Type toType) { IConversionData data = GetConversionData(typeof(Null), toType); - if (data != null) + if (data is not null) { return data; } - if (Nullable.GetUnderlyingType(toType) != null) + if (Nullable.GetUnderlyingType(toType) is not null) { return CacheConversion(typeof(Null), toType, LanguagePrimitives.ConvertNullToNullable, ConversionRank.NullToValue); } @@ -5756,7 +5756,7 @@ internal static string ObjectToTypeNameString(object o) PSObject pso = PSObject.AsPSObject(o); var typeNames = pso.InternalTypeNames; - if ((typeNames != null) && (typeNames.Count > 0)) + if ((typeNames is not null) && (typeNames.Count > 0)) { return typeNames[0]; } diff --git a/src/System.Management.Automation/engine/ManagementObjectAdapter.cs b/src/System.Management.Automation/engine/ManagementObjectAdapter.cs index f308da79615..b5eb46a4111 100644 --- a/src/System.Management.Automation/engine/ManagementObjectAdapter.cs +++ b/src/System.Management.Automation/engine/ManagementObjectAdapter.cs @@ -100,13 +100,13 @@ private IEnumerable GetTypeNameHierarchyFromDerivation(ManagementBaseObj // the immediate parent class, the next is its parent, and so on; the last element // is the base class. PropertyData derivationData = managementObj.SystemProperties["__Derivation"]; - if (derivationData != null) + if (derivationData is not null) { Dbg.Assert(derivationData.IsArray, "__Derivation must be a string array as per MSDN documentation"); // give the typenames based on NameSpace + __Derivation string[] typeHierarchy = PropertySetAndMethodArgumentConvertTo(derivationData.Value, typeof(string[]), CultureInfo.InvariantCulture) as string[]; - if (typeHierarchy != null) + if (typeHierarchy is not null) { foreach (string t in typeHierarchy) { @@ -181,7 +181,7 @@ protected override T GetMember(object obj, string memberName) PSProperty property = DoGetProperty(mgmtObject, memberName); - if (typeof(T).IsAssignableFrom(typeof(PSProperty)) && property != null) + if (typeof(T).IsAssignableFrom(typeof(PSProperty)) && property is not null) { return property as T; } @@ -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 is not null && property is null) { return returnValue; } @@ -226,7 +226,7 @@ protected override T GetFirstMemberOrDefault(object obj, MemberNamePredicate protected override PSMemberInfoInternalCollection GetMembers(object obj) { // obj should never be null - Diagnostics.Assert(obj != null, "Input object is null"); + Diagnostics.Assert(obj is not null, "Input object is null"); ManagementBaseObject wmiObject = (ManagementBaseObject)obj; PSMemberInfoInternalCollection returnValue = new PSMemberInfoInternalCollection(); @@ -245,7 +245,7 @@ protected override PSMemberInfoInternalCollection GetMembers(object obj) protected override object MethodInvoke(PSMethod method, object[] arguments) { ManagementObject mgmtObject = method.baseObject as ManagementObject; - Diagnostics.Assert(mgmtObject != null, + Diagnostics.Assert(mgmtObject is not null, "Object is not of ManagementObject type"); WMIMethodCacheEntry methodEntry = (WMIMethodCacheEntry)method.adapterData; @@ -386,7 +386,7 @@ protected override void PropertySet(PSProperty property, object setValue, bool c PropertyData pd = property.adapterData as PropertyData; - if ((convertIfPossible) && (setValue != null)) + if ((convertIfPossible) && (setValue is not null)) { // Convert only if value is not null Type paramType = GetDotNetType(pd); @@ -460,7 +460,7 @@ protected static CacheTable GetInstanceMethodTable(ManagementBaseObject wmiObjec string key = string.Format(CultureInfo.InvariantCulture, "{0}#{1}", classPath.Path, staticBinding.ToString()); typeTable = (CacheTable)s_instanceMethodCacheTable[key]; - if (typeTable != null) + if (typeTable is not null) { tracer.WriteLine("Returning method information from internal cache"); return typeTable; @@ -505,9 +505,9 @@ protected static CacheTable GetInstanceMethodTable(ManagementBaseObject wmiObjec /// private static void PopulateMethodTable(ManagementClass mgmtClass, CacheTable methodTable, bool staticBinding) { - Dbg.Assert(mgmtClass != null, "ManagementClass cannot be null in this method"); + Dbg.Assert(mgmtClass is not null, "ManagementClass cannot be null in this method"); MethodDataCollection mgmtMethods = mgmtClass.Methods; - if (mgmtMethods != null) + if (mgmtMethods is not null) { ManagementPath classPath = mgmtClass.ClassPath; // new operation will never fail @@ -546,7 +546,7 @@ private static ManagementClass CreateClassFrmObject(ManagementBaseObject mgmtBas // inherit ManagementObject properties ManagementObject mgmtObject = mgmtBaseObject as ManagementObject; - if (mgmtObject != null) + if (mgmtObject is not null) { mgmtClass.Scope = mgmtObject.Scope; mgmtClass.Options = mgmtObject.Options; @@ -600,7 +600,7 @@ protected static string GetEmbeddedObjectTypeName(PropertyData pData) /// A string representing dotnet type. protected static Type GetDotNetType(PropertyData pData) { - Diagnostics.Assert(pData != null, + Diagnostics.Assert(pData is not null, "Input PropertyData should not be null"); tracer.WriteLine("Getting DotNet Type for CimType : {0}", pData.Type); @@ -809,7 +809,7 @@ internal static void UpdateParameters(ManagementBaseObject parameters, /// internal static MethodInformation GetMethodInformation(MethodData mData) { - Diagnostics.Assert(mData != null, "MethodData should not be null"); + Diagnostics.Assert(mData is not null, "MethodData should not be null"); // Get Method parameters var parameters = new SortedList(); @@ -961,7 +961,7 @@ internal class ManagementClassApdapter : BaseWMIAdapter protected override void AddAllProperties(ManagementBaseObject wmiObject, PSMemberInfoInternalCollection members) { - if (wmiObject.SystemProperties != null) + if (wmiObject.SystemProperties is not null) { foreach (PropertyData property in wmiObject.SystemProperties) { @@ -972,7 +972,7 @@ protected override void AddAllProperties(ManagementBaseObject wmiObject, protected override PSProperty DoGetProperty(ManagementBaseObject wmiObject, string propertyName) { - if (wmiObject.SystemProperties != null) + if (wmiObject.SystemProperties is not null) { foreach (PropertyData property in wmiObject.SystemProperties) { @@ -1024,7 +1024,7 @@ protected override object InvokeManagementMethod(ManagementObject wmiObject, protected override void AddAllMethods(ManagementBaseObject wmiObject, PSMemberInfoInternalCollection members) { - Diagnostics.Assert((wmiObject != null) && (members != null), + Diagnostics.Assert((wmiObject is not null) && (members is not null), "Input arguments should not be null."); if (!typeof(T).IsAssignableFrom(typeof(PSMethod))) @@ -1079,7 +1079,7 @@ protected override T GetFirstOrDefaultProperty(ManagementBaseObject wmiObject return null; } - if (wmiObject.SystemProperties != null) + if (wmiObject.SystemProperties is not null) { foreach (PropertyData property in wmiObject.SystemProperties) { @@ -1125,7 +1125,7 @@ protected override void AddAllProperties(ManagementBaseObject wmiObject, // Add System properties base.AddAllProperties(wmiObject, members); - if (wmiObject.Properties != null) + if (wmiObject.Properties is not null) { foreach (PropertyData property in wmiObject.Properties) { @@ -1141,7 +1141,7 @@ protected override PSProperty DoGetProperty(ManagementBaseObject wmiObject, stri // First check whether we have any Class properties by this name PSProperty returnValue = base.DoGetProperty(wmiObject, propertyName); - if (returnValue != null) + if (returnValue is not null) { return returnValue; } @@ -1212,7 +1212,7 @@ protected override object InvokeManagementMethod(ManagementObject obj, string me protected override void AddAllMethods(ManagementBaseObject wmiObject, PSMemberInfoInternalCollection members) { - Diagnostics.Assert((wmiObject != null) && (members != null), + Diagnostics.Assert((wmiObject is not null) && (members is not null), "Input arguments should not be null."); if (!typeof(T).IsAssignableFrom(typeof(PSMethod))) diff --git a/src/System.Management.Automation/engine/MergedCommandParameterMetadata.cs b/src/System.Management.Automation/engine/MergedCommandParameterMetadata.cs index 6caadcc6574..a045cd09902 100644 --- a/src/System.Management.Automation/engine/MergedCommandParameterMetadata.cs +++ b/src/System.Management.Automation/engine/MergedCommandParameterMetadata.cs @@ -398,10 +398,10 @@ private static string RetrieveParameterNameForAlias( IDictionary dict) { MergedCompiledCommandParameter mergedParam = dict[key]; - if (mergedParam != null) + if (mergedParam is not null) { CompiledCommandParameter compiledParam = mergedParam.Parameter; - if (compiledParam != null) + if (compiledParam is not null) { if (!string.IsNullOrEmpty(compiledParam.Name)) return compiledParam.Name; @@ -649,7 +649,7 @@ internal MergedCompiledCommandParameter( CompiledCommandParameter parameter, ParameterBinderAssociation binderAssociation) { - Diagnostics.Assert(parameter != null, "caller to verify parameter is not null"); + Diagnostics.Assert(parameter is not null, "caller to verify parameter is not null"); this.Parameter = parameter; this.BinderAssociation = binderAssociation; } diff --git a/src/System.Management.Automation/engine/Modules/AnalysisCache.cs b/src/System.Management.Automation/engine/Modules/AnalysisCache.cs index be8e25359d9..7fffb853714 100644 --- a/src/System.Management.Automation/engine/Modules/AnalysisCache.cs +++ b/src/System.Management.Automation/engine/Modules/AnalysisCache.cs @@ -81,7 +81,7 @@ internal static ConcurrentDictionary GetExportedCommands(s } } - if (result != null) + if (result is not null) { s_cacheData.QueueSerialization(); ModuleIntrinsics.Tracer.WriteLine("Returning {0} exported commands.", result.Count); @@ -101,7 +101,7 @@ private static ConcurrentDictionary AnalyzeManifestModule( try { var moduleManifestProperties = PsUtils.GetModuleManifestProperties(modulePath, PsUtils.FastModuleManifestAnalysisPropertyNames); - if (moduleManifestProperties != null) + if (moduleManifestProperties is not null) { if (!Configuration.PowerShellConfig.Instance.IsImplicitWinCompatEnabled() && ModuleIsEditionIncompatible(modulePath, moduleManifestProperties)) { @@ -162,7 +162,7 @@ private static ConcurrentDictionary AnalyzeManifestModule( ModuleIntrinsics.Tracer.WriteLine("Exception on fast-path analysis of module {0}", modulePath); } - if (etwEnabled) CommandDiscoveryEventSource.Log.ModuleManifestAnalysisResult(modulePath, result != null); + if (etwEnabled) CommandDiscoveryEventSource.Log.ModuleManifestAnalysisResult(modulePath, result is not null); return result ?? AnalyzeTheOldWay(modulePath, context, lastWriteTime); } @@ -241,18 +241,18 @@ internal static bool ModuleAnalysisViaGetModuleRequired(object modulePathObj, bo private static bool CheckModulesTypesInManifestAgainstExportedCommands(Hashtable moduleManifestProperties, bool hadCmdlets, bool hadFunctions, bool hadAliases) { var rootModule = moduleManifestProperties["RootModule"]; - if (rootModule != null && ModuleAnalysisViaGetModuleRequired(rootModule, hadCmdlets, hadFunctions, hadAliases)) + if (rootModule is not null && ModuleAnalysisViaGetModuleRequired(rootModule, hadCmdlets, hadFunctions, hadAliases)) return true; var moduleToProcess = moduleManifestProperties["ModuleToProcess"]; - if (moduleToProcess != null && ModuleAnalysisViaGetModuleRequired(moduleToProcess, hadCmdlets, hadFunctions, hadAliases)) + if (moduleToProcess is not null && ModuleAnalysisViaGetModuleRequired(moduleToProcess, hadCmdlets, hadFunctions, hadAliases)) return true; var nestedModules = moduleManifestProperties["NestedModules"]; - if (nestedModules != null) + if (nestedModules is not null) { var nestedModule = nestedModules as string; - if (nestedModule != null) + if (nestedModule is not null) { return ModuleAnalysisViaGetModuleRequired(nestedModule, hadCmdlets, hadFunctions, hadAliases); } @@ -301,13 +301,13 @@ private static bool AddPsd1EntryToResult(ConcurrentDictionary result, object value, CommandTypes commandTypeToAdd, ref bool sawWildcard) { string command = value as string; - if (command != null) + if (command is not null) { return AddPsd1EntryToResult(result, command, commandTypeToAdd, ref sawWildcard); } object[] commands = value as object[]; - if (commands != null) + if (commands is not null) { foreach (var o in commands) { @@ -510,7 +510,7 @@ internal static void CacheModuleExports(PSModuleInfo module, ExecutionContext co // First see if the existing module info is sufficient. GetModuleEntryFromCache does LastWriteTime // verification, so this will also return nothing if the cache is out of date or corrupt. - if (moduleCacheEntry != null) + if (moduleCacheEntry is not null) { bool needToUpdate = false; @@ -774,7 +774,7 @@ private void Serialize(string filename) ModuleIntrinsics.Tracer.WriteLine("Exception checking module analysis cache {0}: {1} ", filename, e.Message); } - if (fromOtherProcess != null) + if (fromOtherProcess is not null) { // We should merge with what another process wrote so we don't clobber useful analysis foreach (var otherEntryPair in fromOtherProcess.Entries) diff --git a/src/System.Management.Automation/engine/Modules/ExportModuleMemberCommand.cs b/src/System.Management.Automation/engine/Modules/ExportModuleMemberCommand.cs index 7dc91d76776..24702b004da 100644 --- a/src/System.Management.Automation/engine/Modules/ExportModuleMemberCommand.cs +++ b/src/System.Management.Automation/engine/Modules/ExportModuleMemberCommand.cs @@ -34,7 +34,7 @@ public string[] Function // Create the list of patterns to match at parameter bind time // so errors will be reported before loading the module... _functionPatterns = new List(); - if (_functionList != null) + if (_functionList is not null) { foreach (string pattern in _functionList) { @@ -63,7 +63,7 @@ public string[] Cmdlet // Create the list of patterns to match at parameter bind time // so errors will be reported before loading the module... _cmdletPatterns = new List(); - if (_cmdletList != null) + if (_cmdletList is not null) { foreach (string pattern in _cmdletList) { @@ -92,7 +92,7 @@ public string[] Variable // Create the list of patterns to match at parameter bind time // so errors will be reported before loading the module... _variablePatterns = new List(); - if (_variableExportList != null) + if (_variableExportList is not null) { foreach (string pattern in _variableExportList) { @@ -121,7 +121,7 @@ public string[] Alias // Create the list of patterns to match at parameter bind time // so errors will be reported before loading the module... _aliasPatterns = new List(); - if (_aliasExportList != null) + if (_aliasExportList is not null) { foreach (string pattern in _aliasExportList) { @@ -152,7 +152,7 @@ protected override void ProcessRecord() // Prevent script injection attack by disallowing ExportModuleMemberCommand to export module members across // language boundaries. This will prevent injected untrusted script from exporting private trusted module functions. - if (Context.EngineSessionState.Module?.LanguageMode != null && + if (Context.EngineSessionState.Module?.LanguageMode is not null && Context.LanguageMode != Context.EngineSessionState.Module.LanguageMode) { var se = new PSSecurityException(Modules.CannotExportMembersAccrossLanguageBoundaries); diff --git a/src/System.Management.Automation/engine/Modules/GetModuleCommand.cs b/src/System.Management.Automation/engine/Modules/GetModuleCommand.cs index 4704e24eb47..0361ed794ca 100644 --- a/src/System.Management.Automation/engine/Modules/GetModuleCommand.cs +++ b/src/System.Management.Automation/engine/Modules/GetModuleCommand.cs @@ -141,7 +141,7 @@ public SwitchParameter SkipEditionCheck private IEnumerable GetAvailableViaPsrpSessionCore(string[] moduleNames, Runspace remoteRunspace) { - Dbg.Assert(remoteRunspace != null, "Caller should verify remoteRunspace != null"); + Dbg.Assert(remoteRunspace is not null, "Caller should verify remoteRunspace is not null"); using (var powerShell = System.Management.Automation.PowerShell.Create()) { @@ -154,7 +154,7 @@ private IEnumerable GetAvailableViaPsrpSessionCore(string[] module powerShell.AddParameter("Refresh", true); } - if (moduleNames != null) + if (moduleNames is not null) { powerShell.AddParameter("Name", moduleNames); } @@ -265,7 +265,7 @@ private IEnumerable GetAvailableViaCimSessionCore(IEnumerable remoteModuleInfos = remoteModules .Select(cimModule => this.ConvertCimModuleInfoToPSModuleInfo(cimModule, cimSession.ComputerName)) - .Where(moduleInfo => moduleInfo != null); + .Where(moduleInfo => moduleInfo is not null); return remoteModuleInfos; } @@ -349,7 +349,7 @@ protected override void ProcessRecord() { // Name and FullyQualifiedName should not be specified at the same time. // Throw out terminating error if this is the case. - if ((Name != null) && (FullyQualifiedName != null)) + if ((Name is not null) && (FullyQualifiedName is not null)) { string errMsg = StringUtil.Format(SessionStateStrings.GetContent_TailAndHeadCannotCoexist, "Name", "FullyQualifiedName"); ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "NameAndFullyQualifiedNameCannotBeSpecifiedTogether", ErrorCategory.InvalidOperation, null); @@ -369,13 +369,13 @@ protected override void ProcessRecord() } var strNames = new List(); - if (Name != null) + if (Name is not null) { strNames.AddRange(Name); } var moduleSpecTable = new Dictionary(StringComparer.OrdinalIgnoreCase); - if (FullyQualifiedName != null) + if (FullyQualifiedName is not null) { for (int modSpecIndex = 0; modSpecIndex < FullyQualifiedName.Length; modSpecIndex++) { @@ -436,7 +436,7 @@ protected override void ProcessRecord() private void AssertNameDoesNotResolveToAPath(string[] names, string stringFormat, string resourceId) { - if (names != null) + if (names is not null) { foreach (var n in names) { @@ -524,7 +524,7 @@ private IEnumerable FilterModulesForEditionAndSpecification( modules = modules.Where(module => module.CompatiblePSEditions.Contains(PSEdition, StringComparer.OrdinalIgnoreCase)); } - if (moduleSpecificationTable != null && moduleSpecificationTable.Count > 0) + if (moduleSpecificationTable is not null && moduleSpecificationTable.Count > 0) { modules = FilterModulesForSpecificationMatch(modules, moduleSpecificationTable); } @@ -543,7 +543,7 @@ private static IEnumerable FilterModulesForSpecificationMatch( IEnumerable modules, IDictionary moduleSpecificationTable) { - Dbg.Assert(moduleSpecificationTable != null, $"Caller to verify that {nameof(moduleSpecificationTable)} is not null"); + Dbg.Assert(moduleSpecificationTable is not null, $"Caller to verify that {nameof(moduleSpecificationTable)} is not null"); Dbg.Assert(moduleSpecificationTable.Count != 0, $"Caller to verify that {nameof(moduleSpecificationTable)} is not empty"); foreach (PSModuleInfo module in modules) diff --git a/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs b/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs index cbbe3186684..0fced33cb10 100644 --- a/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs +++ b/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs @@ -503,12 +503,12 @@ private void ImportModule_ViaLocalModuleInfo(ImportModuleOptions importModuleOpt // Add it to the all module tables AddModuleToModuleTables(this.Context, this.TargetSessionState.Internal, moduleToProcess); - if (moduleToProcess.SessionState != null) + if (moduleToProcess.SessionState is not null) { ImportModuleMembers(moduleToProcess, this.BasePrefix, importModuleOptions); } - if (BaseAsCustomObject && moduleToProcess.SessionState != null) + if (BaseAsCustomObject && moduleToProcess.SessionState is not null) { WriteObject(module.AsCustomObject()); } @@ -534,7 +534,7 @@ private void ImportModule_ViaAssembly(ImportModuleOptions importModuleOptions, A { bool moduleLoaded = false; // Loop through Module Cache to ensure that the module is not already imported. - if (suppliedAssembly != null && Context.Modules.ModuleTable != null) + if (suppliedAssembly is not null && Context.Modules.ModuleTable is not null) { foreach (KeyValuePair pair in Context.Modules.ModuleTable) { @@ -579,7 +579,7 @@ private void ImportModule_ViaAssembly(ImportModuleOptions importModuleOptions, A ManifestProcessingFlags.LoadElements | ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.NullOnFirstError, this.BasePrefix, false /* loadTypes */ , false /* loadFormats */, out found); - if (found && module != null) + if (found && module is not null) { // Add it to all module tables ... AddModuleToModuleTables(this.Context, this.TargetSessionState.Internal, module); @@ -594,7 +594,7 @@ private void ImportModule_ViaAssembly(ImportModuleOptions importModuleOptions, A private PSModuleInfo ImportModule_LocallyViaName_WithTelemetry(ImportModuleOptions importModuleOptions, string name) { PSModuleInfo foundModule = ImportModule_LocallyViaName(importModuleOptions, name); - if (foundModule != null) + if (foundModule is not null) { SetModuleBaseForEngineModules(foundModule.Name, this.Context); @@ -743,7 +743,7 @@ private PSModuleInfo ImportModule_LocallyViaName(ImportModuleOptions importModul PSSnapInInfo snapin = ModuleCmdletBase.GetEngineSnapIn(Context, name); // Return the command if we found a module - if (snapin != null) + if (snapin is not null) { // warn that this module already exists as a snapin string warningMessage = string.Format( @@ -796,24 +796,24 @@ private PSModuleInfo ImportModule_LocallyViaName(ImportModuleOptions importModul { ErrorRecord er = null; string message = null; - if (BaseRequiredVersion != null) + if (BaseRequiredVersion is not null) { message = StringUtil.Format(Modules.ModuleWithVersionNotFound, name, BaseRequiredVersion); } - else if (BaseMinimumVersion != null && BaseMaximumVersion != null) + else if (BaseMinimumVersion is not null && BaseMaximumVersion is not null) { message = StringUtil.Format(Modules.MinimumVersionAndMaximumVersionNotFound, name, BaseMinimumVersion, BaseMaximumVersion); } - else if (BaseMinimumVersion != null) + else if (BaseMinimumVersion is not null) { message = StringUtil.Format(Modules.ModuleWithVersionNotFound, name, BaseMinimumVersion); } - else if (BaseMaximumVersion != null) + else if (BaseMaximumVersion is not null) { message = StringUtil.Format(Modules.MaximumVersionNotFound, name, BaseMaximumVersion); } - if (BaseRequiredVersion != null || BaseMinimumVersion != null || BaseMaximumVersion != null) + if (BaseRequiredVersion is not null || BaseMinimumVersion is not null || BaseMaximumVersion is not null) { FileNotFoundException fnf = new FileNotFoundException(message); er = new ErrorRecord(fnf, "Modules_ModuleWithVersionNotFound", @@ -850,7 +850,7 @@ private PSModuleInfo ImportModule_LocallyViaFQName(ImportModuleOptions importMod PSModuleInfo foundModule = ImportModule_LocallyViaName(importModuleOptions, modulespec.Name); - if (foundModule != null) + if (foundModule is not null) { ApplicationInsightsTelemetry.SendTelemetryMetric(TelemetryType.ModuleLoad, foundModule.Name); SetModuleBaseForEngineModules(foundModule.Name, this.Context); @@ -873,7 +873,7 @@ private IList ImportModule_RemotelyViaPsrpSession( bool usingWinCompat = false) { var remotelyImportedModules = new List(); - if (moduleNames != null) + if (moduleNames is not null) { foreach (string moduleName in moduleNames) { @@ -882,7 +882,7 @@ private IList ImportModule_RemotelyViaPsrpSession( } } - if (fullyQualifiedNames != null) + if (fullyQualifiedNames is not null) { foreach (var fullyQualifiedName in fullyQualifiedNames) { @@ -917,7 +917,7 @@ private IList ImportModule_RemotelyViaPsrpSession( powerShell.AddParameter("DisableNameChecking", this.DisableNameChecking); powerShell.AddParameter("PassThru", true); - if (fullyQualifiedName != null) + if (fullyQualifiedName is not null) { powerShell.AddParameter("FullyQualifiedName", fullyQualifiedName); } @@ -925,23 +925,23 @@ private IList ImportModule_RemotelyViaPsrpSession( { powerShell.AddParameter("Name", moduleName); - if (this.MinimumVersion != null) + if (this.MinimumVersion is not null) { powerShell.AddParameter("Version", this.MinimumVersion); } - if (this.RequiredVersion != null) + if (this.RequiredVersion is not null) { powerShell.AddParameter("RequiredVersion", this.RequiredVersion); } - if (this.MaximumVersion != null) + if (this.MaximumVersion is not null) { powerShell.AddParameter("MaximumVersion", this.MaximumVersion); } } - if (this.ArgumentList != null) + if (this.ArgumentList is not null) { powerShell.AddParameter("ArgumentList", this.ArgumentList); } @@ -966,7 +966,7 @@ private IList ImportModule_RemotelyViaPsrpSession( foreach (PSObject remotelyImportedModule in remotelyImportedModules) { PSPropertyInfo nameProperty = remotelyImportedModule.Properties["Name"]; - if (nameProperty != null) + if (nameProperty is not null) { string remoteModuleName = (string)LanguagePrimitives.ConvertTo( nameProperty.Value, @@ -975,7 +975,7 @@ private IList ImportModule_RemotelyViaPsrpSession( PSPropertyInfo helpInfoProperty = remotelyImportedModule.Properties["HelpInfoUri"]; string remoteHelpInfoUri = null; - if (helpInfoProperty != null) + if (helpInfoProperty is not null) { remoteHelpInfoUri = (string)LanguagePrimitives.ConvertTo( helpInfoProperty.Value, @@ -985,14 +985,14 @@ private IList ImportModule_RemotelyViaPsrpSession( PSPropertyInfo guidProperty = remotelyImportedModule.Properties["Guid"]; Guid remoteModuleGuid = Guid.Empty; - if (guidProperty != null) + if (guidProperty is not null) { LanguagePrimitives.TryConvertTo(guidProperty.Value, out remoteModuleGuid); } PSPropertyInfo versionProperty = remotelyImportedModule.Properties["Version"]; Version remoteModuleVersion = null; - if (versionProperty != null) + if (versionProperty is not null) { Version tmp; if (LanguagePrimitives.TryConvertTo(versionProperty.Value, CultureInfo.InvariantCulture, out tmp)) @@ -1009,7 +1009,7 @@ private IList ImportModule_RemotelyViaPsrpSession( // Set the HelpInfoUri and Guid as necessary, so that Save-Help can work with this module object // to retrieve help files from the remote site. - if (moduleInfo != null) + if (moduleInfo is not null) { // set the HelpInfoUri if it's needed if (string.IsNullOrEmpty(moduleInfo.HelpInfoUri) && !string.IsNullOrEmpty(remoteHelpInfoUri)) @@ -1051,7 +1051,7 @@ private PSModuleInfo ImportModule_RemotelyViaPsrpSession_SinglePreimportedModule string localPsm1File = Path.Combine(temporaryModulePath, Path.GetFileName(temporaryModulePath) + ".psm1"); PSModuleInfo alreadyImportedModule = this.IsModuleImportUnnecessaryBecauseModuleIsAlreadyLoaded( localPsm1File, this.BasePrefix, importModuleOptions); - if (alreadyImportedModule != null) + if (alreadyImportedModule is not null) { return alreadyImportedModule; } @@ -1225,14 +1225,14 @@ private bool IsMixedModePsCimModule(RemoteDiscoveryHelper.CimModule cimModule) string[] nestedModules = null; if (LanguagePrimitives.TryConvertTo(manifestData["NestedModules"], CultureInfo.InvariantCulture, out nestedModules)) { - if (nestedModules != null) + if (nestedModules is not null) { numberOfSubmodules += nestedModules.Length; } } object rootModuleValue = manifestData["RootModule"]; - if (rootModuleValue != null) + if (rootModuleValue is not null) { string rootModule; if (LanguagePrimitives.TryConvertTo(rootModuleValue, CultureInfo.InvariantCulture, out rootModule)) @@ -1247,7 +1247,7 @@ private bool IsMixedModePsCimModule(RemoteDiscoveryHelper.CimModule cimModule) { object moduleToProcessValue = manifestData["ModuleToProcess"]; string moduleToProcess; - if (moduleToProcessValue != null && LanguagePrimitives.TryConvertTo(moduleToProcessValue, CultureInfo.InvariantCulture, out moduleToProcess)) + if (moduleToProcessValue is not null && LanguagePrimitives.TryConvertTo(moduleToProcessValue, CultureInfo.InvariantCulture, out moduleToProcess)) { if (!string.IsNullOrEmpty(moduleToProcess)) { @@ -1490,7 +1490,7 @@ private PSModuleInfo ImportModule_RemotelyViaCimModuleData( out throwAwayTokens, out parseErrors); if ((scriptBlockAst is null) || - (parseErrors != null && parseErrors.Length > 0)) + (parseErrors is not null && parseErrors.Length > 0)) { throw new ParseException(parseErrors); } @@ -1533,7 +1533,7 @@ private PSModuleInfo ImportModule_RemotelyViaCimModuleData( // avoid loading an already loaded module PSModuleInfo alreadyImportedModule = this.IsModuleImportUnnecessaryBecauseModuleIsAlreadyLoaded( temporaryModuleManifestPath, this.BasePrefix, importModuleOptions); - if (alreadyImportedModule != null) + if (alreadyImportedModule is not null) { return alreadyImportedModule; } @@ -1624,7 +1624,7 @@ private PSModuleInfo ImportModule_RemotelyViaCimModuleData( // store the default session // Dbg.Assert(moduleInfo.ModuleType == ModuleType.Manifest, "Remote discovery should always produce a 'manifest' module"); - Dbg.Assert(moduleInfo.NestedModules != null, "Remote discovery should always produce a 'manifest' module with nested modules entry"); + Dbg.Assert(moduleInfo.NestedModules is not null, "Remote discovery should always produce a 'manifest' module with nested modules entry"); Dbg.Assert(moduleInfo.NestedModules.Count > 0, "Remote discovery should always produce a 'manifest' module with some nested modules"); foreach (PSModuleInfo nestedModule in moduleInfo.NestedModules) { @@ -1801,7 +1801,7 @@ protected override void BeginProcessing() /// protected override void ProcessRecord() { - if (BaseMaximumVersion != null && BaseMinimumVersion != null && BaseMaximumVersion < BaseMinimumVersion) + if (BaseMaximumVersion is not null && BaseMinimumVersion is not null && BaseMaximumVersion < BaseMinimumVersion) { string message = StringUtil.Format(Modules.MinimumVersionAndMaximumVersionInvalidRange, BaseMinimumVersion, BaseMaximumVersion); throw new PSArgumentOutOfRangeException(message); @@ -1846,7 +1846,7 @@ protected override void ProcessRecord() else if (this.ParameterSetName.Equals(ParameterSet_Assembly, StringComparison.OrdinalIgnoreCase)) { // Now load all of the supplied assemblies... - if (Assembly != null) + if (Assembly is not null) { foreach (Assembly suppliedAssembly in Assembly) { @@ -1927,7 +1927,7 @@ private bool IsModuleInDenyList(string[] moduleDenyList, string moduleName, Modu private List FilterModuleCollection(IEnumerable moduleCollection) { List filteredModuleCollection = null; - if (moduleCollection != null) + if (moduleCollection is not null) { // the ModuleDeny list is cached in PowerShellConfig object string[] moduleDenyList = PowerShellConfig.Instance.GetWindowsPowerShellCompatibilityModuleDenyList(); @@ -1960,7 +1960,7 @@ private void PrepareNoClobberWinCompatModuleImport(string moduleName, ModuleSpec var isModuleToLoadEngineModule = InitialSessionState.IsEngineModule(coreModuleToLoad); string[] noClobberModuleList = PowerShellConfig.Instance.GetWindowsPowerShellCompatibilityNoClobberModuleList(); - if (isModuleToLoadEngineModule || ((noClobberModuleList != null) && noClobberModuleList.Contains(coreModuleToLoad, StringComparer.OrdinalIgnoreCase))) + if (isModuleToLoadEngineModule || ((noClobberModuleList is not null) && noClobberModuleList.Contains(coreModuleToLoad, StringComparer.OrdinalIgnoreCase))) { // if it is one of engine modules - first try to load it from $PSHOME\Modules // otherwise rely on $env:PSModulePath (in which WinPS module location has to go after CorePS module location) @@ -2022,7 +2022,7 @@ internal override IList ImportModulesUsingWinCompat(IEnumerable ImportModulesUsingWinCompat(IEnumerable modulePath = null; - if (tempModuleInfoFromVerification != null) + if (tempModuleInfoFromVerification is not null) { var subdirName = Path.GetFileName(tempModuleInfoFromVerification.ModuleBase); Version version; @@ -829,7 +829,7 @@ private PSModuleInfo LoadModuleNamedInManifest(PSModuleInfo parentModule, Module } } - if (manifestLanguageMode.HasValue && found && (module != null) && module.LanguageMode.HasValue) + if (manifestLanguageMode.HasValue && found && (module is not null) && module.LanguageMode.HasValue) { // Check for script module language mode consistency. All loaded script modules must have the same language mode as the manifest. // If not then this indicates a malformed module and a possible exploit to make trusted private functions visible in a @@ -852,9 +852,9 @@ private PSModuleInfo LoadModuleNamedInManifest(PSModuleInfo parentModule, Module // actually process the binary module. bool shouldLoadModule = true; - if ((parentModule != null) && !importingModule) + if ((parentModule is not null) && !importingModule) { - if ((parentModule.ExportedCmdlets != null) && (parentModule.ExportedCmdlets.Count > 0)) + if ((parentModule.ExportedCmdlets is not null) && (parentModule.ExportedCmdlets.Count > 0)) { shouldLoadModule = false; @@ -899,7 +899,7 @@ private PSModuleInfo LoadModuleNamedInManifest(PSModuleInfo parentModule, Module // In this case, we can safely ignore this exception and throw a 'Modules_ModuleFileNotFound' error. } - if ((module != null) && importingModule) + if ((module is not null) && importingModule) { AddModuleToModuleTables(this.Context, this.TargetSessionState.Internal, module); } @@ -927,7 +927,7 @@ internal List GetModule(string[] names, bool all, bool refresh) List modulePaths = new List(); List moduleNames = new List(); - if (names != null) + if (names is not null) { foreach (var n in names) { @@ -973,7 +973,7 @@ private IEnumerable GetModuleForRootedPaths(List modulePat // Now we resolve the possible paths in case it is relative path/path contains wildcards var modulePathCollection = GetResolvedPathCollection(modulePath, this.Context); - if (modulePathCollection != null) + if (modulePathCollection is not null) { foreach (string resolvedModulePath in modulePathCollection) { @@ -983,7 +983,7 @@ private IEnumerable GetModuleForRootedPaths(List modulePat if (!Directory.Exists(resolvedModulePath) && ModuleIntrinsics.IsPowerShellModuleExtension(Path.GetExtension(moduleName))) { PSModuleInfo module = CreateModuleInfoForGetModule(resolvedModulePath, refresh); - if (module != null) + if (module is not null) { if (!modules.Contains(resolvedModulePath)) { @@ -1009,7 +1009,7 @@ private IEnumerable GetModuleForRootedPaths(List modulePat foreach (string file in availableModuleFiles) { PSModuleInfo module = CreateModuleInfoForGetModule(file, refresh); - if (module != null) + if (module is not null) { if (string.Equals(moduleName, module.Name, StringComparison.OrdinalIgnoreCase)) { @@ -1098,7 +1098,7 @@ private IEnumerable GetModulesFromOneModulePath(List names { const WildcardOptions options = WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant; IEnumerable namePatterns = null; - if (names != null && names.Count > 0) + if (names is not null && names.Count > 0) { namePatterns = SessionStateUtilities.CreateWildcardsFromStrings(names, options); } @@ -1239,7 +1239,7 @@ private PSModuleInfo CreateModuleInfoForGetModule(string file, bool refresh) if (extension.Equals(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase)) { - if (moduleInfo.RootModuleForManifest != null) + if (moduleInfo.RootModuleForManifest is not null) { if (moduleInfo.RootModuleForManifest.EndsWith(StringLiterals.PowerShellILAssemblyExtension, StringComparison.OrdinalIgnoreCase) || moduleInfo.RootModuleForManifest.EndsWith(StringLiterals.PowerShellILExecutableExtension, StringComparison.OrdinalIgnoreCase)) @@ -1364,7 +1364,7 @@ internal PSModuleInfo LoadModuleManifest( Guid? requiredModuleGuid, ref ImportModuleOptions options) { - Dbg.Assert(scriptInfo != null, "scriptInfo for module (.psd1) can't be null"); + Dbg.Assert(scriptInfo is not null, "scriptInfo for module (.psd1) can't be null"); bool containedErrors = false; Hashtable data = null; @@ -1389,7 +1389,7 @@ internal bool LoadModuleManifestData(ExternalScriptInfo scriptInfo, ManifestProc ExternalScriptInfo localizedScriptInfo = FindLocalizedModuleManifest(scriptInfo.Path); localizedData = null; - if (localizedScriptInfo != null) + if (localizedScriptInfo is not null) { localizedData = LoadModuleManifestData(localizedScriptInfo, null, manifestProcessingFlags, ref containedErrors); if (localizedData is null) @@ -1491,7 +1491,7 @@ internal PSModuleInfo LoadModuleManifest( var importingModule = manifestProcessingFlags.HasFlag(ManifestProcessingFlags.LoadElements); var writingErrors = manifestProcessingFlags.HasFlag(ManifestProcessingFlags.WriteErrors); - Dbg.Assert(moduleManifestPath != null, "moduleManifestPath for module (.psd1) can't be null"); + Dbg.Assert(moduleManifestPath is not null, "moduleManifestPath for module (.psd1) can't be null"); string moduleBase = Path.GetDirectoryName(moduleManifestPath); if ((manifestProcessingFlags & @@ -1609,7 +1609,7 @@ internal PSModuleInfo LoadModuleManifest( { rootedPath = this.FixupFileName(moduleBase, actualRootModule, extensionToTry, importingModule); TryGetFromModuleTable(rootedPath, out loadedModule); - if (loadedModule != null) + if (loadedModule is not null) break; } } @@ -1717,9 +1717,9 @@ internal PSModuleInfo LoadModuleManifest( } Version moduleVersionFromFolderName; - if (parent != null && + if (parent is not null && Version.TryParse(parent.Name, out moduleVersionFromFolderName) && - parent.Parent != null && + parent.Parent is not null && parent.Parent.Name.Equals(Path.GetFileNameWithoutExtension(moduleManifestPath))) { if (!moduleVersionFromFolderName.Equals(moduleVersion)) @@ -1749,7 +1749,7 @@ internal PSModuleInfo LoadModuleManifest( containedErrors = true; if (bailOnFirstError) return null; } - else if (powerShellVersion != null) + else if (powerShellVersion is not null) { Version currentPowerShellVersion = PSVersionInfo.PSVersion; if (currentPowerShellVersion < powerShellVersion) @@ -1783,7 +1783,7 @@ internal PSModuleInfo LoadModuleManifest( bailOnFirstError) return null; } - else if (requestedHostName != null) + else if (requestedHostName is not null) { string currentHostName = this.Context.InternalHost.Name; if (!string.Equals(currentHostName, requestedHostName, StringComparison.OrdinalIgnoreCase)) @@ -1821,7 +1821,7 @@ internal PSModuleInfo LoadModuleManifest( bailOnFirstError) return null; } - else if (requestedHostVersion != null) + else if (requestedHostVersion is not null) { Version currentHostVersion = this.Context.InternalHost.Version; if (currentHostVersion < requestedHostVersion) @@ -1916,7 +1916,7 @@ internal PSModuleInfo LoadModuleManifest( containedErrors = true; if (bailOnFirstError) return null; } - else if ((requiredModules != null)) + else if ((requiredModules is not null)) { if (importingModule) { @@ -1931,7 +1931,7 @@ internal PSModuleInfo LoadModuleManifest( fakeManifestInfo.SetGuid(manifestGuid.Value); } - if (moduleVersion != null) + if (moduleVersion is not null) { fakeManifestInfo.SetVersion(moduleVersion); } @@ -1945,14 +1945,14 @@ internal PSModuleInfo LoadModuleManifest( ErrorRecord error = null; PSModuleInfo module = LoadRequiredModule(fakeManifestInfo, normalizedRequiredModuleSpec, moduleManifestPath, manifestProcessingFlags, containedErrors, out error); - if (module is null && error != null) + if (module is null && error is not null) { WriteError(error); return null; } // module can be null (in case the RequiredModule has already been added as a snapin. // In that case, we just emit a warning and do not add the snapin to the list of requiredmodules) - if (module != null) + if (module is not null) { requiredModulesLoaded.Add(module); } @@ -1979,7 +1979,7 @@ internal PSModuleInfo LoadModuleManifest( List nestedModules = new List(); - if (tmpNestedModules != null && tmpNestedModules.Length > 0) + if (tmpNestedModules is not null && tmpNestedModules.Length > 0) { foreach (ModuleSpecification s in tmpNestedModules) { @@ -2012,7 +2012,7 @@ internal PSModuleInfo LoadModuleManifest( if (bailOnFirstError) return null; } - if (features != null && features.Length > 0) + if (features is not null && features.Length > 0) { bool nameMissingOrEmpty = false; var invalidNames = new List(); @@ -2118,7 +2118,7 @@ internal PSModuleInfo LoadModuleManifest( if (importingModule) { iss = InitialSessionState.Create(); - if (Context.InitialSessionState != null) + if (Context.InitialSessionState is not null) { iss.DisableFormatUpdates = Context.InitialSessionState.DisableFormatUpdates; } @@ -2143,7 +2143,7 @@ internal PSModuleInfo LoadModuleManifest( } else { - if (tmpAssemblyList != null && tmpAssemblyList.Count > 0) + if (tmpAssemblyList is not null && tmpAssemblyList.Count > 0) { foreach (string assembly in tmpAssemblyList) { @@ -2151,7 +2151,7 @@ internal PSModuleInfo LoadModuleManifest( } } - if ((assemblyList != null) && importingModule) + if ((assemblyList is not null) && importingModule) { foreach (string assembly in assemblyList) { @@ -2199,7 +2199,7 @@ internal PSModuleInfo LoadModuleManifest( } else { - if ((exportedTypeFiles != null) && importingModule) + if ((exportedTypeFiles is not null) && importingModule) { foreach (string fileName in exportedTypeFiles) { @@ -2244,7 +2244,7 @@ internal PSModuleInfo LoadModuleManifest( } else { - if ((exportedFormatFiles != null) && importingModule) + if ((exportedFormatFiles is not null) && importingModule) { foreach (string fileName in exportedFormatFiles) { @@ -2286,7 +2286,7 @@ internal PSModuleInfo LoadModuleManifest( } else { - if ((scriptsToProcess != null) && importingModule) + if ((scriptsToProcess is not null) && importingModule) { foreach (string scriptFile in scriptsToProcess) { @@ -2309,7 +2309,7 @@ internal PSModuleInfo LoadModuleManifest( string description = string.Empty; if (data.Contains("Description")) { - if (localizedData != null && localizedData.Contains("Description")) + if (localizedData is not null && localizedData.Contains("Description")) { description = (string)LanguagePrimitives.ConvertTo(localizedData["Description"], typeof(string), CultureInfo.InvariantCulture); @@ -2459,7 +2459,7 @@ internal PSModuleInfo LoadModuleManifest( SetModuleLoggingInformation(manifestInfo); } - if (requiredModulesSpecifiedInModuleManifest != null && requiredModulesSpecifiedInModuleManifest.Count > 0) + if (requiredModulesSpecifiedInModuleManifest is not null && requiredModulesSpecifiedInModuleManifest.Count > 0) { foreach (var module in requiredModulesSpecifiedInModuleManifest) { @@ -2468,7 +2468,7 @@ internal PSModuleInfo LoadModuleManifest( } // If there is a session state, set up to import/export commands and variables - if (ss != null) + if (ss is not null) { ss.Internal.SetVariable(SpecialVariables.PSScriptRootVarPath, Path.GetDirectoryName(moduleManifestPath), true, CommandOrigin.Internal); @@ -2524,12 +2524,12 @@ internal PSModuleInfo LoadModuleManifest( // if it is and declared "Core" as a compatible PSEdition. manifestInfo.IsConsideredEditionCompatible = isConsideredCompatible; - if (expFeatureList != null) + if (expFeatureList is not null) { manifestInfo.ExperimentalFeatures = new ReadOnlyCollection(expFeatureList); } - if (assemblyList != null) + if (assemblyList is not null) { foreach (var a in assemblyList) { @@ -2537,7 +2537,7 @@ internal PSModuleInfo LoadModuleManifest( } } - if (fileList != null) + if (fileList is not null) { foreach (var f in fileList) { @@ -2546,7 +2546,7 @@ internal PSModuleInfo LoadModuleManifest( } } - if (moduleList != null) + if (moduleList is not null) { foreach (var m in moduleList) { @@ -2555,12 +2555,12 @@ internal PSModuleInfo LoadModuleManifest( } } - if (compatiblePSEditions != null) + if (compatiblePSEditions is not null) { manifestInfo.AddToCompatiblePSEditions(compatiblePSEditions); } - if (scriptsToProcess != null) + if (scriptsToProcess is not null) { foreach (var s in scriptsToProcess) { @@ -2570,12 +2570,12 @@ internal PSModuleInfo LoadModuleManifest( manifestInfo.RootModule = actualRootModule; manifestInfo.RootModuleForManifest = actualRootModule; - if (manifestGuid != null) + if (manifestGuid is not null) { manifestInfo.SetGuid((Guid)manifestGuid); } - if (helpInfoUri != null) + if (helpInfoUri is not null) { manifestInfo.SetHelpInfoUri(helpInfoUri); } @@ -2585,7 +2585,7 @@ internal PSModuleInfo LoadModuleManifest( manifestInfo.AddRequiredModule(module); } - if (requiredModules != null) + if (requiredModules is not null) { foreach (ModuleSpecification moduleSpecification in requiredModules) { @@ -2603,7 +2603,7 @@ internal PSModuleInfo LoadModuleManifest( using (TextReader reader = File.OpenText(psgetItemInfoXml)) { PSObject xml = PSSerializer.Deserialize(reader.ReadToEnd()) as PSObject; - if (xml != null && xml.Properties["RepositorySourceLocation"] != null) + if (xml is not null && xml.Properties["RepositorySourceLocation"] is not null) { var repositorySourceLocation = xml.Properties["RepositorySourceLocation"].Value.ToString(); Uri repositorySourceLocationUri; @@ -2646,7 +2646,7 @@ internal PSModuleInfo LoadModuleManifest( bool sawExportedCmdlets = false; bool sawExportedAliases = false; - if (exportedFunctions != null) + if (exportedFunctions is not null) { manifestInfo.DeclaredFunctionExports = new Collection(); @@ -2674,7 +2674,7 @@ internal PSModuleInfo LoadModuleManifest( sawExportedFunctions = true; } - if (exportedCmdlets != null) + if (exportedCmdlets is not null) { manifestInfo.DeclaredCmdletExports = new Collection(); @@ -2702,7 +2702,7 @@ internal PSModuleInfo LoadModuleManifest( sawExportedCmdlets = true; } - if (exportedAliases != null) + if (exportedAliases is not null) { manifestInfo.DeclaredAliasExports = new Collection(); @@ -2730,7 +2730,7 @@ internal PSModuleInfo LoadModuleManifest( sawExportedAliases = true; } - if (exportedVariables != null) + if (exportedVariables is not null) { manifestInfo.DeclaredVariableExports = new Collection(); @@ -2795,7 +2795,7 @@ internal PSModuleInfo LoadModuleManifest( } } - if (scriptsToProcess != null) + if (scriptsToProcess is not null) { Version savedBaseMinimumVersion = BaseMinimumVersion; Version savedBaseMaximumVersion = BaseMaximumVersion; @@ -2891,11 +2891,11 @@ internal PSModuleInfo LoadModuleManifest( { if (importingModule) { - Dbg.Assert(ss != null, "ss should not be null"); - Dbg.Assert(ss.Internal != null, "ss.Internal should not be null"); + Dbg.Assert(ss is not null, "ss should not be null"); + Dbg.Assert(ss.Internal is not null, "ss.Internal should not be null"); } - if (ss != null) + if (ss is not null) { ss.Internal.ManifestWithExplicitFunctionExport = !exportedFunctionsContainsWildcards; Context.EngineSessionState = ss.Internal; @@ -2909,7 +2909,7 @@ internal PSModuleInfo LoadModuleManifest( // If the nested manifest explicitly (no wildcards) specifies functions to be exported then allow all functions to be exported // into the session state function table (regardless of language boundaries), because the manifest will filter them later to the // specified function list. - nestedModuleOptions.AllowNestedModuleFunctionsToExport = ((exportedFunctions != null) && !exportedFunctionsContainsWildcards); + nestedModuleOptions.AllowNestedModuleFunctionsToExport = ((exportedFunctions is not null) && !exportedFunctionsContainsWildcards); foreach (ModuleSpecification nestedModuleSpecification in nestedModules) { @@ -2932,7 +2932,7 @@ internal PSModuleInfo LoadModuleManifest( privateData: privateData, found: out found, shortModuleName: null, - manifestLanguageMode: ((manifestScriptInfo != null) ? manifestScriptInfo.DefiningLanguageMode.GetValueOrDefault() : (PSLanguageMode?)null)); + manifestLanguageMode: ((manifestScriptInfo is not null) ? manifestScriptInfo.DefiningLanguageMode.GetValueOrDefault() : (PSLanguageMode?)null)); this.BaseGlobal = oldGlobal; @@ -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 is null) && (nestedModule is not null)) { foreach (string detectedCmdlet in nestedModule.ExportedCmdlets.Keys) { @@ -2962,7 +2962,7 @@ internal PSModuleInfo LoadModuleManifest( // If the NestedModules was a .ps1 script no module object would have been generated // so there's nothing to add, otherwise add it to the list. // When we are in analysis mode and we do not analyze the nested module (because the parent module has explicit exports), the nested modules do not get added to the list - if (nestedModule != null) + if (nestedModule is not null) { manifestInfo.AddNestedModule(nestedModule); } @@ -3002,7 +3002,7 @@ internal PSModuleInfo LoadModuleManifest( // Now see if the ModuleToProcess field was set. This radically // changes how the exports are done. - if (actualRootModule != null) + if (actualRootModule is not null) { PSModuleInfo newManifestInfo; @@ -3035,7 +3035,7 @@ internal PSModuleInfo LoadModuleManifest( privateData: privateData, found: out found, shortModuleName: null, - manifestLanguageMode: ((manifestScriptInfo != null) ? manifestScriptInfo.DefiningLanguageMode.GetValueOrDefault() : (PSLanguageMode?)null)); + manifestLanguageMode: ((manifestScriptInfo is not null) ? manifestScriptInfo.DefiningLanguageMode.GetValueOrDefault() : (PSLanguageMode?)null)); if (!found || (newManifestInfo is null)) { @@ -3051,7 +3051,7 @@ internal PSModuleInfo LoadModuleManifest( ErrorRecord errorRecord = GetErrorRecordIfUnsupportedRootCdxmlAndNestedModuleScenario(data, moduleManifestPath, newManifestInfo.Path); - if (errorRecord != null) + if (errorRecord is not null) { containedErrors = true; RemoveModule(newManifestInfo); @@ -3118,17 +3118,17 @@ internal PSModuleInfo LoadModuleManifest( newManifestInfo.SetVersion(moduleVersion); } - if (newManifestInfo.Guid.Equals(Guid.Empty) && (manifestGuid != null)) + if (newManifestInfo.Guid.Equals(Guid.Empty) && (manifestGuid is not null)) { newManifestInfo.SetGuid((Guid)manifestGuid); } - if (newManifestInfo.HelpInfoUri is null && (helpInfoUri != null)) + if (newManifestInfo.HelpInfoUri is null && (helpInfoUri is not null)) { newManifestInfo.SetHelpInfoUri(helpInfoUri); } - if (requiredModules != null) + if (requiredModules is not null) { foreach (ModuleSpecification moduleSpecification in requiredModules) { @@ -3215,7 +3215,7 @@ internal PSModuleInfo LoadModuleManifest( if (newManifestInfo.FileList is null || newManifestInfo.FileList.LongCount() == 0) { - if (fileList != null) + if (fileList is not null) { foreach (var f in fileList) { @@ -3226,7 +3226,7 @@ internal PSModuleInfo LoadModuleManifest( if (newManifestInfo.ModuleList is null || newManifestInfo.ModuleList.LongCount() == 0) { - if (moduleList != null) + if (moduleList is not null) { foreach (var m in moduleList) { @@ -3237,7 +3237,7 @@ internal PSModuleInfo LoadModuleManifest( if (newManifestInfo.CompatiblePSEditions is null || newManifestInfo.CompatiblePSEditions.LongCount() == 0) { - if (compatiblePSEditions != null) + if (compatiblePSEditions is not null) { newManifestInfo.AddToCompatiblePSEditions(compatiblePSEditions); } @@ -3250,7 +3250,7 @@ internal PSModuleInfo LoadModuleManifest( if (newManifestInfo.RequiredAssemblies is null || newManifestInfo.RequiredAssemblies.LongCount() == 0) { - if (assemblyList != null) + if (assemblyList is not null) { foreach (var a in assemblyList) { @@ -3261,7 +3261,7 @@ internal PSModuleInfo LoadModuleManifest( if (newManifestInfo.Scripts is null || newManifestInfo.Scripts.LongCount() == 0) { - if (scriptsToProcess != null) + if (scriptsToProcess is not null) { foreach (var s in scriptsToProcess) { @@ -3280,7 +3280,7 @@ internal PSModuleInfo LoadModuleManifest( newManifestInfo.DeclaredCmdletExports = manifestInfo.DeclaredCmdletExports; } - if (manifestInfo.DetectedCmdletExports != null) + if (manifestInfo.DetectedCmdletExports is not null) { foreach (string detectedExport in manifestInfo.DetectedCmdletExports) { @@ -3294,7 +3294,7 @@ internal PSModuleInfo LoadModuleManifest( newManifestInfo.DeclaredFunctionExports = manifestInfo.DeclaredFunctionExports; } - if (manifestInfo.DetectedFunctionExports != null) + if (manifestInfo.DetectedFunctionExports is not null) { foreach (string detectedExport in manifestInfo.DetectedFunctionExports) { @@ -3307,7 +3307,7 @@ internal PSModuleInfo LoadModuleManifest( newManifestInfo.DeclaredAliasExports = manifestInfo.DeclaredAliasExports; } - if (manifestInfo.DetectedAliasExports != null) + if (manifestInfo.DetectedAliasExports is not null) { foreach (var pair in manifestInfo.DetectedAliasExports) { @@ -3340,12 +3340,12 @@ internal PSModuleInfo LoadModuleManifest( // mark the binary module exports... if (manifestInfo.ModuleType == ModuleType.Binary) { - if ((exportedCmdlets != null) && (ss != null)) + if ((exportedCmdlets is not null) && (ss is not null)) { manifestInfo.ExportedCmdlets.Clear(); // Mark stuff for export - if (ss != null) + if (ss is not null) { ModuleIntrinsics.ExportModuleMembers( this, @@ -3362,7 +3362,7 @@ internal PSModuleInfo LoadModuleManifest( { // If the script didn't call Export-ModuleMember explicitly, then // implicitly export functions and cmdlets. - if ((ss != null) && (!ss.Internal.UseExportList)) + if ((ss is not null) && (!ss.Internal.UseExportList)) { // For cross language boundaries, implicitly import all functions only if // this manifest *does* exort functions explicitly. @@ -3382,9 +3382,9 @@ internal PSModuleInfo LoadModuleManifest( } // Export* fields in .psd1 subset Export-ModuleMember calls from ModuleToProcess=psm1 - if (exportedFunctions != null) + if (exportedFunctions is not null) { - if (ss != null) + if (ss is not null) { // If module (psm1) functions were not exported because of cross language boundary restrictions, // then implicitly export them here so that they can be filtered by the exportedFunctions list. @@ -3402,7 +3402,7 @@ internal PSModuleInfo LoadModuleManifest( doNotExportCmdlets: null); } - Dbg.Assert(ss.Internal.ExportedFunctions != null, + Dbg.Assert(ss.Internal.ExportedFunctions is not null, "ss.Internal.ExportedFunctions should not be null"); // Update the exports to only contain things that are also in the manifest export list @@ -3414,11 +3414,11 @@ internal PSModuleInfo LoadModuleManifest( } } - if (exportedCmdlets != null) + if (exportedCmdlets is not null) { - if (ss != null) + if (ss is not null) { - Dbg.Assert(ss.Internal.ExportedCmdlets != null, + Dbg.Assert(ss.Internal.ExportedCmdlets is not null, "ss.Internal.ExportedCmdlets should not be null"); // Update the exports to only contain things that are also in the manifest export list @@ -3430,11 +3430,11 @@ internal PSModuleInfo LoadModuleManifest( } } - if (exportedAliases != null) + if (exportedAliases is not null) { - if (ss != null) + if (ss is not null) { - Dbg.Assert(ss.Internal.ExportedAliases != null, + Dbg.Assert(ss.Internal.ExportedAliases is not null, "ss.Internal.ExportedAliases should not be null"); // Update the exports to only contain things that are also in the manifest export list @@ -3446,11 +3446,11 @@ internal PSModuleInfo LoadModuleManifest( } } - if (exportedVariables != null) + if (exportedVariables is not null) { - if (ss != null) + if (ss is not null) { - Dbg.Assert(ss.Internal.ExportedVariables != null, + Dbg.Assert(ss.Internal.ExportedVariables is not null, "ss.Internal.ExportedVariables should not be null"); // Update the exports to only contain things that are also in the manifest export list @@ -3474,7 +3474,7 @@ internal PSModuleInfo LoadModuleManifest( } else { - if (ss != null) + if (ss is not null) { // In the case where there are only nested modules, // the members of the manifest are canonical... @@ -3498,7 +3498,7 @@ internal PSModuleInfo LoadModuleManifest( ImportModuleMembers(manifestInfo, resolvedCommandPrefix, options); } - manifestInfo.LanguageMode = (manifestScriptInfo != null) ? manifestScriptInfo.DefiningLanguageMode : (PSLanguageMode?)null; + manifestInfo.LanguageMode = (manifestScriptInfo is not null) ? manifestScriptInfo.DefiningLanguageMode : (PSLanguageMode?)null; return manifestInfo; } @@ -3528,10 +3528,10 @@ private static void PropagateExportedTypesFromNestedModulesToRootModuleScope(Imp foreach (var nestedModule in modulesToProcess) { - if (nestedModule != null) + if (nestedModule is not null) { var exportedTypes = nestedModule.GetExportedTypeDefinitions(); - if (exportedTypes != null && exportedTypes.Count != 0) + if (exportedTypes is not null && exportedTypes.Count != 0) { foreach (var t in exportedTypes) { @@ -3544,7 +3544,7 @@ private static void PropagateExportedTypesFromNestedModulesToRootModuleScope(Imp private static void SetDeclaredDscResources(List exportedDscResources, PSModuleInfo manifestInfo) { - if (exportedDscResources != null) + if (exportedDscResources is not null) { manifestInfo._declaredDscResourceExports = new Collection(); @@ -3562,7 +3562,7 @@ private static void SetDeclaredDscResources(List exportedDscRes } // if it is empty it means there is a wildcard pattern - if (manifestInfo._declaredDscResourceExports != null && manifestInfo._declaredDscResourceExports.Count == 0) + if (manifestInfo._declaredDscResourceExports is not null && manifestInfo._declaredDscResourceExports.Count == 0) { var exportedTypes = manifestInfo.GetExportedTypeDefinitions(); var exportedClassDscResources = exportedTypes.Values.Where(typeAst => @@ -3675,12 +3675,12 @@ private static ErrorRecord GenerateInvalidModuleMemberErrorRecord(string manifes internal static object IsModuleLoaded(ExecutionContext context, ModuleSpecification requiredModule, out ModuleMatchFailure matchFailureReason, out bool loaded) { loaded = false; - Dbg.Assert(requiredModule != null, "Caller should verify requiredModuleSpecification != null"); + Dbg.Assert(requiredModule is not null, "Caller should verify requiredModuleSpecification is not null"); // Assume the module is not loaded. object result = null; - Dbg.Assert(requiredModule.Name != null, "GetModuleSpecification should guarantee that moduleName != null"); + Dbg.Assert(requiredModule.Name is not null, "GetModuleSpecification should guarantee that moduleName is not null"); ModuleMatchFailure matchFailure = ModuleMatchFailure.None; foreach (PSModuleInfo module in context.Modules.GetModules(new string[] { "*" }, false)) { @@ -3697,7 +3697,7 @@ internal static object IsModuleLoaded(ExecutionContext context, ModuleSpecificat if (result is null && InitialSessionState.IsEngineModule(requiredModule.Name)) { result = ModuleCmdletBase.GetEngineSnapIn(context, requiredModule.Name); - if (result != null) + if (result is not null) { loaded = true; } @@ -3721,7 +3721,7 @@ internal static object IsModuleLoaded(ExecutionContext context, ModuleSpecificat /// Null if the module is not loaded or loadElements is false, the loaded module otherwise. internal PSModuleInfo LoadRequiredModule(PSModuleInfo currentModule, ModuleSpecification requiredModule, string moduleManifestPath, ManifestProcessingFlags manifestProcessingFlags, bool containedErrors, out ErrorRecord error) { - Dbg.Assert(moduleManifestPath != null, "Caller should verify moduleManifestPath != null"); + Dbg.Assert(moduleManifestPath is not null, "Caller should verify moduleManifestPath is not null"); error = null; if (!containedErrors) { @@ -3768,19 +3768,19 @@ internal static PSModuleInfo LoadRequiredModule(ExecutionContext context, PSModuleInfo requiredModuleInfo = null; Collection moduleInfo = GetModuleIfAvailable(requiredModuleSpecification); - if (moduleInfo != null && moduleInfo.Count > 0) + if (moduleInfo is not null && moduleInfo.Count > 0) { requiredModuleInfo = moduleInfo[0]; // Check for cyclic references of RequiredModule bool hasRequiredModulesCyclicReference = false; Dictionary> requiredModules = new Dictionary>(new ModuleSpecificationComparer()); - if (currentModule != null) + if (currentModule is not null) { requiredModules.Add(new ModuleSpecification(currentModule), new List { requiredModuleSpecification }); } - if (requiredModuleSpecification != null) + if (requiredModuleSpecification is not null) { requiredModules.Add(requiredModuleSpecification, new List(requiredModuleInfo.RequiredModulesSpecification)); } @@ -3798,11 +3798,11 @@ internal static PSModuleInfo LoadRequiredModule(ExecutionContext context, else { // Error Record - if (moduleManifestPath != null) + if (moduleManifestPath is not null) { - Dbg.Assert(error != null, "Error message should be populated if there is cyclic dependency"); + Dbg.Assert(error is not null, "Error message should be populated if there is cyclic dependency"); MissingMemberException mm = null; - if (error != null && error.Exception != null) + if (error is not null && error.Exception is not null) { mm = new MissingMemberException(error.Exception.Message); } @@ -3815,7 +3815,7 @@ internal static PSModuleInfo LoadRequiredModule(ExecutionContext context, else { string message; - if (moduleManifestPath != null) + if (moduleManifestPath is not null) { if (0 != (manifestProcessingFlags & ManifestProcessingFlags.WriteErrors)) { @@ -3929,11 +3929,11 @@ private static PSModuleInfo ImportRequiredModule(ExecutionContext context, Modul powerShell.AddCommand("Import-Module"); powerShell.AddParameter("Name", requiredModule.Name); - if (requiredModule.RequiredVersion != null) + if (requiredModule.RequiredVersion is not null) { powerShell.AddParameter("RequiredVersion", requiredModule.RequiredVersion); } - else if (requiredModule.MaximumVersion != null) + else if (requiredModule.MaximumVersion is not null) { powerShell.AddParameter("MaximumVersion", requiredModule.MaximumVersion); } @@ -3943,7 +3943,7 @@ private static PSModuleInfo ImportRequiredModule(ExecutionContext context, Modul } powerShell.Invoke(); - if (powerShell.Streams.Error != null && powerShell.Streams.Error.Count > 0) + if (powerShell.Streams.Error is not null && powerShell.Streams.Error.Count > 0) { error = powerShell.Streams.Error[0]; } @@ -3959,22 +3959,22 @@ private static PSModuleInfo ImportRequiredModule(ExecutionContext context, Modul } ModuleSpecification ms = new ModuleSpecification(moduleNameToCheckAgainst); - if (requiredModule.Guid != null) + if (requiredModule.Guid is not null) { ms.Guid = requiredModule.Guid.Value; } - if (requiredModule.RequiredVersion != null) + if (requiredModule.RequiredVersion is not null) { ms.RequiredVersion = requiredModule.RequiredVersion; } - if (requiredModule.Version != null) + if (requiredModule.Version is not null) { ms.Version = requiredModule.Version; } - if (requiredModule.MaximumVersion != null) + if (requiredModule.MaximumVersion is not null) { ms.MaximumVersion = requiredModule.MaximumVersion; } @@ -4024,9 +4024,9 @@ internal bool VerifyIfNestedModuleIsAvailable(ModuleSpecification nestedModuleSp string extension, out PSModuleInfo nestedModuleInfoIfAvailable) { - Dbg.Assert(nestedModuleSpec != null, "nestedModuleSpec cannot be null."); + Dbg.Assert(nestedModuleSpec is not null, "nestedModuleSpec cannot be null."); nestedModuleInfoIfAvailable = null; - if ((nestedModuleSpec.Guid != null) || (nestedModuleSpec.Version != null) || (nestedModuleSpec.RequiredVersion != null) || (nestedModuleSpec.MaximumVersion != null)) + if ((nestedModuleSpec.Guid is not null) || (nestedModuleSpec.Version is not null) || (nestedModuleSpec.RequiredVersion is not null) || (nestedModuleSpec.MaximumVersion is not null)) { if (!string.IsNullOrEmpty(extension) && (!string.Equals(extension, StringLiterals.PowerShellDataFileExtension))) @@ -4048,17 +4048,17 @@ internal bool VerifyIfNestedModuleIsAvailable(ModuleSpecification nestedModuleSp tempSpec.Guid = nestedModuleSpec.Guid.Value; } - if (nestedModuleSpec.Version != null) + if (nestedModuleSpec.Version is not null) { tempSpec.Version = nestedModuleSpec.Version; } - if (nestedModuleSpec.RequiredVersion != null) + if (nestedModuleSpec.RequiredVersion is not null) { tempSpec.RequiredVersion = nestedModuleSpec.RequiredVersion; } - if (nestedModuleSpec.MaximumVersion != null) + if (nestedModuleSpec.MaximumVersion is not null) { tempSpec.MaximumVersion = nestedModuleSpec.MaximumVersion; } @@ -4167,7 +4167,7 @@ private static bool HasRequiredModulesCyclicReference(ModuleSpecification curren } } - Dbg.Assert(mo != null, "The moduleInfo should be present"); + Dbg.Assert(mo is not null, "The moduleInfo should be present"); string message = StringUtil.Format(Modules.RequiredModulesCyclicDependency, currentModuleSpecification.ToString(), requiredModuleSpecification.ToString(), mo.Path); MissingMemberException mm = new MissingMemberException(message); error = new ErrorRecord(mm, "Modules_InvalidManifest", ErrorCategory.ResourceUnavailable, mo.Path); @@ -4211,7 +4211,7 @@ private ExternalScriptInfo FindLocalizedModuleManifest(string path) CultureInfo culture = System.Globalization.CultureInfo.CurrentUICulture; CultureInfo currentCulture = culture; - while (currentCulture != null && !string.IsNullOrEmpty(currentCulture.Name)) + while (currentCulture is not null && !string.IsNullOrEmpty(currentCulture.Name)) { StringBuilder stringBuilder = new StringBuilder(dir); stringBuilder.Append("\\"); @@ -4231,7 +4231,7 @@ private ExternalScriptInfo FindLocalizedModuleManifest(string path) } ExternalScriptInfo result = null; - if (localizedFile != null) + if (localizedFile is not null) { result = new ExternalScriptInfo(Path.GetFileName(localizedFile), localizedFile); } @@ -4260,7 +4260,7 @@ internal bool GetListOfStringsFromData( list = null; if (data.Contains(key)) { - if (data[key] != null) + if (data[key] is not null) { try { @@ -4304,7 +4304,7 @@ private bool GetListOfWildcardsFromData( return false; } - if (listOfStrings != null) + if (listOfStrings is not null) { list = new List(); foreach (string s in listOfStrings) @@ -4363,7 +4363,7 @@ private bool GetListOfFilesFromData( return false; } - if (listOfStrings != null) + if (listOfStrings is not null) { var psHome = Utils.DefaultPowerShellAppBase; string alternateDirToCheck = null; @@ -4383,7 +4383,7 @@ private bool GetListOfFilesFromData( var dir = Path.GetDirectoryName(fixedFileName); if (string.Equals(psHome, dir, StringComparison.OrdinalIgnoreCase) || - (alternateDirToCheck != null && string.Equals(alternateDirToCheck, dir, StringComparison.OrdinalIgnoreCase))) + (alternateDirToCheck is not null && string.Equals(alternateDirToCheck, dir, StringComparison.OrdinalIgnoreCase))) { // The ps1xml file no longer exists in $PSHOME. Downstream, we expect a resolved path, // which we can't really do b/c the file doesn't exist. @@ -4442,7 +4442,7 @@ private void SetModuleLoggingInformation(ModuleLoggingGroupPolicyStatus status, // if ((status & ModuleLoggingGroupPolicyStatus.Enabled) != 0) // { // } - if (((status & ModuleLoggingGroupPolicyStatus.Enabled) != 0) && moduleNames != null) + if (((status & ModuleLoggingGroupPolicyStatus.Enabled) != 0) && moduleNames is not null) { foreach (string currentGPModuleName in moduleNames) { @@ -4471,7 +4471,7 @@ internal static ModuleLoggingGroupPolicyStatus GetModuleLoggingInformation(out I ModuleLoggingGroupPolicyStatus status = ModuleLoggingGroupPolicyStatus.Undefined; var moduleLogging = Utils.GetPolicySetting(Utils.SystemWideThenCurrentUserConfig); - if (moduleLogging != null) + if (moduleLogging is not null) { if (moduleLogging.EnableModuleLogging == false) { @@ -4584,7 +4584,7 @@ internal string FixupFileName(string moduleBase, string name, string extension, : ResolveRootedFilePath(combinedPath, Context); // Return the path if successfully resolved. - if (resolvedPath != null) + if (resolvedPath is not null) { if (isImportingModule && resolvedPath.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) && !skipLoading) { @@ -4613,7 +4613,7 @@ internal string FixupFileName(string moduleBase, string name, string extension, extension.Equals(StringLiterals.PowerShellILExecutableExtension, StringComparison.OrdinalIgnoreCase))) { Assembly assembly = ExecutionContext.LoadAssembly(name: originalName, filename: null, error: out _); - if (assembly != null) + if (assembly is not null) { pathIsResolved = true; result = assembly.Location; @@ -4730,7 +4730,7 @@ internal static string GetResolvedPath(string filePath, ExecutionContext context Collection filePaths; - if (context != null && context.EngineSessionState != null && context.EngineSessionState.IsProviderLoaded(context.ProviderNames.FileSystem)) + if (context is not null && context.EngineSessionState is not null && context.EngineSessionState.IsProviderLoaded(context.ProviderNames.FileSystem)) { try { @@ -4767,7 +4767,7 @@ internal static Collection GetResolvedPathCollection(string filePath, Ex Collection filePaths; - if (context != null && context.EngineSessionState != null && context.EngineSessionState.IsProviderLoaded(context.ProviderNames.FileSystem)) + if (context is not null && context.EngineSessionState is not null && context.EngineSessionState.IsProviderLoaded(context.ProviderNames.FileSystem)) { try { @@ -4844,9 +4844,9 @@ internal static void CleanupWindowsPowerShellCompatResources(SessionState sessio lock (s_WindowsPowerShellCompatSyncObject) { var compatSession = GetWindowsPowerShellCompatRemotingSession(); - if (compatSession != null) + if (compatSession is not null) { - if (sessionState?.InvokeCommand.LocationChangedAction != null) + if (sessionState?.InvokeCommand.LocationChangedAction is not null) { sessionState.InvokeCommand.LocationChangedAction -= SyncCurrentLocationDelegate; } @@ -4883,8 +4883,8 @@ private void RemoveTypesAndFormatting( { try { - if (((formatFilesToRemove != null) && formatFilesToRemove.Count > 0) || - ((typeFilesToRemove != null) && typeFilesToRemove.Count > 0)) + if (((formatFilesToRemove is not null) && formatFilesToRemove.Count > 0) || + ((typeFilesToRemove is not null) && typeFilesToRemove.Count > 0)) { bool oldRefreshTypeFormatSetting = this.Context.InitialSessionState.RefreshTypeAndFormatSetting; try @@ -4944,7 +4944,7 @@ internal void RemoveModule(PSModuleInfo module, string moduleNameInRemoveModuleC if (Context.Modules.ModuleTable.ContainsKey(module.Path)) { // We should try to run OnRemove as the very first thing - if (module.OnRemove != null) + if (module.OnRemove is not null) { module.OnRemove.InvokeUsingCmdlet( contextCmdlet: this, @@ -4956,7 +4956,7 @@ internal void RemoveModule(PSModuleInfo module, string moduleNameInRemoveModuleC args: new object[] { module }); } - if (module.ImplementingAssembly != null && module.ImplementingAssembly.IsDynamic == false) + if (module.ImplementingAssembly is not null && module.ImplementingAssembly.IsDynamic == false) { var exportedTypes = PSSnapInHelpers.GetAssemblyTypes(module.ImplementingAssembly, module.Name); foreach (var type in exportedTypes) @@ -5017,7 +5017,7 @@ internal void RemoveModule(PSModuleInfo module, string moduleNameInRemoveModuleC foreach (KeyValuePair> pl in providers) { - Dbg.Assert(pl.Value != null, "There should never be a null list of entries in the provider table"); + Dbg.Assert(pl.Value is not null, "There should never be a null list of entries in the provider table"); // For each provider with this name, if it was imported from the module, // remove it from the list. @@ -5037,7 +5037,7 @@ internal void RemoveModule(PSModuleInfo module, string moduleNameInRemoveModuleC // Remove drives from all other module contexts. foreach (PSModuleInfo psmi in Context.Modules.ModuleTable.Values) { - if (psmi.SessionState != null) + if (psmi.SessionState is not null) { SessionStateInternal mssi = psmi.SessionState.Internal; if (mssi != Context.TopLevelSessionState && @@ -5069,7 +5069,7 @@ internal void RemoveModule(PSModuleInfo module, string moduleNameInRemoveModuleC SessionStateInternal ss = Context.EngineSessionState; - if (module.SessionState != null) + if (module.SessionState is not null) { // Remove the imported functions from SessionState... // (can't just go through module.SessionState.Internal.ExportedFunctions, @@ -5106,7 +5106,7 @@ internal void RemoveModule(PSModuleInfo module, string moduleNameInRemoveModuleC foreach (PSVariable mv in module.SessionState.Internal.ExportedVariables) { PSVariable sv = ss.GetVariable(mv.Name); - if (sv != null && sv == mv) + if (sv is not null && sv == mv) { ss.RemoveVariable(sv, BaseForce); string memberMessage = StringUtil.Format(Modules.RemovingImportedVariable, sv.Name); @@ -5146,7 +5146,7 @@ internal void RemoveModule(PSModuleInfo module, string moduleNameInRemoveModuleC foreach (KeyValuePair e in Context.Modules.ModuleTable) { PSModuleInfo m = e.Value; - if (m.SessionState != null) + if (m.SessionState is not null) { if (m.SessionState.Internal.ModuleTable.ContainsKey(module.Path)) { @@ -5175,7 +5175,7 @@ internal void RemoveModule(PSModuleInfo module, string moduleNameInRemoveModuleC foreach (var modInfo in Context.Modules.ModuleTable.Values) { var privateData = modInfo.PrivateData as Hashtable; - if ((privateData != null) && privateData.ContainsKey("ImplicitRemoting")) + if ((privateData is not null) && privateData.ContainsKey("ImplicitRemoting")) { Context.Modules.IsImplicitRemotingModuleLoaded = true; break; @@ -5444,7 +5444,7 @@ internal string GetDefaultPrefix(PSModuleInfo module) { string throwAwayScriptName; ExternalScriptInfo scriptInfo = GetScriptInfoForFile(module.Path, out throwAwayScriptName, true); - Dbg.Assert(scriptInfo != null, "scriptInfo for module (.psd1) can't be null"); + Dbg.Assert(scriptInfo is not null, "scriptInfo for module (.psd1) can't be null"); bool containedErrors = false; Hashtable data = null; Hashtable localizedData = null; @@ -5454,7 +5454,7 @@ internal string GetDefaultPrefix(PSModuleInfo module) // Get Default prefix if (data.Contains("DefaultCommandPrefix")) { - if (localizedData != null && localizedData.Contains("DefaultCommandPrefix")) + if (localizedData is not null && localizedData.Contains("DefaultCommandPrefix")) { prefix = (string)LanguagePrimitives.ConvertTo(localizedData["DefaultCommandPrefix"], typeof(string), CultureInfo.InvariantCulture); @@ -5547,7 +5547,7 @@ internal PSModuleInfo LoadModule(PSModuleInfo parentModule, string fileName, str SessionState ss, object privateData, ref ImportModuleOptions options, ManifestProcessingFlags manifestProcessingFlags, out bool found, out bool moduleFileFound) { - Dbg.Assert(fileName != null, "Filename argument to LoadModule() shouldn't be null"); + Dbg.Assert(fileName is not null, "Filename argument to LoadModule() shouldn't be null"); if (!File.Exists(fileName)) { @@ -5582,7 +5582,7 @@ internal PSModuleInfo LoadModule(PSModuleInfo parentModule, string fileName, str } // If MinimumVersion/RequiredVersion/MaximumVersion has been specified, then only try to process manifest modules... - if (BaseMinimumVersion != null || BaseMaximumVersion != null || BaseRequiredVersion != null || BaseGuid != null) + if (BaseMinimumVersion is not null || BaseMaximumVersion is not null || BaseRequiredVersion is not null || BaseGuid is not null) { // If the -Version flag was specified, don't look for non-manifest modules if (string.IsNullOrEmpty(ext) || !ext.Equals(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase)) @@ -5758,7 +5758,7 @@ internal PSModuleInfo LoadModule(PSModuleInfo parentModule, string fileName, str // This module info is created so that we can keep the behavior consistent between scripts imported as modules and other kind of modules(all of them should have a PSModuleInfo). // Auto-loading expects we always have a PSModuleInfo object for any module. This is how this issue was found. var ps1ScriptInfo = GetScriptInfoForFile(fileName, out scriptName, true); - Dbg.Assert(ps1ScriptInfo != null, "Scriptinfo for dotted file can't be null"); + Dbg.Assert(ps1ScriptInfo is not null, "Scriptinfo for dotted file can't be null"); module = new PSModuleInfo(ModuleIntrinsics.GetModuleName(fileName), fileName, Context, ss, ps1ScriptInfo.DefiningLanguageMode); message = StringUtil.Format(Modules.DottingScriptFile, fileName); @@ -5789,7 +5789,7 @@ internal PSModuleInfo LoadModule(PSModuleInfo parentModule, string fileName, str { // since useLocalScope is set false while calling InvokeWithPipe, we need to // revert the changes made to LocalsTuple - if (Context.EngineSessionState.CurrentScope.LocalsTuple != null) + if (Context.EngineSessionState.CurrentScope.LocalsTuple is not null) { Context.EngineSessionState.CurrentScope.LocalsTuple.SetAutomaticVariable( AutomaticVariable.PSScriptRoot, oldPSScriptRoot, Context); @@ -5838,7 +5838,7 @@ internal PSModuleInfo LoadModule(PSModuleInfo parentModule, string fileName, str { var psd1ScriptInfo = GetScriptInfoForFile(fileName, out scriptName, true); found = true; - Dbg.Assert(psd1ScriptInfo != null, "Scriptinfo for module manifest (.psd1) can't be null"); + Dbg.Assert(psd1ScriptInfo is not null, "Scriptinfo for module manifest (.psd1) can't be null"); module = LoadModuleManifest( psd1ScriptInfo, manifestProcessingFlags, @@ -5848,7 +5848,7 @@ internal PSModuleInfo LoadModule(PSModuleInfo parentModule, string fileName, str BaseGuid, ref options); - if (module != null) + if (module is not null) { CheckForDisallowedDotSourcing(module.SessionState, psd1ScriptInfo, options); @@ -5863,7 +5863,7 @@ internal PSModuleInfo LoadModule(PSModuleInfo parentModule, string fileName, str WriteObject(module); } } - else if (BaseMinimumVersion != null || BaseRequiredVersion != null || BaseGuid != null || BaseMaximumVersion != null) + else if (BaseMinimumVersion is not null || BaseRequiredVersion is not null || BaseGuid is not null || BaseMaximumVersion is not null) { found = false; } @@ -5874,7 +5874,7 @@ internal PSModuleInfo LoadModule(PSModuleInfo parentModule, string fileName, str { module = LoadBinaryModule(false, ModuleIntrinsics.GetModuleName(fileName), fileName, null, moduleBase, ss, options, manifestProcessingFlags, prefix, true, true, out found); - if (found && module != null) + if (found && module is not null) { // LanguageMode does not apply to binary modules module.LanguageMode = (PSLanguageMode?)null; @@ -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 is not null && moduleBase is null && this.AddToAppDomainLevelCache) { // Cache using the actual name specified by the user rather than the module basename PSModuleInfo.AddToAppDomainLevelModuleCache(module.Name, fileName, this.BaseForce); @@ -6032,7 +6032,7 @@ private void CheckForDisallowedDotSourcing( }, searchNestedScriptBlocks: true).FirstOrDefault(); - if (dotSourceOperator != null) + if (dotSourceOperator is not null) { var errorRecord = new ErrorRecord( new PSSecurityException(Modules.CannotUseDotSourceWithWildCardFunctionExport), @@ -6049,9 +6049,9 @@ private static bool ShouldProcessScriptModule(PSModuleInfo parentModule, ref boo // If we are in module analysis and the parent module declares non-wildcarded exports, then we don't need to // actually process the script module. - if (parentModule != null) + if (parentModule is not null) { - if (shouldProcessModule && (parentModule.DeclaredFunctionExports != null) && (parentModule.DeclaredFunctionExports.Count > 0)) + if (shouldProcessModule && (parentModule.DeclaredFunctionExports is not null) && (parentModule.DeclaredFunctionExports.Count > 0)) { shouldProcessModule = false; @@ -6103,7 +6103,7 @@ private static BinaryAnalysisResult GetCmdletsFromBinaryModuleImplementation(str s_binaryAnalysisCache.TryGetValue(path, out tuple); } - if (tuple != null) + if (tuple is not null) { assemblyVersion = tuple.Item2; return tuple.Item1; @@ -6139,7 +6139,7 @@ private BinaryAnalysisResult GetCmdletsFromBinaryModuleImplementation(string pat s_binaryAnalysisCache.TryGetValue(path, out tuple); } - if (tuple != null) + if (tuple is not null) { assemblyVersion = tuple.Item2; return tuple.Item1; @@ -6228,7 +6228,7 @@ private static void AnalyzeSnapinDomainHelper() assembly = ExecutionContext.LoadAssembly(path, null, out ignored); } - if (assembly != null) + if (assembly is not null) { assemblyVersion = GetAssemblyVersionNumber(assembly); } @@ -6238,7 +6238,7 @@ private static void AnalyzeSnapinDomainHelper() { } - if (assembly != null) + if (assembly is not null) { PSSnapInHelpers.AnalyzePSSnapInAssembly(assembly, assembly.Location, null, null, isModuleLoad, out cmdlets, out aliases, out providers, out throwAwayHelpFile); } @@ -6251,7 +6251,7 @@ private static void AnalyzeSnapinDomainHelper() List detectedCmdlets = new List(); List> detectedAliases = new List>(); - if (cmdlets != null) + if (cmdlets is not null) { foreach (SessionStateCmdletEntry cmdlet in cmdlets.Values) { @@ -6259,7 +6259,7 @@ private static void AnalyzeSnapinDomainHelper() } } - if (aliases != null) + if (aliases is not null) { foreach (List aliasList in aliases.Values) { @@ -6290,7 +6290,7 @@ private PSModuleInfo AnalyzeScriptFile(string filename, bool force, ExecutionCon s_scriptAnalysisCache.TryGetValue(filename, out module); } - if (module != null) + if (module is not null) return module.Clone(); // fake/empty manifestInfo for processing in (!loadElements) mode @@ -6301,7 +6301,7 @@ private PSModuleInfo AnalyzeScriptFile(string filename, bool force, ExecutionCon var exportedCommands = AnalysisCache.GetExportedCommands(filename, true, context); // If we have this info cached, return from the cache. - if (exportedCommands != null) + if (exportedCommands is not null) { foreach (var pair in exportedCommands) { @@ -6412,7 +6412,7 @@ private PSModuleInfo AnalyzeScriptFile(string filename, bool force, ExecutionCon moduleToProcess = Path.Combine(moduleDirectory, moduleToProcess); PSModuleInfo fileBasedModule = CreateModuleInfoForGetModule(moduleToProcess, true); - if (fileBasedModule != null) + if (fileBasedModule is not null) { processedModules.Add(fileBasedModule); } @@ -6561,7 +6561,7 @@ internal PSModuleInfo LoadBinaryModule(PSModuleInfo parentModule, bool trySnapIn var importingModule = 0 != (manifestProcessingFlags & ManifestProcessingFlags.LoadElements); // See if we're loading a straight assembly... - if (assemblyToLoad != null) + if (assemblyToLoad is not null) { // Figure out what to use for a module path... if (!string.IsNullOrEmpty(fileName)) @@ -6584,7 +6584,7 @@ internal PSModuleInfo LoadBinaryModule(PSModuleInfo parentModule, bool trySnapIn // Passing module as a parameter here so that the providers can have the module property populated. // For engine providers, the module should point to top-level module name // For FileSystem, the module is Microsoft.PowerShell.Core and not System.Management.Automation - if (parentModule != null && InitialSessionState.IsEngineModule(parentModule.Name)) + if (parentModule is not null && InitialSessionState.IsEngineModule(parentModule.Name)) { iss.ImportCmdletsFromAssembly(assemblyToLoad, parentModule); } @@ -6609,7 +6609,7 @@ internal PSModuleInfo LoadBinaryModule(PSModuleInfo parentModule, bool trySnapIn else { // Avoid trying to import a PowerShell assembly as Snapin as it results in PSArgumentException - if ((moduleName != null) && Utils.IsPowerShellAssembly(moduleName)) + if ((moduleName is not null) && Utils.IsPowerShellAssembly(moduleName)) { trySnapInName = false; } @@ -6634,7 +6634,7 @@ internal PSModuleInfo LoadBinaryModule(PSModuleInfo parentModule, bool trySnapIn } #endif - if (snapin != null) + if (snapin is not null) { importSuccessful = true; if (string.IsNullOrEmpty(fileName)) @@ -6674,7 +6674,7 @@ internal PSModuleInfo LoadBinaryModule(PSModuleInfo parentModule, bool trySnapIn if (assembly is null) { - if (error != null) + if (error is not null) throw error; found = false; @@ -6691,7 +6691,7 @@ internal PSModuleInfo LoadBinaryModule(PSModuleInfo parentModule, bool trySnapIn // Passing module as a parameter here so that the providers can have the module property populated. // For engine providers, the module should point to top-level module name // For FileSystem, the module is Microsoft.PowerShell.Core and not System.Management.Automation - if (parentModule != null && InitialSessionState.IsEngineModule(parentModule.Name)) + if (parentModule is not null && InitialSessionState.IsEngineModule(parentModule.Name)) { iss.ImportCmdletsFromAssembly(assembly, parentModule); } @@ -6761,7 +6761,7 @@ internal PSModuleInfo LoadBinaryModule(PSModuleInfo parentModule, bool trySnapIn { // For engine providers, the module should point to top-level module name // For FileSystem, the module is Microsoft.PowerShell.Core and not System.Management.Automation - if (parentModule != null && InitialSessionState.IsEngineModule(parentModule.Name)) + if (parentModule is not null && InitialSessionState.IsEngineModule(parentModule.Name)) { sspe.SetModule(parentModule); } @@ -6772,7 +6772,7 @@ internal PSModuleInfo LoadBinaryModule(PSModuleInfo parentModule, bool trySnapIn } // Add all of the exported cmdlets to the module object... - if (iss.Commands != null) + if (iss.Commands is not null) { foreach (SessionStateCommandEntry commandEntry in iss.Commands) { @@ -6788,14 +6788,14 @@ internal PSModuleInfo LoadBinaryModule(PSModuleInfo parentModule, bool trySnapIn aliasEntry = commandEntry as SessionStateAliasEntry; } - Dbg.Assert((cmdletEntry != null || aliasEntry != null), "When importing a binary module, the commands entry should only have cmdlets/aliases in it"); - if (ss != null) + Dbg.Assert((cmdletEntry is not null || aliasEntry is not null), "When importing a binary module, the commands entry should only have cmdlets/aliases in it"); + if (ss is not null) { - if (cmdletEntry != null) + if (cmdletEntry is not null) { ss.Internal.ExportedCmdlets.Add(CommandDiscovery.NewCmdletInfo(cmdletEntry, this.Context)); } - else if (aliasEntry != null) + else if (aliasEntry is not null) { ss.Internal.ExportedAliases.Add(CommandDiscovery.NewAliasInfo(aliasEntry, this.Context)); } @@ -6804,11 +6804,11 @@ internal PSModuleInfo LoadBinaryModule(PSModuleInfo parentModule, bool trySnapIn { // If there is no session state, we need to attach the entry to the module instead // of the session state. - if (cmdletEntry != null) + if (cmdletEntry is not null) { module.AddExportedCmdlet(CommandDiscovery.NewCmdletInfo(cmdletEntry, this.Context)); } - else if (aliasEntry != null) + else if (aliasEntry is not null) { module.AddExportedAlias(CommandDiscovery.NewAliasInfo(aliasEntry, this.Context)); } @@ -6817,7 +6817,7 @@ internal PSModuleInfo LoadBinaryModule(PSModuleInfo parentModule, bool trySnapIn } // If there were any cmdlets that were detected, add those. - if (detectedCmdlets != null) + if (detectedCmdlets is not null) { foreach (string detectedCmdlet in detectedCmdlets) { @@ -6826,7 +6826,7 @@ internal PSModuleInfo LoadBinaryModule(PSModuleInfo parentModule, bool trySnapIn } // If there were any aliases that were detected, add those. - if (detectedAliases != null) + if (detectedAliases is not null) { foreach (Tuple detectedAlias in detectedAliases) { @@ -6836,7 +6836,7 @@ internal PSModuleInfo LoadBinaryModule(PSModuleInfo parentModule, bool trySnapIn // If any command patterns where specified, then only import the // commands matching the patterns... - if (BaseCmdletPatterns != null) + if (BaseCmdletPatterns is not null) { InitialSessionStateEntryCollection commands = iss.Commands; // Remove all of the command entries that aren't matched by a pattern @@ -6870,7 +6870,7 @@ internal PSModuleInfo LoadBinaryModule(PSModuleInfo parentModule, bool trySnapIn { // If we have a session state instance, set it to be the engine sessionstate // for the duration of the bind. - if (ss != null) + if (ss is not null) { Context.EngineSessionState = ss.Internal; } @@ -6883,11 +6883,11 @@ internal PSModuleInfo LoadBinaryModule(PSModuleInfo parentModule, bool trySnapIn // Scan all of the types in the assembly to register JobSourceAdapters. IEnumerable allTypes = new Type[] { }; - if (assembly != null) + if (assembly is not null) { allTypes = assembly.ExportedTypes; } - else if (assemblyToLoad != null) + else if (assemblyToLoad is not null) { allTypes = assemblyToLoad.ExportedTypes; } @@ -6977,7 +6977,7 @@ private static Version GetAssemblyVersionNumber(Assembly assemblyToLoad) internal static string AddPrefixToCommandName(string commandName, string prefix) { - Dbg.Assert(commandName != null, "Caller should verify that commandName argument != null"); + Dbg.Assert(commandName is not null, "Caller should verify that commandName argument is not null"); if (string.IsNullOrEmpty(prefix)) return commandName; @@ -7004,8 +7004,8 @@ internal static string AddPrefixToCommandName(string commandName, string prefix) /// The command name without the prefix. internal static string RemovePrefixFromCommandName(string commandName, string prefix) { - Dbg.Assert(commandName != null, "Caller should verify that commandName argument != null"); - Dbg.Assert(prefix != null, "Caller should verify that prefix argument != null"); + Dbg.Assert(commandName is not null, "Caller should verify that commandName argument is not null"); + Dbg.Assert(prefix is not null, "Caller should verify that prefix argument is not null"); string result = commandName; @@ -7035,7 +7035,7 @@ internal static string RemovePrefixFromCommandName(string commandName, string pr internal static bool IsPrefixedCommand(CommandInfo commandInfo) { - Dbg.Assert(commandInfo != null, "Caller should verify that commandInfo is not null"); + Dbg.Assert(commandInfo is not null, "Caller should verify that commandInfo is not null"); Dbg.Assert(!string.IsNullOrEmpty(commandInfo.Prefix), "Caller should verify that the commandInfo has prefix"); string verb, noun; @@ -7048,9 +7048,9 @@ internal static bool IsPrefixedCommand(CommandInfo commandInfo) internal static void AddModuleToModuleTables(ExecutionContext context, SessionStateInternal targetSessionState, PSModuleInfo module) { - Dbg.Assert(context != null, "Caller should verify that context != null"); - Dbg.Assert(targetSessionState != null, "Caller should verify that targetSessionState != null"); - Dbg.Assert(module != null, "Caller should verify that module != null"); + Dbg.Assert(context is not null, "Caller should verify that context is not null"); + Dbg.Assert(targetSessionState is not null, "Caller should verify that targetSessionState is not null"); + Dbg.Assert(module is not null, "Caller should verify that module is not null"); // if the module path is empty (assembly module in memory), we add the modulename as key string moduleTableKey; @@ -7081,14 +7081,14 @@ internal static void AddModuleToModuleTables(ExecutionContext context, SessionSt targetSessionState.ModuleTableKeys.Add(moduleTableKey); } - if (targetSessionState.Module != null) + if (targetSessionState.Module is not null) { targetSessionState.Module.AddNestedModule(module); } var privateDataHashTable = module.PrivateData as Hashtable; if (context.Modules.IsImplicitRemotingModuleLoaded == false && - privateDataHashTable != null && privateDataHashTable.ContainsKey("ImplicitRemoting")) + privateDataHashTable is not null && privateDataHashTable.ContainsKey("ImplicitRemoting")) { context.Modules.IsImplicitRemotingModuleLoaded = true; } @@ -7162,7 +7162,7 @@ internal static void ImportModuleMembers( // TODO/FIXME: we should be calling AddModuleToModuleTables here but we can't // because of the inconsistency with which dynamic modules should // or should not be included in the global modules table - if (targetSessionState.Module != null) + if (targetSessionState.Module is not null) { bool present = false; foreach (PSModuleInfo m in targetSessionState.Module.NestedModules) @@ -7178,7 +7178,7 @@ internal static void ImportModuleMembers( } SessionStateInternal source = null; - if (sourceModule.SessionState != null) + if (sourceModule.SessionState is not null) { source = sourceModule.SessionState.Internal; } @@ -7282,7 +7282,7 @@ internal static void ImportModuleMembers( // Only process functions, variables and aliases if there is a session state // associated with the source module. - if (source != null) + if (source is not null) { foreach (FunctionInfo func in sourceModule.ExportedFunctions.Values) { @@ -7294,7 +7294,7 @@ internal static void ImportModuleMembers( { if (SessionStateUtilities.MatchesAnyWildcardPattern(v.Name, variablePatterns, noPatternsSpecified)) { - if (options.NoClobber && (targetSessionState.ModuleScope.GetVariable(v.Name) != null)) + if (options.NoClobber && (targetSessionState.ModuleScope.GetVariable(v.Name) is not null)) { // The verbose output for Import-Module -NoClobber should state which members were skipped due to conflicts with existing names in the caller's environment. message = StringUtil.Format(Modules.ImportModuleNoClobberForVariable, v.Name); @@ -7552,7 +7552,7 @@ internal static PSSnapInInfo GetEngineSnapIn(ExecutionContext context, string na foreach (CmdletInfo cmdlet in cmdlets) { PSSnapInInfo snapin = cmdlet.PSSnapIn; - if (snapin != null && !snapinSet.Contains(snapin)) + if (snapin is not null && !snapinSet.Contains(snapin)) snapinSet.Add(snapin); } diff --git a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs index 7365cb3546d..351571613db 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs @@ -171,7 +171,7 @@ private PSModuleInfo CreateModuleImplementation(string name, string path, object // Build the scriptblock at this point so the references to the module // context are correct... ExternalScriptInfo scriptInfo = moduleCode as ExternalScriptInfo; - if (scriptInfo != null) + if (scriptInfo is not null) { sb = scriptInfo.ScriptBlock; @@ -180,7 +180,7 @@ private PSModuleInfo CreateModuleImplementation(string name, string path, object else { sb = moduleCode as ScriptBlock; - if (sb != null) + if (sb is not null) { PSLanguageMode? moduleLanguageMode = sb.LanguageMode; sb = sb.Clone(); @@ -191,7 +191,7 @@ private PSModuleInfo CreateModuleImplementation(string name, string path, object else { var sbText = moduleCode as string; - if (sbText != null) + if (sbText is not null) sb = ScriptBlock.Create(_context, sbText); } } @@ -207,7 +207,7 @@ private PSModuleInfo CreateModuleImplementation(string name, string path, object // Save the module string module._definitionExtent = sb.Ast.Extent; var ast = sb.Ast; - while (ast.Parent != null) + while (ast.Parent is not null) { ast = ast.Parent; } @@ -601,7 +601,7 @@ internal static bool AreModuleFieldsMatchingConstraints( { // If a name is required, check that it matches. // A required module name may also be an absolute path, so check it against the given module's path as well. - if (requiredName != null + if (requiredName is not null && !requiredName.Equals(moduleName, StringComparison.OrdinalIgnoreCase) && !MatchesModulePath(modulePath, requiredName)) { @@ -610,7 +610,7 @@ internal static bool AreModuleFieldsMatchingConstraints( } // If a GUID is required, check it matches - if (requiredGuid != null && !requiredGuid.Equals(moduleGuid)) + if (requiredGuid is not null && !requiredGuid.Equals(moduleGuid)) { matchFailureReason = ModuleMatchFailure.Guid; return false; @@ -659,24 +659,24 @@ internal static bool IsVersionMatchingConstraints( Version minimumVersion = null, Version maximumVersion = null) { - Dbg.Assert(version != null, $"Caller to verify that {nameof(version)} is not null"); + Dbg.Assert(version is not null, $"Caller to verify that {nameof(version)} is not null"); // If a RequiredVersion is given it overrides other version settings - if (requiredVersion != null) + if (requiredVersion is not null) { matchFailureReason = ModuleMatchFailure.RequiredVersion; return requiredVersion.Equals(version); } // Check the version is at least the minimum version - if (minimumVersion != null && version < minimumVersion) + if (minimumVersion is not null && version < minimumVersion) { matchFailureReason = ModuleMatchFailure.MinimumVersion; return false; } // Check the version is at most the maximum version - if (maximumVersion != null && version > maximumVersion) + if (maximumVersion is not null && version > maximumVersion) { matchFailureReason = ModuleMatchFailure.MaximumVersion; return false; @@ -695,7 +695,7 @@ internal static bool IsVersionMatchingConstraints( /// True if the module path matches the required path, false otherwise. internal static bool MatchesModulePath(string modulePath, string requiredPath) { - Dbg.Assert(requiredPath != null, $"Caller to verify that {nameof(requiredPath)} is not null"); + Dbg.Assert(requiredPath is not null, $"Caller to verify that {nameof(requiredPath)} is not null"); if (modulePath is null) { @@ -814,7 +814,7 @@ internal static Version GetManifestModuleVersion(string manifestPath) PsUtils.ManifestModuleVersionPropertyName); object versionValue = dataFileSetting["ModuleVersion"]; - if (versionValue != null) + if (versionValue is not null) { Version moduleVersion; if (LanguagePrimitives.TryConvertTo(versionValue, out moduleVersion)) @@ -838,7 +838,7 @@ internal static Guid GetManifestGuid(string manifestPath) PsUtils.ManifestGuidPropertyName); object guidValue = dataFileSetting["GUID"]; - if (guidValue != null) + if (guidValue is not null) { Guid guidID; if (LanguagePrimitives.TryConvertTo(guidValue, out guidID)) @@ -865,7 +865,7 @@ internal static ExperimentalFeature[] GetExperimentalFeature(string manifestPath if (privateData is Hashtable hashData && hashData["PSData"] is Hashtable psData) { object expFeatureValue = psData["ExperimentalFeatures"]; - if (expFeatureValue != null && + if (expFeatureValue is not null && LanguagePrimitives.TryConvertTo(expFeatureValue, out Hashtable[] features) && features.Length > 0) { @@ -977,7 +977,7 @@ internal static string GetPersonalModulePath() /// The PSHome module path. internal static string GetPSHomeModulePath() { - if (s_psHomeModulePath != null) + if (s_psHomeModulePath is not null) { return s_psHomeModulePath; } @@ -1093,8 +1093,8 @@ internal static string GetExpandedEnvironmentVariable(string name, EnvironmentVa private static int PathContainsSubstring(string pathToScan, string pathToLookFor) { // we don't support if any of the args are null - parent function should ensure this; empty values are ok - Diagnostics.Assert(pathToScan != null, "pathToScan should not be null according to contract of the function"); - Diagnostics.Assert(pathToLookFor != null, "pathToLookFor should not be null according to contract of the function"); + Diagnostics.Assert(pathToScan is not null, "pathToScan should not be null according to contract of the function"); + Diagnostics.Assert(pathToLookFor is not null, "pathToLookFor should not be null according to contract of the function"); int pos = 0; // position of the current substring in pathToScan string[] substrings = pathToScan.Split(Utils.Separators.PathSeparator, StringSplitOptions.None); // we want to process empty entries @@ -1129,8 +1129,8 @@ private static int PathContainsSubstring(string pathToScan, string pathToLookFor private static string AddToPath(string basePath, string pathToAdd, int insertPosition) { // we don't support if any of the args are null - parent function should ensure this; empty values are ok - Diagnostics.Assert(basePath != null, "basePath should not be null according to contract of the function"); - Diagnostics.Assert(pathToAdd != null, "pathToAdd should not be null according to contract of the function"); + Diagnostics.Assert(basePath is not null, "basePath should not be null according to contract of the function"); + Diagnostics.Assert(pathToAdd is not null, "pathToAdd should not be null according to contract of the function"); StringBuilder result = new StringBuilder(basePath); @@ -1339,7 +1339,7 @@ internal static IEnumerable GetModulePath(bool includeSystemModulePath, foreach (string envPath in modulePathString.Split(Utils.Separators.PathSeparator, StringSplitOptions.RemoveEmptyEntries)) { var processedPath = ProcessOneModulePath(context, envPath, processedPathSet); - if (processedPath != null) + if (processedPath is not null) yield return processedPath; } } @@ -1347,7 +1347,7 @@ internal static IEnumerable GetModulePath(bool includeSystemModulePath, if (includeSystemModulePath) { var processedPath = ProcessOneModulePath(context, GetPSHomeModulePath(), processedPathSet); - if (processedPath != null) + if (processedPath is not null) yield return processedPath; } } @@ -1405,7 +1405,7 @@ private static string ProcessOneModulePath(ExecutionContext context, string envP // volume identifier (for example, "c:\" is Supported but not "c:\temp\Z:\invalidPath") } - if (provider != null && resolvedPaths != null && provider.NameEquals(context.ProviderNames.FileSystem)) + if (provider is not null && resolvedPaths is not null && provider.NameEquals(context.ProviderNames.FileSystem)) { var result = resolvedPaths.FirstOrDefault(); if (processedPathSet.Add(result)) @@ -1447,7 +1447,7 @@ internal static void RemoveNestedModuleFunctions(PSModuleInfo module) private static void SortAndRemoveDuplicates(List input, Func keyGetter) { - Dbg.Assert(input != null, "Caller should verify that input != null"); + Dbg.Assert(input is not null, "Caller should verify that input is not null"); input.Sort( delegate (T x, T y) @@ -1501,7 +1501,7 @@ internal static void ExportModuleMembers( sessionState.UseExportList = true; - if (functionPatterns != null) + if (functionPatterns is not null) { sessionState.FunctionsExported = true; if (PatternContainsWildcard(functionPatterns)) @@ -1530,7 +1530,7 @@ internal static void ExportModuleMembers( SortAndRemoveDuplicates(sessionState.ExportedFunctions, delegate (FunctionInfo ci) { return ci.Name; }); } - if (cmdletPatterns != null) + if (cmdletPatterns is not null) { IDictionary> ft = sessionState.ModuleScope.CmdletTable; @@ -1554,7 +1554,7 @@ internal static void ExportModuleMembers( CmdletInfo exportedCmdlet = new CmdletInfo(element.Name, element.ImplementingType, element.HelpFile, null, element.Context) { Module = sessionState.Module }; - Dbg.Assert(sessionState.Module != null, "sessionState.Module should not be null by the time we're exporting cmdlets"); + Dbg.Assert(sessionState.Module is not null, "sessionState.Module should not be null by the time we're exporting cmdlets"); sessionState.Module.CompiledExports.Add(exportedCmdlet); } } @@ -1576,7 +1576,7 @@ internal static void ExportModuleMembers( CmdletInfo exportedCmdlet = new CmdletInfo(cmdletToImport.Name, cmdletToImport.ImplementingType, cmdletToImport.HelpFile, null, cmdletToImport.Context) { Module = sessionState.Module }; - Dbg.Assert(sessionState.Module != null, "sessionState.Module should not be null by the time we're exporting cmdlets"); + Dbg.Assert(sessionState.Module is not null, "sessionState.Module should not be null by the time we're exporting cmdlets"); sessionState.Module.CompiledExports.Add(exportedCmdlet); } } @@ -1585,7 +1585,7 @@ internal static void ExportModuleMembers( SortAndRemoveDuplicates(sessionState.Module.CompiledExports, delegate (CmdletInfo ci) { return ci.Name; }); } - if (variablePatterns != null) + if (variablePatterns is not null) { IDictionary vt = sessionState.ModuleScope.Variables; @@ -1608,7 +1608,7 @@ internal static void ExportModuleMembers( SortAndRemoveDuplicates(sessionState.ExportedVariables, delegate (PSVariable v) { return v.Name; }); } - if (aliasPatterns != null) + if (aliasPatterns is not null) { IEnumerable mai = sessionState.ModuleScope.AliasTable; @@ -1656,7 +1656,7 @@ internal static void ExportModuleMembers( /// True if pattern contains '*'. internal static bool PatternContainsWildcard(List list) { - if (list != null) + if (list is not null) { foreach (var item in list) { @@ -1672,9 +1672,9 @@ internal static bool PatternContainsWildcard(List list) private static AliasInfo NewAliasInfo(AliasInfo alias, SessionStateInternal sessionState) { - Dbg.Assert(alias != null, "alias should not be null"); - Dbg.Assert(sessionState != null, "sessionState should not be null"); - Dbg.Assert(sessionState.Module != null, "sessionState.Module should not be null by the time we're exporting aliases"); + Dbg.Assert(alias is not null, "alias should not be null"); + Dbg.Assert(sessionState is not null, "sessionState should not be null"); + Dbg.Assert(sessionState.Module is not null, "sessionState.Module should not be null by the time we're exporting aliases"); // Copy the alias info, changing the module association to be the current module... var aliasCopy = new AliasInfo(alias.Name, alias.Definition, alias.Context, alias.Options) diff --git a/src/System.Management.Automation/engine/Modules/ModuleSpecification.cs b/src/System.Management.Automation/engine/Modules/ModuleSpecification.cs index e03a8f8de01..88ce2a0c50a 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleSpecification.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleSpecification.cs @@ -73,7 +73,7 @@ public ModuleSpecification(Hashtable moduleSpecification) } var exception = ModuleSpecificationInitHelper(this, moduleSpecification); - if (exception != null) + if (exception is not null) { throw exception; } @@ -155,13 +155,13 @@ internal static Exception ModuleSpecificationInitHelper(ModuleSpecification modu return new MissingMemberException(message); } - if (moduleSpecification.RequiredVersion != null && moduleSpecification.Version != null) + if (moduleSpecification.RequiredVersion is not null && moduleSpecification.Version is not null) { message = StringUtil.Format(SessionStateStrings.GetContent_TailAndHeadCannotCoexist, "ModuleVersion", "RequiredVersion"); return new ArgumentException(message); } - if (moduleSpecification.RequiredVersion != null && moduleSpecification.MaximumVersion != null) + if (moduleSpecification.RequiredVersion is not null && moduleSpecification.MaximumVersion is not null) { message = StringUtil.Format(SessionStateStrings.GetContent_TailAndHeadCannotCoexist, "MaximumVersion", "RequiredVersion"); return new ArgumentException(message); @@ -199,23 +199,23 @@ public override string ToString() moduleSpecBuilder.Append("@{ ModuleName = '").Append(Name).Append("'"); - if (Guid != null) + if (Guid is not null) { moduleSpecBuilder.Append("; Guid = '{").Append(Guid).Append("}' "); } - if (RequiredVersion != null) + if (RequiredVersion is not null) { moduleSpecBuilder.Append("; RequiredVersion = '").Append(RequiredVersion).Append("'"); } else { - if (Version != null) + if (Version is not null) { moduleSpecBuilder.Append("; ModuleVersion = '").Append(Version).Append("'"); } - if (MaximumVersion != null) + if (MaximumVersion is not null) { moduleSpecBuilder.Append("; MaximumVersion = '").Append(MaximumVersion).Append("'"); } @@ -321,7 +321,7 @@ public bool Equals(ModuleSpecification x, ModuleSpecification y) return true; } - return x != null && y != null + return x is not null && y is not null && string.Equals(x.Name, y.Name, StringComparison.OrdinalIgnoreCase) && Guid.Equals(x.Guid, y.Guid) && Version.Equals(x.RequiredVersion, y.RequiredVersion) diff --git a/src/System.Management.Automation/engine/Modules/ModuleUtils.cs b/src/System.Management.Automation/engine/Modules/ModuleUtils.cs index 4432b4e870f..29c8f6382bd 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleUtils.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleUtils.cs @@ -144,7 +144,7 @@ internal static IEnumerable GetDefaultAvailableModuleFiles(bool isForAut // Write a progress message for UNC paths, so that users know what is happening try { - if ((context.CurrentCommandProcessor != null) && Utils.PathIsUnc(directory)) + if ((context.CurrentCommandProcessor is not null) && Utils.PathIsUnc(directory)) { analysisProgress = new ProgressRecord(0, Modules.DeterminingAvailableModules, @@ -360,7 +360,7 @@ internal static bool IsModuleInVersionSubdirectory(string modulePath, out Versio { version = null; string folderName = Path.GetDirectoryName(modulePath); - if (folderName != null) + if (folderName is not null) { folderName = Path.GetFileName(folderName); return Version.TryParse(folderName, out version); @@ -423,7 +423,7 @@ internal static IEnumerable GetMatchingCommands(string pattern, Exe PSModuleAutoLoadingPreference moduleAutoLoadingPreference = CommandDiscovery.GetCommandDiscoveryPreference(context, SpecialVariables.PSModuleAutoLoadingPreferenceVarPath, "PSModuleAutoLoadingPreference"); if ((moduleAutoLoadingPreference != PSModuleAutoLoadingPreference.None) && - ((commandOrigin == CommandOrigin.Internal) || ((cmdletInfo != null) && (cmdletInfo.Visibility == SessionStateEntryVisibility.Public)))) + ((commandOrigin == CommandOrigin.Internal) || ((cmdletInfo is not null) && (cmdletInfo.Visibility == SessionStateEntryVisibility.Public)))) { foreach (string modulePath in GetDefaultAvailableModuleFiles(isForAutoDiscovery: false, context)) { @@ -517,17 +517,17 @@ internal static IEnumerable GetMatchingCommands(string pattern, Exe bool shouldExportCommand = true; // Verify that we don't already have it represented in the initial session state. - if ((context.InitialSessionState != null) && (commandOrigin == CommandOrigin.Runspace)) + if ((context.InitialSessionState is not null) && (commandOrigin == CommandOrigin.Runspace)) { foreach (SessionStateCommandEntry commandEntry in context.InitialSessionState.Commands[commandName]) { string moduleCompareName = null; - if (commandEntry.Module != null) + if (commandEntry.Module is not null) { moduleCompareName = commandEntry.Module.Name; } - else if (commandEntry.PSSnapIn != null) + else if (commandEntry.PSSnapIn is not null) { moduleCompareName = commandEntry.PSSnapIn.Name; } diff --git a/src/System.Management.Automation/engine/Modules/NewModuleCommand.cs b/src/System.Management.Automation/engine/Modules/NewModuleCommand.cs index a2e23348e46..8fff7022f55 100644 --- a/src/System.Management.Automation/engine/Modules/NewModuleCommand.cs +++ b/src/System.Management.Automation/engine/Modules/NewModuleCommand.cs @@ -155,7 +155,7 @@ public object[] ArgumentList protected override void EndProcessing() { // Create a module from a scriptblock... - if (_scriptBlock != null) + if (_scriptBlock is not null) { // Check ScriptBlock language mode. If it is different than the context language mode // then throw error since private trusted script functions may be exposed. @@ -206,7 +206,7 @@ protected override void EndProcessing() } // If the module was created successfully, then process the result... - if (localModule != null) + if (localModule is not null) { if (_returnResult) { diff --git a/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs b/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs index 7c3c082fe31..6bd99b3da7f 100644 --- a/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs +++ b/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs @@ -624,7 +624,7 @@ private string QuoteNames(IEnumerable names, StreamWriter streamWriter) /// private IEnumerable PreProcessModuleSpec(IEnumerable moduleSpecs) { - if (moduleSpecs != null) + if (moduleSpecs is not null) { foreach (object spec in moduleSpecs) { @@ -652,7 +652,7 @@ private string QuoteModules(IEnumerable moduleSpecs, StreamWriter streamWriter) StringBuilder result = new StringBuilder(); result.Append("@("); - if (moduleSpecs != null) + if (moduleSpecs is not null) { bool firstModule = true; foreach (object spec in moduleSpecs) @@ -689,28 +689,28 @@ private string QuoteModules(IEnumerable moduleSpecs, StreamWriter streamWriter) result.Append(QuoteName(moduleSpecification.Name)); result.Append("; "); - if (moduleSpecification.Guid != null) + if (moduleSpecification.Guid is not null) { result.Append("GUID = "); result.Append(QuoteName(moduleSpecification.Guid.ToString())); result.Append("; "); } - if (moduleSpecification.Version != null) + if (moduleSpecification.Version is not null) { result.Append("ModuleVersion = "); result.Append(QuoteName(moduleSpecification.Version.ToString())); result.Append("; "); } - if (moduleSpecification.MaximumVersion != null) + if (moduleSpecification.MaximumVersion is not null) { result.Append("MaximumVersion = "); result.Append(QuoteName(moduleSpecification.MaximumVersion)); result.Append("; "); } - if (moduleSpecification.RequiredVersion != null) + if (moduleSpecification.RequiredVersion is not null) { result.Append("RequiredVersion = "); result.Append(QuoteName(moduleSpecification.RequiredVersion.ToString())); @@ -737,7 +737,7 @@ private string QuoteFiles(IEnumerable names, StreamWriter streamWriter) { List resolvedPaths = new List(); - if (names != null) + if (names is not null) { foreach (string name in names) { @@ -768,7 +768,7 @@ private string QuoteFiles(IEnumerable names, StreamWriter streamWriter) ///// The quoted list. // private string QuoteFilesWithWildcard(string basePath, IEnumerable names, string allowedExtension, StreamWriter streamWriter, string item) // { - // if (names != null) + // if (names is not null) // { // foreach (string name in names) // { @@ -947,7 +947,7 @@ protected override void EndProcessing() // // If one of these parameters has been specified, default back to the old behavior by specifying // wildcards for exported commands that weren't specified on the command line. - if (_rootModule != null || _nestedModules != null || _requiredModules != null) + if (_rootModule is not null || _nestedModules is not null || _requiredModules is not null) { if (_exportedFunctions is null) _exportedFunctions = new string[] { "*" }; @@ -960,12 +960,12 @@ protected override void EndProcessing() ValidateUriParameterValue(ProjectUri, "ProjectUri"); ValidateUriParameterValue(LicenseUri, "LicenseUri"); ValidateUriParameterValue(IconUri, "IconUri"); - if (_helpInfoUri != null) + if (_helpInfoUri is not null) { ValidateUriParameterValue(new Uri(_helpInfoUri), "HelpInfoUri"); } - if (CompatiblePSEditions != null && (CompatiblePSEditions.Distinct(StringComparer.OrdinalIgnoreCase).Count() != CompatiblePSEditions.Length)) + if (CompatiblePSEditions is not null && (CompatiblePSEditions.Distinct(StringComparer.OrdinalIgnoreCase).Count() != CompatiblePSEditions.Length)) { string message = StringUtil.Format(Modules.DuplicateEntriesInCompatiblePSEditions, string.Join(",", CompatiblePSEditions)); var ioe = new InvalidOperationException(message); @@ -1036,9 +1036,9 @@ protected override void EndProcessing() BuildModuleManifest(result, nameof(RootModule), Modules.RootModule, !string.IsNullOrEmpty(_rootModule), () => QuoteName(_rootModule), streamWriter); - BuildModuleManifest(result, nameof(ModuleVersion), Modules.ModuleVersion, _moduleVersion != null && !string.IsNullOrEmpty(_moduleVersion.ToString()), () => QuoteName(_moduleVersion), streamWriter); + BuildModuleManifest(result, nameof(ModuleVersion), Modules.ModuleVersion, _moduleVersion is not null && !string.IsNullOrEmpty(_moduleVersion.ToString()), () => QuoteName(_moduleVersion), streamWriter); - BuildModuleManifest(result, nameof(CompatiblePSEditions), Modules.CompatiblePSEditions, _compatiblePSEditions != null && _compatiblePSEditions.Length > 0, () => QuoteNames(_compatiblePSEditions, streamWriter), streamWriter); + BuildModuleManifest(result, nameof(CompatiblePSEditions), Modules.CompatiblePSEditions, _compatiblePSEditions is not null && _compatiblePSEditions.Length > 0, () => QuoteNames(_compatiblePSEditions, streamWriter), streamWriter); BuildModuleManifest(result, nameof(Modules.GUID), Modules.GUID, !string.IsNullOrEmpty(_guid.ToString()), () => QuoteName(_guid.ToString()), streamWriter); @@ -1050,47 +1050,47 @@ protected override void EndProcessing() BuildModuleManifest(result, nameof(Description), Modules.Description, !string.IsNullOrEmpty(_description), () => QuoteName(_description), streamWriter); - BuildModuleManifest(result, nameof(PowerShellVersion), Modules.PowerShellVersion, _powerShellVersion != null && !string.IsNullOrEmpty(_powerShellVersion.ToString()), () => QuoteName(_powerShellVersion), streamWriter); + BuildModuleManifest(result, nameof(PowerShellVersion), Modules.PowerShellVersion, _powerShellVersion is not null && !string.IsNullOrEmpty(_powerShellVersion.ToString()), () => QuoteName(_powerShellVersion), streamWriter); BuildModuleManifest(result, nameof(PowerShellHostName), Modules.PowerShellHostName, !string.IsNullOrEmpty(_PowerShellHostName), () => QuoteName(_PowerShellHostName), streamWriter); - BuildModuleManifest(result, nameof(PowerShellHostVersion), Modules.PowerShellHostVersion, _PowerShellHostVersion != null && !string.IsNullOrEmpty(_PowerShellHostVersion.ToString()), () => QuoteName(_PowerShellHostVersion), streamWriter); + BuildModuleManifest(result, nameof(PowerShellHostVersion), Modules.PowerShellHostVersion, _PowerShellHostVersion is not null && !string.IsNullOrEmpty(_PowerShellHostVersion.ToString()), () => QuoteName(_PowerShellHostVersion), streamWriter); - BuildModuleManifest(result, nameof(DotNetFrameworkVersion), StringUtil.Format(Modules.DotNetFrameworkVersion, Modules.PrerequisiteForDesktopEditionOnly), _DotNetFrameworkVersion != null && !string.IsNullOrEmpty(_DotNetFrameworkVersion.ToString()), () => QuoteName(_DotNetFrameworkVersion), streamWriter); + BuildModuleManifest(result, nameof(DotNetFrameworkVersion), StringUtil.Format(Modules.DotNetFrameworkVersion, Modules.PrerequisiteForDesktopEditionOnly), _DotNetFrameworkVersion is not null && !string.IsNullOrEmpty(_DotNetFrameworkVersion.ToString()), () => QuoteName(_DotNetFrameworkVersion), streamWriter); - BuildModuleManifest(result, nameof(ClrVersion), StringUtil.Format(Modules.CLRVersion, Modules.PrerequisiteForDesktopEditionOnly), _ClrVersion != null && !string.IsNullOrEmpty(_ClrVersion.ToString()), () => QuoteName(_ClrVersion), streamWriter); + BuildModuleManifest(result, nameof(ClrVersion), StringUtil.Format(Modules.CLRVersion, Modules.PrerequisiteForDesktopEditionOnly), _ClrVersion is not null && !string.IsNullOrEmpty(_ClrVersion.ToString()), () => QuoteName(_ClrVersion), streamWriter); BuildModuleManifest(result, nameof(ProcessorArchitecture), Modules.ProcessorArchitecture, _processorArchitecture.HasValue, () => QuoteName(_processorArchitecture.ToString()), streamWriter); - BuildModuleManifest(result, nameof(RequiredModules), Modules.RequiredModules, _requiredModules != null && _requiredModules.Length > 0, () => QuoteModules(_requiredModules, streamWriter), streamWriter); + BuildModuleManifest(result, nameof(RequiredModules), Modules.RequiredModules, _requiredModules is not null && _requiredModules.Length > 0, () => QuoteModules(_requiredModules, streamWriter), streamWriter); - BuildModuleManifest(result, nameof(RequiredAssemblies), Modules.RequiredAssemblies, _requiredAssemblies != null, () => QuoteFiles(_requiredAssemblies, streamWriter), streamWriter); + BuildModuleManifest(result, nameof(RequiredAssemblies), Modules.RequiredAssemblies, _requiredAssemblies is not null, () => QuoteFiles(_requiredAssemblies, streamWriter), streamWriter); - BuildModuleManifest(result, nameof(ScriptsToProcess), Modules.ScriptsToProcess, _scripts != null, () => QuoteFiles(_scripts, streamWriter), streamWriter); + BuildModuleManifest(result, nameof(ScriptsToProcess), Modules.ScriptsToProcess, _scripts is not null, () => QuoteFiles(_scripts, streamWriter), streamWriter); - BuildModuleManifest(result, nameof(TypesToProcess), Modules.TypesToProcess, _types != null, () => QuoteFiles(_types, streamWriter), streamWriter); + BuildModuleManifest(result, nameof(TypesToProcess), Modules.TypesToProcess, _types is not null, () => QuoteFiles(_types, streamWriter), streamWriter); - BuildModuleManifest(result, nameof(FormatsToProcess), Modules.FormatsToProcess, _formats != null, () => QuoteFiles(_formats, streamWriter), streamWriter); + BuildModuleManifest(result, nameof(FormatsToProcess), Modules.FormatsToProcess, _formats is not null, () => QuoteFiles(_formats, streamWriter), streamWriter); - BuildModuleManifest(result, nameof(NestedModules), Modules.NestedModules, _nestedModules != null, () => QuoteModules(PreProcessModuleSpec(_nestedModules), streamWriter), streamWriter); + BuildModuleManifest(result, nameof(NestedModules), Modules.NestedModules, _nestedModules is not null, () => QuoteModules(PreProcessModuleSpec(_nestedModules), streamWriter), streamWriter); BuildModuleManifest(result, nameof(FunctionsToExport), Modules.FunctionsToExport, true, () => QuoteNames(_exportedFunctions, streamWriter), streamWriter); BuildModuleManifest(result, nameof(CmdletsToExport), Modules.CmdletsToExport, true, () => QuoteNames(_exportedCmdlets, streamWriter), streamWriter); - BuildModuleManifest(result, nameof(VariablesToExport), Modules.VariablesToExport, _exportedVariables != null && _exportedVariables.Length > 0, () => QuoteNames(_exportedVariables, streamWriter), streamWriter); + BuildModuleManifest(result, nameof(VariablesToExport), Modules.VariablesToExport, _exportedVariables is not null && _exportedVariables.Length > 0, () => QuoteNames(_exportedVariables, streamWriter), streamWriter); BuildModuleManifest(result, nameof(AliasesToExport), Modules.AliasesToExport, true, () => QuoteNames(_exportedAliases, streamWriter), streamWriter); - BuildModuleManifest(result, nameof(DscResourcesToExport), Modules.DscResourcesToExport, _dscResourcesToExport != null && _dscResourcesToExport.Length > 0, () => QuoteNames(_dscResourcesToExport, streamWriter), streamWriter); + BuildModuleManifest(result, nameof(DscResourcesToExport), Modules.DscResourcesToExport, _dscResourcesToExport is not null && _dscResourcesToExport.Length > 0, () => QuoteNames(_dscResourcesToExport, streamWriter), streamWriter); - BuildModuleManifest(result, nameof(ModuleList), Modules.ModuleList, _moduleList != null, () => QuoteModules(_moduleList, streamWriter), streamWriter); + BuildModuleManifest(result, nameof(ModuleList), Modules.ModuleList, _moduleList is not null, () => QuoteModules(_moduleList, streamWriter), streamWriter); - BuildModuleManifest(result, nameof(FileList), Modules.FileList, _miscFiles != null, () => QuoteFiles(_miscFiles, streamWriter), streamWriter); + BuildModuleManifest(result, nameof(FileList), Modules.FileList, _miscFiles is not null, () => QuoteFiles(_miscFiles, streamWriter), streamWriter); BuildPrivateDataInModuleManifest(result, streamWriter); - BuildModuleManifest(result, nameof(Modules.HelpInfoURI), Modules.HelpInfoURI, !string.IsNullOrEmpty(_helpInfoUri), () => QuoteName((_helpInfoUri != null) ? new Uri(_helpInfoUri) : null), streamWriter); + BuildModuleManifest(result, nameof(Modules.HelpInfoURI), Modules.HelpInfoURI, !string.IsNullOrEmpty(_helpInfoUri), () => QuoteName((_helpInfoUri is not null) ? new Uri(_helpInfoUri) : null), streamWriter); BuildModuleManifest(result, nameof(DefaultCommandPrefix), Modules.DefaultCommandPrefix, !string.IsNullOrEmpty(_defaultCommandPrefix), () => QuoteName(_defaultCommandPrefix), streamWriter); @@ -1152,7 +1152,7 @@ private void BuildPrivateDataInModuleManifest(StringBuilder result, StreamWriter var privateDataHashTable = PrivateData as Hashtable; bool specifiedPSDataProperties = !(Tags is null && ReleaseNotes is null && ProjectUri is null && IconUri is null && LicenseUri is null); - if (_privateData != null && privateDataHashTable is null) + if (_privateData is not null && privateDataHashTable is null) { if (specifiedPSDataProperties) { @@ -1164,7 +1164,7 @@ private void BuildPrivateDataInModuleManifest(StringBuilder result, StreamWriter { WriteWarning(Modules.PrivateDataValueTypeShouldBeHashTableWarning); - BuildModuleManifest(result, nameof(PrivateData), Modules.PrivateData, _privateData != null, + BuildModuleManifest(result, nameof(PrivateData), Modules.PrivateData, _privateData is not null, () => QuoteName((string)LanguagePrimitives.ConvertTo(_privateData, typeof(string), CultureInfo.InvariantCulture)), streamWriter); } @@ -1182,21 +1182,21 @@ private void BuildPrivateDataInModuleManifest(StringBuilder result, StreamWriter _indent = " "; - BuildModuleManifest(result, nameof(Tags), Modules.Tags, Tags != null && Tags.Length > 0, () => QuoteNames(Tags, streamWriter), streamWriter); - BuildModuleManifest(result, nameof(LicenseUri), Modules.LicenseUri, LicenseUri != null, () => QuoteName(LicenseUri), streamWriter); - BuildModuleManifest(result, nameof(ProjectUri), Modules.ProjectUri, ProjectUri != null, () => QuoteName(ProjectUri), streamWriter); - BuildModuleManifest(result, nameof(IconUri), Modules.IconUri, IconUri != null, () => QuoteName(IconUri), streamWriter); + BuildModuleManifest(result, nameof(Tags), Modules.Tags, Tags is not null && Tags.Length > 0, () => QuoteNames(Tags, streamWriter), streamWriter); + BuildModuleManifest(result, nameof(LicenseUri), Modules.LicenseUri, LicenseUri is not null, () => QuoteName(LicenseUri), streamWriter); + BuildModuleManifest(result, nameof(ProjectUri), Modules.ProjectUri, ProjectUri is not null, () => QuoteName(ProjectUri), streamWriter); + BuildModuleManifest(result, nameof(IconUri), Modules.IconUri, IconUri is not null, () => QuoteName(IconUri), streamWriter); BuildModuleManifest(result, nameof(ReleaseNotes), Modules.ReleaseNotes, !string.IsNullOrEmpty(ReleaseNotes), () => QuoteName(ReleaseNotes), streamWriter); BuildModuleManifest(result, nameof(Prerelease), Modules.Prerelease, !string.IsNullOrEmpty(Prerelease), () => QuoteName(Prerelease), streamWriter); BuildModuleManifest(result, nameof(RequireLicenseAcceptance), Modules.RequireLicenseAcceptance, RequireLicenseAcceptance.IsPresent, () => { return RequireLicenseAcceptance.IsPresent ? "$true" : "$false"; }, streamWriter); - BuildModuleManifest(result, nameof(ExternalModuleDependencies), Modules.ExternalModuleDependencies, ExternalModuleDependencies != null && ExternalModuleDependencies.Length > 0, () => QuoteNames(ExternalModuleDependencies, streamWriter), streamWriter); + BuildModuleManifest(result, nameof(ExternalModuleDependencies), Modules.ExternalModuleDependencies, ExternalModuleDependencies is not null && ExternalModuleDependencies.Length > 0, () => QuoteNames(ExternalModuleDependencies, streamWriter), streamWriter); result.Append(" } "); result.Append(ManifestComment(StringUtil.Format(Modules.EndOfManifestHashTable, "PSData"), streamWriter)); result.Append(streamWriter.NewLine); _indent = " "; - if (privateDataHashTable != null) + if (privateDataHashTable is not null) { result.Append(streamWriter.NewLine); @@ -1219,7 +1219,7 @@ private void ValidateUriParameterValue(Uri uri, string parameterName) { Dbg.Assert(!string.IsNullOrWhiteSpace(parameterName), "parameterName should not be null or whitespace"); - if (uri != null && !Uri.IsWellFormedUriString(uri.AbsoluteUri, UriKind.Absolute)) + if (uri is not null && !Uri.IsWellFormedUriString(uri.AbsoluteUri, UriKind.Absolute)) { var message = StringUtil.Format(Modules.InvalidParameterValue, uri); var ioe = new InvalidOperationException(message); diff --git a/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs b/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs index 92118527fac..07eef04cfc7 100644 --- a/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs +++ b/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs @@ -76,7 +76,7 @@ internal PSModuleInfo(string name, string path, ExecutionContext context, Sessio /// The module's sessionstate object - this may be null if the module is a dll. internal PSModuleInfo(string name, string path, ExecutionContext context, SessionState sessionState) { - if (path != null) + if (path is not null) { string resolvedPath = ModuleCmdletBase.GetResolvedPath(path, context); // The resolved path might be null if we're building a dynamic module and the path @@ -85,7 +85,7 @@ internal PSModuleInfo(string name, string path, ExecutionContext context, Sessio } SessionState = sessionState; - if (sessionState != null) + if (sessionState is not null) { sessionState.Internal.Module = this; } @@ -378,7 +378,7 @@ private void SetPSDataPropertiesFromPrivateData() private static Uri GetUriFromString(string uriString) { Uri uri = null; - if (uriString != null) + if (uriString is not null) { // try creating the Uri object // Ignoring the return value from Uri.TryCreate(), as uri value will be null on false or valid uri object on true. @@ -541,7 +541,7 @@ public Dictionary ExportedFunctions Dictionary exports = new Dictionary(StringComparer.OrdinalIgnoreCase); // If the module is not binary, it may also have functions... - if (DeclaredFunctionExports != null) + if (DeclaredFunctionExports is not null) { if (DeclaredFunctionExports.Count == 0) { return exports; } @@ -551,11 +551,11 @@ public Dictionary ExportedFunctions exports[fn] = tempFunction; } } - else if (SessionState != null) + else if (SessionState is not null) { // If there is no session state object associated with this list, // just return a null list of exports... - if (SessionState.Internal.ExportedFunctions != null) + if (SessionState.Internal.ExportedFunctions is not null) { foreach (FunctionInfo fi in SessionState.Internal.ExportedFunctions) { @@ -585,7 +585,7 @@ public Dictionary ExportedFunctions private bool IsScriptModuleFile(string path) { var ext = System.IO.Path.GetExtension(path); - return ext != null && s_scriptModuleExtensions.Contains(ext); + return ext is not null && s_scriptModuleExtensions.Contains(ext); } /// @@ -603,7 +603,7 @@ public ReadOnlyDictionary GetExportedTypeDefinitions( string rootedPath = null; if (RootModule is null) { - if (this.Path != null) + if (this.Path is not null) { rootedPath = this.Path; } @@ -614,7 +614,7 @@ public ReadOnlyDictionary GetExportedTypeDefinitions( } // ExternalScriptInfo.GetScriptBlockAst() uses a cache layer to avoid re-parsing. - CreateExportedTypeDefinitions(rootedPath != null && IsScriptModuleFile(rootedPath) && IO.File.Exists(rootedPath) ? + CreateExportedTypeDefinitions(rootedPath is not null && IsScriptModuleFile(rootedPath) && IO.File.Exists(rootedPath) ? (new ExternalScriptInfo(rootedPath, rootedPath)).GetScriptBlockAst() : null); } @@ -686,7 +686,7 @@ public string Prefix /// The function to add. internal void AddDetectedFunctionExport(string name) { - Dbg.Assert(name != null, "AddDetectedFunctionExport should not be called with a null value"); + Dbg.Assert(name is not null, "AddDetectedFunctionExport should not be called with a null value"); if (!DetectedFunctionExports.Contains(name)) { @@ -703,7 +703,7 @@ public Dictionary ExportedCmdlets { Dictionary exports = new Dictionary(StringComparer.OrdinalIgnoreCase); - if (DeclaredCmdletExports != null) + if (DeclaredCmdletExports is not null) { if (DeclaredCmdletExports.Count == 0) { return exports; } @@ -713,7 +713,7 @@ public Dictionary ExportedCmdlets exports[fn] = tempCmdlet; } } - else if ((CompiledExports != null) && (CompiledExports.Count > 0)) + else if ((CompiledExports is not null) && (CompiledExports.Count > 0)) { foreach (CmdletInfo cmdlet in CompiledExports) { @@ -742,7 +742,7 @@ public Dictionary ExportedCmdlets /// The cmdlet to add... internal void AddDetectedCmdletExport(string cmdlet) { - Dbg.Assert(cmdlet != null, "AddDetectedCmdletExport should not be called with a null value"); + Dbg.Assert(cmdlet is not null, "AddDetectedCmdletExport should not be called with a null value"); if (!DetectedCmdletExports.Contains(cmdlet)) { @@ -762,7 +762,7 @@ public Dictionary ExportedCommands { Dictionary exports = new Dictionary(StringComparer.OrdinalIgnoreCase); Dictionary cmdlets = this.ExportedCmdlets; - if (cmdlets != null) + if (cmdlets is not null) { foreach (var cmdlet in cmdlets) { @@ -771,7 +771,7 @@ public Dictionary ExportedCommands } Dictionary functions = this.ExportedFunctions; - if (functions != null) + if (functions is not null) { foreach (var function in functions) { @@ -780,7 +780,7 @@ public Dictionary ExportedCommands } Dictionary aliases = this.ExportedAliases; - if (aliases != null) + if (aliases is not null) { foreach (var alias in aliases) { @@ -798,7 +798,7 @@ public Dictionary ExportedCommands /// The cmdlet to add... internal void AddExportedCmdlet(CmdletInfo cmdlet) { - Dbg.Assert(cmdlet != null, "AddExportedCmdlet should not be called with a null value"); + Dbg.Assert(cmdlet is not null, "AddExportedCmdlet should not be called with a null value"); _compiledExports.Add(cmdlet); } @@ -815,7 +815,7 @@ internal List CompiledExports // If this module has a session state instance and there are any // exported cmdlets in the session state, migrate them to the // module info _compiledCmdlets entry. - if (SessionState != null && SessionState.Internal.ExportedCmdlets != null && + if (SessionState is not null && SessionState.Internal.ExportedCmdlets is not null && SessionState.Internal.ExportedCmdlets.Count > 0) { foreach (CmdletInfo ci in SessionState.Internal.ExportedCmdlets) @@ -838,7 +838,7 @@ internal List CompiledExports /// The cmdlet to add... internal void AddExportedAlias(AliasInfo aliasInfo) { - Dbg.Assert(aliasInfo != null, "AddExportedAlias should not be called with a null value"); + Dbg.Assert(aliasInfo is not null, "AddExportedAlias should not be called with a null value"); CompiledAliasExports.Add(aliasInfo); } @@ -1082,7 +1082,7 @@ internal string RootModuleForManifest /// private static void AddModuleToList(PSModuleInfo module, List moduleList) { - Dbg.Assert(module != null, "AddModuleToList should not be called with a null value"); + Dbg.Assert(module is not null, "AddModuleToList should not be called with a null value"); // Add the module if it isn't already there... foreach (PSModuleInfo m in moduleList) { @@ -1105,7 +1105,7 @@ public Dictionary ExportedVariables { Dictionary exportedVariables = new Dictionary(StringComparer.OrdinalIgnoreCase); - if ((DeclaredVariableExports != null) && (DeclaredVariableExports.Count > 0)) + if ((DeclaredVariableExports is not null) && (DeclaredVariableExports.Count > 0)) { foreach (string fn in DeclaredVariableExports) { @@ -1141,7 +1141,7 @@ public Dictionary ExportedAliases { Dictionary exportedAliases = new Dictionary(StringComparer.OrdinalIgnoreCase); - if ((DeclaredAliasExports != null) && (DeclaredAliasExports.Count > 0)) + if ((DeclaredAliasExports is not null) && (DeclaredAliasExports.Count > 0)) { foreach (string fn in DeclaredAliasExports) { @@ -1149,7 +1149,7 @@ public Dictionary ExportedAliases exportedAliases[fn] = tempAlias; } } - else if ((CompiledAliasExports != null) && (CompiledAliasExports.Count > 0)) + else if ((CompiledAliasExports is not null) && (CompiledAliasExports.Count > 0)) { foreach (AliasInfo ai in CompiledAliasExports) { @@ -1202,7 +1202,7 @@ public Dictionary ExportedAliases /// The command it resolves to. internal void AddDetectedAliasExport(string name, string value) { - Dbg.Assert(name != null, "AddDetectedAliasExport should not be called with a null value"); + Dbg.Assert(name is not null, "AddDetectedAliasExport should not be called with a null value"); DetectedAliasExports[name] = value; } @@ -1213,7 +1213,7 @@ public ReadOnlyCollection ExportedDscResources { get { - return _declaredDscResourceExports != null + return _declaredDscResourceExports is not null ? new ReadOnlyCollection(_declaredDscResourceExports) : Utils.EmptyReadOnlyCollection(); } @@ -1325,7 +1325,7 @@ public PSVariable GetVariableFromCallersModule(string variableName) } } - if (callersSessionState != null) + if (callersSessionState is not null) { return callersSessionState.Internal.GetVariable(variableName); } @@ -1348,7 +1348,7 @@ internal void CaptureLocals() var context = LocalPipeline.GetExecutionContextFromTLS(); var tuple = context.EngineSessionState.CurrentScope.LocalsTuple; IEnumerable variables = context.EngineSessionState.CurrentScope.Variables.Values; - if (tuple != null) + if (tuple is not null) { var result = new Dictionary(); tuple.GetVariableTable(result, false); @@ -1391,7 +1391,7 @@ public PSObject AsCustomObject() foreach (KeyValuePair entry in this.ExportedFunctions) { FunctionInfo func = entry.Value; - if (func != null) + if (func is not null) { PSScriptMethod sm = new PSScriptMethod(func.Name, func.ScriptBlock); obj.Members.Add(sm); @@ -1401,7 +1401,7 @@ public PSObject AsCustomObject() foreach (KeyValuePair entry in this.ExportedVariables) { PSVariable var = entry.Value; - if (var != null) + if (var is not null) { PSVariableProperty sm = new PSVariableProperty(var); obj.Members.Add(sm); @@ -1621,11 +1621,11 @@ public int GetHashCode(PSModuleInfo obj) { int result = 0; - if (obj != null) + if (obj is not null) { // picking two different prime numbers to avoid collisions result = 23; - if (obj.Name != null) + if (obj.Name is not null) { result = result * 17 + obj.Name.GetHashCode(); } @@ -1635,7 +1635,7 @@ public int GetHashCode(PSModuleInfo obj) result = result * 17 + obj.Guid.GetHashCode(); } - if (obj.Version != null) + if (obj.Version is not null) { result = result * 17 + obj.Version.GetHashCode(); } diff --git a/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs b/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs index 8a2cc5a03bb..2c329f87870 100644 --- a/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs +++ b/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs @@ -43,9 +43,9 @@ private static Collection RehydrateHashtableKeys(PSObject pso, string pr List list = hashtable .Keys .Cast() - .Where(k => k != null) + .Where(k => k is not null) .Select(k => k.ToString()) - .Where(s => s != null) + .Where(s => s is not null) .ToList(); return new Collection(list); } @@ -82,7 +82,7 @@ internal static PSModuleInfo RehydratePSModuleInfo(PSObject deserializedModuleIn moduleInfo.DeclaredVariableExports = RehydrateHashtableKeys(deserializedModuleInfo, "ExportedVariables"); var compatiblePSEditions = DeserializingTypeConverter.GetPropertyValue(deserializedModuleInfo, "CompatiblePSEditions", rehydrationFlags); - if (compatiblePSEditions != null && compatiblePSEditions.Length > 0) + if (compatiblePSEditions is not null && compatiblePSEditions.Length > 0) { foreach (var edition in compatiblePSEditions) { @@ -92,7 +92,7 @@ internal static PSModuleInfo RehydratePSModuleInfo(PSObject deserializedModuleIn // PowerShellGet related properties var tags = DeserializingTypeConverter.GetPropertyValue(deserializedModuleInfo, "Tags", rehydrationFlags); - if (tags != null && tags.Length > 0) + if (tags is not null && tags.Length > 0) { foreach (var tag in tags) { @@ -325,7 +325,7 @@ internal static ErrorRecord GetErrorRecordForProcessingOfCimModule(Exception inn private static ErrorRecord GetErrorRecordForRemoteDiscoveryProvider(Exception innerException) { CimException cimException = innerException as CimException; - if ((cimException != null) && + if ((cimException is not null) && ((cimException.NativeErrorCode == NativeErrorCode.InvalidNamespace) || (cimException.NativeErrorCode == NativeErrorCode.InvalidClass) || (cimException.NativeErrorCode == NativeErrorCode.MethodNotFound) || @@ -360,9 +360,9 @@ private static ErrorRecord GetErrorRecordForRemotePipelineInvocation(Exception i Exception outerException = new InvalidOperationException(errorMessage, innerException); RemoteException remoteException = innerException as RemoteException; - ErrorRecord remoteErrorRecord = remoteException != null ? remoteException.ErrorRecord : null; - string errorId = remoteErrorRecord != null ? remoteErrorRecord.FullyQualifiedErrorId : innerException.GetType().Name; - ErrorCategory errorCategory = remoteErrorRecord != null ? remoteErrorRecord.CategoryInfo.Category : ErrorCategory.NotSpecified; + ErrorRecord remoteErrorRecord = remoteException is not null ? remoteException.ErrorRecord : null; + string errorId = remoteErrorRecord is not null ? remoteErrorRecord.FullyQualifiedErrorId : innerException.GetType().Name; + ErrorCategory errorCategory = remoteErrorRecord is not null ? remoteErrorRecord.CategoryInfo.Category : ErrorCategory.NotSpecified; ErrorRecord errorRecord = new ErrorRecord(outerException, errorId, errorCategory, null); return errorRecord; @@ -371,11 +371,11 @@ private static ErrorRecord GetErrorRecordForRemotePipelineInvocation(Exception i private static ErrorRecord GetErrorRecordForRemotePipelineInvocation(ErrorRecord innerErrorRecord, string errorMessageTemplate) { string innerErrorMessage; - if (innerErrorRecord.ErrorDetails != null && innerErrorRecord.ErrorDetails.Message != null) + if (innerErrorRecord.ErrorDetails is not null && innerErrorRecord.ErrorDetails.Message is not null) { innerErrorMessage = innerErrorRecord.ErrorDetails.Message; } - else if (innerErrorRecord.Exception != null && innerErrorRecord.Exception.Message != null) + else if (innerErrorRecord.Exception is not null && innerErrorRecord.Exception.Message is not null) { innerErrorMessage = innerErrorRecord.Exception.Message; } @@ -408,7 +408,7 @@ private static IEnumerable EnumerateWithCatch(IEnumerable enumerable, A exceptionHandler(e); } - if (enumerator != null) + if (enumerator is not null) using (enumerator) { bool gotResults = false; @@ -455,8 +455,8 @@ private static void HandleErrorFromPipeline(Cmdlet cmdlet, ErrorRecord errorReco { if (!cmdlet.MyInvocation.ExpectingInput) { - if (((powerShell.Runspace != null) && (powerShell.Runspace.RunspaceStateInfo.State != RunspaceState.Opened)) || - ((powerShell.RunspacePool != null) && (powerShell.RunspacePool.RunspacePoolStateInfo.State != RunspacePoolState.Opened))) + if (((powerShell.Runspace is not null) && (powerShell.Runspace.RunspaceStateInfo.State != RunspaceState.Opened)) || + ((powerShell.RunspacePool is not null) && (powerShell.RunspacePool.RunspacePoolStateInfo.State != RunspacePoolState.Opened))) { cmdlet.ThrowTerminatingError(errorRecord); } @@ -624,7 +624,7 @@ internal class CimModule internal CimModule(CimInstance baseObject) { - Dbg.Assert(baseObject != null, "Caller should make sure baseObject != null"); + Dbg.Assert(baseObject is not null, "Caller should make sure baseObject is not null"); Dbg.Assert( baseObject.CimSystemProperties.ClassName.Equals(DiscoveryProviderModuleClass, StringComparison.OrdinalIgnoreCase), "Caller should make sure baseObject is an instance of the right CIM class"); @@ -693,8 +693,8 @@ private class CimModuleManifestFile : CimModuleFile { internal CimModuleManifestFile(string fileName, byte[] rawFileData) { - Dbg.Assert(fileName != null, "Caller should make sure fileName != null"); - Dbg.Assert(rawFileData != null, "Caller should make sure rawFileData != null"); + Dbg.Assert(fileName is not null, "Caller should make sure fileName is not null"); + Dbg.Assert(rawFileData is not null, "Caller should make sure rawFileData is not null"); FileName = fileName; RawFileDataCore = rawFileData; @@ -711,7 +711,7 @@ private class CimModuleImplementationFile : CimModuleFile internal CimModuleImplementationFile(CimInstance baseObject) { - Dbg.Assert(baseObject != null, "Caller should make sure baseObject != null"); + Dbg.Assert(baseObject is not null, "Caller should make sure baseObject is not null"); Dbg.Assert( baseObject.CimSystemProperties.ClassName.Equals(DiscoveryProviderFileClass, StringComparison.OrdinalIgnoreCase), "Caller should make sure baseObject is an instance of the right CIM class"); @@ -769,8 +769,8 @@ private static IEnumerable GetCimModules( Cmdlet cmdlet, CancellationToken cancellationToken) { - Dbg.Assert(cimSession != null, "Caller should verify cimSession != null"); - Dbg.Assert(moduleNamePattern != null, "Caller should verify that moduleNamePattern != null"); + Dbg.Assert(cimSession is not null, "Caller should verify cimSession is not null"); + Dbg.Assert(moduleNamePattern is not null, "Caller should verify that moduleNamePattern is not null"); const WildcardOptions wildcardOptions = WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant; var wildcardPattern = WildcardPattern.Get(moduleNamePattern, wildcardOptions); @@ -778,7 +778,7 @@ private static IEnumerable GetCimModules( var options = new CimOperationOptions { CancellationToken = cancellationToken }; options.SetCustomOption("PS_ModuleNamePattern", dosWildcard, mustComply: false); - if (resourceUri != null) + if (resourceUri is not null) { options.ResourceUri = resourceUri; } @@ -991,7 +991,7 @@ internal static CimSession CreateCimSession( var sessionOptions = new CimSessionOptions(); CimCredential cimCredentials = GetCimCredentials(authentication, credential); - if (cimCredentials != null) + if (cimCredentials is not null) { sessionOptions.AddDestinationCredentials(cimCredentials); } @@ -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 is null) || (parseErrors is not null && parseErrors.Length > 0)) { containedErrors = true; } @@ -1083,14 +1083,14 @@ internal static void DispatchModuleInfoProcessing( } Tuple cimSessionInfo = weaklyTypeSession as Tuple; - if (cimSessionInfo != null) + if (cimSessionInfo is not null) { cimSessionAction(cimSessionInfo.Item1, cimSessionInfo.Item2, cimSessionInfo.Item3); return; } PSSession psSession = weaklyTypeSession as PSSession; - if (psSession != null) + if (psSession is not null) { psSessionAction(psSession); return; diff --git a/src/System.Management.Automation/engine/Modules/RemoveModuleCommand.cs b/src/System.Management.Automation/engine/Modules/RemoveModuleCommand.cs index 64958c9fde6..34cb7b6ff08 100644 --- a/src/System.Management.Automation/engine/Modules/RemoveModuleCommand.cs +++ b/src/System.Management.Automation/engine/Modules/RemoveModuleCommand.cs @@ -88,7 +88,7 @@ protected override void ProcessRecord() modulesToRemove.Add(m, new List { m }); } - if (FullyQualifiedName != null) + if (FullyQualifiedName is not null) { // TODO: // Paths in the module name may fail here because @@ -111,7 +111,7 @@ protected override void ProcessRecord() foreach (var entry in modulesToRemove) { var module = entry.Key; - if (module.NestedModules != null && module.NestedModules.Count > 0) + if (module.NestedModules is not null && module.NestedModules.Count > 0) { List nestedModulesWithNoCircularReference = new List(); GetAllNestedModules(module, ref nestedModulesWithNoCircularReference); @@ -270,7 +270,7 @@ private bool ModuleProvidesCurrentSessionDrive(PSModuleInfo module) Dictionary> providers = Context.TopLevelSessionState.Providers; foreach (KeyValuePair> pList in providers) { - Dbg.Assert(pList.Value != null, "There should never be a null list of entries in the provider table"); + Dbg.Assert(pList.Value is not null, "There should never be a null list of entries in the provider table"); foreach (ProviderInfo pInfo in pList.Value) { string implTypeAssemblyLocation = pInfo.ImplementingType.Assembly.Location; @@ -294,7 +294,7 @@ private bool ModuleProvidesCurrentSessionDrive(PSModuleInfo module) private void GetAllNestedModules(PSModuleInfo module, ref List nestedModulesWithNoCircularReference) { List nestedModules = new List(); - if (module.NestedModules != null && module.NestedModules.Count > 0) + if (module.NestedModules is not null && module.NestedModules.Count > 0) { foreach (var nestedModule in module.NestedModules) { @@ -362,12 +362,12 @@ protected override void EndProcessing() hasWildcards = false; } - if (FullyQualifiedName != null && (FullyQualifiedName.Any(moduleSpec => !InitialSessionState.IsEngineModule(moduleSpec.Name)))) + if (FullyQualifiedName is not null && (FullyQualifiedName.Any(moduleSpec => !InitialSessionState.IsEngineModule(moduleSpec.Name)))) { isEngineModule = false; } - if (!isEngineModule && (!hasWildcards || _moduleInfo.Length != 0 || (FullyQualifiedName != null && FullyQualifiedName.Length != 0))) + if (!isEngineModule && (!hasWildcards || _moduleInfo.Length != 0 || (FullyQualifiedName is not null && FullyQualifiedName.Length != 0))) { string message = StringUtil.Format(Modules.NoModulesRemoved); InvalidOperationException invalidOp = new InvalidOperationException(message); diff --git a/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs b/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs index 74e608d8e7d..9f10b488096 100644 --- a/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs +++ b/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs @@ -23,7 +23,7 @@ internal static ScriptAnalysis Analyze(string path, ExecutionContext context) try { - if (Utils.PathIsUnc(path) && (context.CurrentCommandProcessor.CommandRuntime != null)) + if (Utils.PathIsUnc(path) && (context.CurrentCommandProcessor.CommandRuntime is not null)) { ProgressRecord analysisProgress = new ProgressRecord(0, Modules.ScriptAnalysisPreparing, @@ -189,7 +189,7 @@ public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst fun // function Foo-Bar { [Alias("Alias1", "...")] param() ... } var functionBody = functionDefinitionAst.Body; - if ((functionBody.ParamBlock != null) && (functionBody.ParamBlock.Attributes != null)) + if ((functionBody.ParamBlock is not null) && (functionBody.ParamBlock.Attributes is not null)) { foreach (AttributeAst attribute in functionBody.ParamBlock.Attributes) { @@ -198,7 +198,7 @@ public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst fun foreach (ExpressionAst aliasAst in attribute.PositionalArguments) { var aliasExpression = aliasAst as StringConstantExpressionAst; - if (aliasExpression != null) + if (aliasExpression is not null) { string alias = aliasExpression.Value; @@ -430,14 +430,14 @@ private void ProcessCmdletArguments(object value, Action onEachArgument) if (value is null) return; var commandName = value as string; - if (commandName != null) + if (commandName is not null) { onEachArgument(commandName); return; } var names = value as object[]; - if (names != null) + if (names is not null) { foreach (var n in names) { @@ -466,7 +466,7 @@ private Hashtable DoPsuedoParameterBinding(CommandAst commandAst, string command { var element = commandAst.CommandElements[i]; var specifiedParameter = element as CommandParameterAst; - if (specifiedParameter != null) + if (specifiedParameter is not null) { bool boundParameter = false; var specifiedParamName = specifiedParameter.ParameterName; @@ -483,13 +483,13 @@ private Hashtable DoPsuedoParameterBinding(CommandAst commandAst, string command if (argumentAst is null) { argumentAst = commandAst.CommandElements[i] as ExpressionAst; - if (argumentAst != null) + if (argumentAst is not null) { i += 1; } } - if (argumentAst != null) + if (argumentAst is not null) { boundParameter = true; result[parameterInfo.name] = @@ -500,7 +500,7 @@ private Hashtable DoPsuedoParameterBinding(CommandAst commandAst, string command } } - if (boundParameter || specifiedParameter.Argument != null) + if (boundParameter || specifiedParameter.Argument is not null) { continue; } diff --git a/src/System.Management.Automation/engine/Modules/TestModuleManifestCommand.cs b/src/System.Management.Automation/engine/Modules/TestModuleManifestCommand.cs index 6d13c611a07..c0e0f071501 100644 --- a/src/System.Management.Automation/engine/Modules/TestModuleManifestCommand.cs +++ b/src/System.Management.Automation/engine/Modules/TestModuleManifestCommand.cs @@ -129,10 +129,10 @@ protected override void ProcessRecord() null, null); - if (module != null) + if (module is not null) { // Validate file existence - if (module.RequiredAssemblies != null) + if (module.RequiredAssemblies is not null) { foreach (string requiredAssembliespath in module.RequiredAssemblies) { @@ -160,7 +160,7 @@ protected override void ProcessRecord() LoadModuleManifestData(scriptInfo, ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.WriteWarnings, out data, out localizedData, ref containerErrors); ModuleSpecification[] nestedModules; GetScalarFromData(data, scriptInfo.Path, "NestedModules", ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.WriteWarnings, out nestedModules); - if (nestedModules != null) + if (nestedModules is not null) { foreach (ModuleSpecification nestedModule in nestedModules) { @@ -185,7 +185,7 @@ protected override void ProcessRecord() ModuleSpecification[] requiredModules; GetScalarFromData(data, scriptInfo.Path, "RequiredModules", ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.WriteWarnings, out requiredModules); - if (requiredModules != null) + if (requiredModules is not null) { foreach (ModuleSpecification requiredModule in requiredModules) { @@ -202,7 +202,7 @@ protected override void ProcessRecord() string[] fileListPaths; GetScalarFromData(data, scriptInfo.Path, "FileList", ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.WriteWarnings, out fileListPaths); - if (fileListPaths != null) + if (fileListPaths is not null) { foreach (string fileListPath in fileListPaths) { @@ -218,7 +218,7 @@ protected override void ProcessRecord() ModuleSpecification[] moduleListModules; GetScalarFromData(data, scriptInfo.Path, "ModuleList", ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.WriteWarnings, out moduleListModules); - if (moduleListModules != null) + if (moduleListModules is not null) { foreach (ModuleSpecification moduleListModule in moduleListModules) { @@ -263,7 +263,7 @@ protected override void ProcessRecord() catch (ArgumentException) { } Version version; - if (parent != null && Version.TryParse(parent.Name, out version)) + if (parent is not null && Version.TryParse(parent.Name, out version)) { if (!version.Equals(module.Version)) { @@ -277,7 +277,7 @@ protected override void ProcessRecord() WriteVerbose(Modules.ModuleVersionEqualsToVersionFolder); } - if (module != null) + if (module is not null) { WriteObject(module); } diff --git a/src/System.Management.Automation/engine/MshCmdlet.cs b/src/System.Management.Automation/engine/MshCmdlet.cs index 8d3a6936959..3fd039fb9c6 100644 --- a/src/System.Management.Automation/engine/MshCmdlet.cs +++ b/src/System.Management.Automation/engine/MshCmdlet.cs @@ -240,7 +240,7 @@ public class CommandInvocationIntrinsics internal CommandInvocationIntrinsics(ExecutionContext context, PSCmdlet cmdlet) { _context = context; - if (cmdlet != null) + if (cmdlet is not null) { _cmdlet = cmdlet; _commandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; @@ -279,7 +279,7 @@ public bool HasErrors /// public string ExpandString(string source) { - if (_cmdlet != null) + if (_cmdlet is not null) _cmdlet.ThrowIfStopping(); return _context.Engine.Expand(source); } @@ -309,18 +309,18 @@ public CommandInfo GetCommand(string commandName, CommandTypes type, object[] ar try { CommandOrigin commandOrigin = CommandOrigin.Runspace; - if (_cmdlet != null) + if (_cmdlet is not null) { commandOrigin = _cmdlet.CommandOrigin; } - else if (_context != null) + else if (_context is not null) { commandOrigin = _context.EngineSessionState.CurrentScope.ScopeOrigin; } result = CommandDiscovery.LookupCommandInfo(commandName, type, SearchResolutionOptions.None, commandOrigin, _context); - if ((result != null) && (arguments != null) && (arguments.Length > 0)) + if ((result is not null) && (arguments is not null) && (arguments.Length > 0)) { // We've been asked to retrieve dynamic parameters if (result.ImplementsDynamicParameters) @@ -440,7 +440,7 @@ public CmdletInfo GetCmdletByTypeName(string cmdletTypeName) Exception e = null; Type cmdletType = TypeResolver.ResolveType(cmdletTypeName, out e); - if (e != null) + if (e is not null) { throw e; } @@ -454,7 +454,7 @@ public CmdletInfo GetCmdletByTypeName(string cmdletTypeName) foreach (var attr in cmdletType.GetCustomAttributes(true)) { ca = attr as CmdletAttribute; - if (ca != null) + if (ca is not null) break; } @@ -528,7 +528,7 @@ public List GetCmdlets(string pattern) } current = ((IEnumerator)searcher).Current as CmdletInfo; - if (current != null) + if (current is not null) cmdlets.Add(current); } @@ -626,7 +626,7 @@ internal IEnumerable GetCommands(string name, CommandTypes commandT commandTypes, _context); - if (commandOrigin != null) + if (commandOrigin is not null) { searcher.CommandOrigin = commandOrigin.Value; } @@ -662,7 +662,7 @@ internal IEnumerable GetCommands(string name, CommandTypes commandT } CommandInfo commandInfo = ((IEnumerator)searcher).Current as CommandInfo; - if (commandInfo != null) + if (commandInfo is not null) { yield return commandInfo; } @@ -795,7 +795,7 @@ public Collection InvokeScript(string script, bool useNewScope, private Collection InvokeScript(ScriptBlock sb, bool useNewScope, PipelineResultTypes writeToPipeline, IList input, params object[] args) { - if (_cmdlet != null) + if (_cmdlet is not null) _cmdlet.ThrowIfStopping(); Cmdlet cmdletToUse = null; @@ -824,7 +824,7 @@ private Collection InvokeScript(ScriptBlock sb, bool useNewScope, // If the cmdletToUse is not null, then the result of the evaluation will be // streamed out the output pipe of the cmdlet. object rawResult; - if (cmdletToUse != null) + if (cmdletToUse is not null) { sb.InvokeUsingCmdlet( contextCmdlet: cmdletToUse, @@ -854,7 +854,7 @@ private Collection InvokeScript(ScriptBlock sb, bool useNewScope, // If the result is already a collection of PSObjects, just return it... Collection result = rawResult as Collection; - if (result != null) + if (result is not null) return result; result = new Collection(); @@ -862,7 +862,7 @@ private Collection InvokeScript(ScriptBlock sb, bool useNewScope, IEnumerator list = null; list = LanguagePrimitives.GetEnumerator(rawResult); - if (list != null) + if (list is not null) { while (list.MoveNext()) { @@ -887,7 +887,7 @@ private Collection InvokeScript(ScriptBlock sb, bool useNewScope, /// public ScriptBlock NewScriptBlock(string scriptText) { - if (_commandRuntime != null) + if (_commandRuntime is not null) _commandRuntime.ThrowIfStopping(); ScriptBlock result = ScriptBlock.Create(_context, scriptText); @@ -972,7 +972,7 @@ public PagingParameters PagingParameters if (_pagingParameters is null) { MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) + if (mshCommandRuntime is not null) { _pagingParameters = mshCommandRuntime.PagingParameters ?? new PagingParameters(mshCommandRuntime); } diff --git a/src/System.Management.Automation/engine/MshCommandRuntime.cs b/src/System.Management.Automation/engine/MshCommandRuntime.cs index f9c26c5b574..61ec06f1cc5 100644 --- a/src/System.Management.Automation/engine/MshCommandRuntime.cs +++ b/src/System.Management.Automation/engine/MshCommandRuntime.cs @@ -112,7 +112,7 @@ internal MshCommandRuntime(ExecutionContext context, CommandInfo commandInfo, In /// public override string ToString() { - if (_commandInfo != null) + if (_commandInfo is not null) return _commandInfo.ToString(); return ""; // does not require localization } @@ -132,7 +132,7 @@ internal InvocationInfo MyInvocation /// internal bool IsStopping { - get { return (this.PipelineProcessor != null && this.PipelineProcessor.Stopping); } + get { return (this.PipelineProcessor is not null && this.PipelineProcessor.Stopping); } } #region Write @@ -493,9 +493,9 @@ internal void WriteDebug(DebugRecord record, bool overrideInquire = false) CBhost?.Runspace?.Debugger?.Break(record); } - if (DebugOutputPipe != null) + if (DebugOutputPipe is not null) { - if (CBhost != null && CBhost.InternalUI != null && + if (CBhost is not null && CBhost.InternalUI is not null && DebugOutputPipe.NullPipe) { // If redirecting to a null pipe, still write to @@ -587,9 +587,9 @@ internal void WriteVerbose(VerboseRecord record, bool overrideInquire = false) CBhost?.Runspace?.Debugger?.Break(record); } - if (VerboseOutputPipe != null) + if (VerboseOutputPipe is not null) { - if (CBhost != null && CBhost.InternalUI != null && + if (CBhost is not null && CBhost.InternalUI is not null && VerboseOutputPipe.NullPipe) { // If redirecting to a null pipe, still write to @@ -681,9 +681,9 @@ internal void WriteWarning(WarningRecord record, bool overrideInquire = false) CBhost?.Runspace?.Debugger?.Break(record); } - if (WarningOutputPipe != null) + if (WarningOutputPipe is not null) { - if (CBhost != null && CBhost.InternalUI != null && + if (CBhost is not null && CBhost.InternalUI is not null && WarningOutputPipe.NullPipe) { // If redirecting to a null pipe, still write to @@ -749,9 +749,9 @@ internal void WriteInformation(InformationRecord record, bool overrideInquire = if (preference != ActionPreference.Ignore) { - if (InformationOutputPipe != null) + if (InformationOutputPipe is not null) { - if (CBhost != null && CBhost.InternalUI != null && + if (CBhost is not null && CBhost.InternalUI is not null && InformationOutputPipe.NullPipe) { // If redirecting to a null pipe, still write to @@ -781,7 +781,7 @@ internal void WriteInformation(InformationRecord record, bool overrideInquire = || (preference == ActionPreference.Continue)) { HostInformationMessage hostOutput = record.MessageData as HostInformationMessage; - if (hostOutput != null) + if (hostOutput is not null) { string message = hostOutput.Message; ConsoleColor? foregroundColor = null; @@ -891,19 +891,19 @@ private bool InitShouldLogPipelineExecutionDetail() { CmdletInfo cmdletInfo = _commandInfo as CmdletInfo; - if (cmdletInfo != null) + if (cmdletInfo is not null) { if (string.Equals("Add-Type", cmdletInfo.Name, StringComparison.OrdinalIgnoreCase)) { return true; } - if (cmdletInfo.Module is null && cmdletInfo.PSSnapIn != null) + if (cmdletInfo.Module is null && cmdletInfo.PSSnapIn is not null) { return cmdletInfo.PSSnapIn.LogPipelineExecutionDetails; } - if (cmdletInfo.PSSnapIn is null && cmdletInfo.Module != null) + if (cmdletInfo.PSSnapIn is null && cmdletInfo.Module is not null) { return cmdletInfo.Module.LogPipelineExecutionDetails; } @@ -913,7 +913,7 @@ private bool InitShouldLogPipelineExecutionDetail() // Logging should be enabled for functions from modules also FunctionInfo functionInfo = _commandInfo as FunctionInfo; - if (functionInfo != null && functionInfo.Module != null) + if (functionInfo is not null && functionInfo.Module is not null) { return functionInfo.Module.LogPipelineExecutionDetails; } @@ -2059,8 +2059,8 @@ public void ThrowTerminatingError(ErrorRecord errorRecord) errorRecord.SetInvocationInfo(MyInvocation); - if (errorRecord.ErrorDetails != null - && errorRecord.ErrorDetails.TextLookupError != null) + if (errorRecord.ErrorDetails is not null + && errorRecord.ErrorDetails.TextLookupError is not null) { Exception textLookupError = errorRecord.ErrorDetails.TextLookupError; errorRecord.ErrorDetails.TextLookupError = null; @@ -2071,7 +2071,7 @@ public void ThrowTerminatingError(ErrorRecord errorRecord) } // This code forces the stack trace and source fields to be populated - if (errorRecord.Exception != null + if (errorRecord.Exception is not null && string.IsNullOrEmpty(errorRecord.Exception.StackTrace)) { try @@ -2166,22 +2166,22 @@ internal void SetMergeFromRuntime(MshCommandRuntime fromRuntime) { this.ErrorMergeTo = fromRuntime.ErrorMergeTo; - if (fromRuntime.WarningOutputPipe != null) + if (fromRuntime.WarningOutputPipe is not null) { this.WarningOutputPipe = fromRuntime.WarningOutputPipe; } - if (fromRuntime.VerboseOutputPipe != null) + if (fromRuntime.VerboseOutputPipe is not null) { this.VerboseOutputPipe = fromRuntime.VerboseOutputPipe; } - if (fromRuntime.DebugOutputPipe != null) + if (fromRuntime.DebugOutputPipe is not null) { this.DebugOutputPipe = fromRuntime.DebugOutputPipe; } - if (fromRuntime.InformationOutputPipe != null) + if (fromRuntime.InformationOutputPipe is not null) { this.InformationOutputPipe = fromRuntime.InformationOutputPipe; } @@ -2292,7 +2292,7 @@ internal void ThrowIfWriteNotPermitted(bool needsToWriteToPipeline) { // Only generate these exceptions if a pipeline has already been declared as the 'writing' pipeline. // Otherwise, these are probably infrastructure messages and can be ignored. - if (this.PipelineProcessor?._permittedToWrite != null) + if (this.PipelineProcessor?._permittedToWrite is not null) { throw PSTraceSource.NewInvalidOperationException( PipelineStrings.WriteNotPermitted); @@ -2371,7 +2371,7 @@ public Exception ManageException(Exception e) if (e is null) throw PSTraceSource.NewArgumentNullException(nameof(e)); - if (PipelineProcessor != null) + if (PipelineProcessor is not null) { PipelineProcessor.RecordFailure(e, _thisCommand); } @@ -2546,10 +2546,10 @@ internal void SetupVariable(VariableStreamKind streamKind, string variableName, { varList = new ArrayList(); - if (oldValue != null && AutomationNull.Value != oldValue) + if (oldValue is not null && AutomationNull.Value != oldValue) { IEnumerable enumerable = LanguagePrimitives.GetEnumerable(oldValue); - if (enumerable != null) + if (enumerable is not null) { foreach (object o in enumerable) { @@ -2814,8 +2814,8 @@ internal void _WriteErrorSkipAllowCheck(ErrorRecord errorRecord, ActionPreferenc { ThrowIfStopping(); - if (errorRecord.ErrorDetails != null - && errorRecord.ErrorDetails.TextLookupError != null) + if (errorRecord.ErrorDetails is not null + && errorRecord.ErrorDetails.TextLookupError is not null) { Exception textLookupError = errorRecord.ErrorDetails.TextLookupError; errorRecord.ErrorDetails.TextLookupError = null; @@ -3702,8 +3702,8 @@ bool hasSecurityImpact /// private bool IsSuspendPromptAllowed() { - Dbg.Assert(this.CBhost != null, "Expected this.CBhost != null"); - Dbg.Assert(this.CBhost.ExternalHost != null, "Expected this.CBhost.ExternalHost != null"); + Dbg.Assert(this.CBhost is not null, "Expected this.CBhost is not null"); + Dbg.Assert(this.CBhost.ExternalHost is not null, "Expected this.CBhost.ExternalHost is not null"); if (this.CBhost.ExternalHost is ServerRemoteHost) { return false; @@ -3719,27 +3719,27 @@ internal void SetVariableListsInPipe() { Diagnostics.Assert(_thisCommand is PSScriptCmdlet, "this is only done for script cmdlets"); - if (_outVarList != null) + if (_outVarList is not null) { this.OutputPipe.AddVariableList(VariableStreamKind.Output, _outVarList); } - if (_errorVarList != null) + if (_errorVarList is not null) { this.OutputPipe.AddVariableList(VariableStreamKind.Error, _errorVarList); } - if (_warningVarList != null) + if (_warningVarList is not null) { this.OutputPipe.AddVariableList(VariableStreamKind.Warning, _warningVarList); } - if (_informationVarList != null) + if (_informationVarList is not null) { this.OutputPipe.AddVariableList(VariableStreamKind.Information, _informationVarList); } - if (this.PipelineVariable != null) + if (this.PipelineVariable is not null) { this.OutputPipe.SetPipelineVariable(_pipelineVarReference); } @@ -3749,27 +3749,27 @@ internal void RemoveVariableListsInPipe() { // Diagnostics.Assert(thisCommand is PSScriptCmdlet, "this is only done for script cmdlets"); - if (_outVarList != null) + if (_outVarList is not null) { this.OutputPipe.RemoveVariableList(VariableStreamKind.Output, _outVarList); } - if (_errorVarList != null) + if (_errorVarList is not null) { this.OutputPipe.RemoveVariableList(VariableStreamKind.Error, _errorVarList); } - if (_warningVarList != null) + if (_warningVarList is not null) { this.OutputPipe.RemoveVariableList(VariableStreamKind.Warning, _warningVarList); } - if (_informationVarList != null) + if (_informationVarList is not null) { this.OutputPipe.RemoveVariableList(VariableStreamKind.Information, _informationVarList); } - if (this.PipelineVariable != null) + if (this.PipelineVariable is not null) { this.OutputPipe.RemovePipelineVariable(); // '_state' could be null when a 'DynamicParam' block runs because the 'DynamicParam' block runs in 'DoPrepare', diff --git a/src/System.Management.Automation/engine/MshMemberInfo.cs b/src/System.Management.Automation/engine/MshMemberInfo.cs index 619dd53e182..fde19184c6d 100644 --- a/src/System.Management.Automation/engine/MshMemberInfo.cs +++ b/src/System.Management.Automation/engine/MshMemberInfo.cs @@ -354,7 +354,7 @@ public override string ToString() StringBuilder returnValue = new StringBuilder(); returnValue.Append(this.Name); returnValue.Append(" = "); - if (ConversionType != null) + if (ConversionType is not null) { returnValue.Append("("); returnValue.Append(ConversionType); @@ -462,7 +462,7 @@ public override string TypeNameOfValue { get { - if (ConversionType != null) + if (ConversionType is not null) { return ConversionType.FullName; } @@ -585,7 +585,7 @@ public override object Value get { object returnValue = this.ReferencedMember.Value; - if (ConversionType != null) + if (ConversionType is not null) { returnValue = LanguagePrimitives.ConvertTo(returnValue, ConversionType, CultureInfo.InvariantCulture); } @@ -863,12 +863,12 @@ public override PSMemberInfo Copy() /// /// Gets true if this property can be set. /// - public override bool IsSettable => this.SetterCodeReference != null; + public override bool IsSettable => this.SetterCodeReference is not null; /// /// Gets true if this property can be read. /// - public override bool IsGettable => GetterCodeReference != null; + public override bool IsGettable => GetterCodeReference is not null; /// /// Gets and Sets the value of this member. @@ -1031,7 +1031,7 @@ public override string ToString() return returnValue.ToString(); } - Diagnostics.Assert((this.baseObject != null) && (this.adapter != null), "if it is deserialized, it should have all these properties set"); + Diagnostics.Assert((this.baseObject is not null) && (this.adapter is not null), "if it is deserialized, it should have all these properties set"); return adapter.BasePropertyToString(this); } @@ -1113,7 +1113,7 @@ private object GetAdaptedValue() return serializedValue; } - Diagnostics.Assert((this.baseObject != null) && (this.adapter != null), "if it is deserialized, it should have all these properties set"); + Diagnostics.Assert((this.baseObject is not null) && (this.adapter is not null), "if it is deserialized, it should have all these properties set"); object o = adapter.BasePropertyGet(this); return o; @@ -1127,7 +1127,7 @@ internal void SetAdaptedValue(object setValue, bool shouldConvert) return; } - Diagnostics.Assert((this.baseObject != null) && (this.adapter != null), "if it is deserialized, it should have all these properties set"); + Diagnostics.Assert((this.baseObject is not null) && (this.adapter is not null), "if it is deserialized, it should have all these properties set"); adapter.BasePropertySet(this, setValue, shouldConvert); } @@ -1154,7 +1154,7 @@ public override bool IsSettable return true; } - Diagnostics.Assert((this.baseObject != null) && (this.adapter != null), "if it is deserialized, it should have all these properties set"); + Diagnostics.Assert((this.baseObject is not null) && (this.adapter is not null), "if it is deserialized, it should have all these properties set"); return adapter.BasePropertyIsSettable(this); } } @@ -1171,7 +1171,7 @@ public override bool IsGettable return true; } - Diagnostics.Assert((this.baseObject != null) && (this.adapter != null), "if it is deserialized, it should have all these properties set"); + Diagnostics.Assert((this.baseObject is not null) && (this.adapter is not null), "if it is deserialized, it should have all these properties set"); return adapter.BasePropertyIsGettable(this); } } @@ -1193,7 +1193,7 @@ public override string TypeNameOfValue if (serializedValue is PSObject serializedValueAsPSObject) { var typeNames = serializedValueAsPSObject.InternalTypeNames; - if ((typeNames != null) && (typeNames.Count >= 1)) + if ((typeNames is not null) && (typeNames.Count >= 1)) { // type name at 0-th index is the most specific type (i.e. deserialized.system.io.directoryinfo) // type names at other indices are less specific (i.e. deserialized.system.object) @@ -1204,7 +1204,7 @@ public override string TypeNameOfValue return serializedValue.GetType().FullName; } - Diagnostics.Assert((this.baseObject != null) && (this.adapter != null), "if it is deserialized, it should have all these properties set"); + Diagnostics.Assert((this.baseObject is not null) && (this.adapter is not null), "if it is deserialized, it should have all these properties set"); return adapter.BasePropertyType(this); } } @@ -1366,7 +1366,7 @@ public override string TypeNameOfValue if (val is PSObject valAsPSObject) { var typeNames = valAsPSObject.InternalTypeNames; - if ((typeNames != null) && (typeNames.Count >= 1)) + if ((typeNames is not null) && (typeNames.Count >= 1)) { // type name at 0-th index is the most specific type (i.e. system.string) // type names at other indices are less specific (i.e. system.object) @@ -1387,7 +1387,7 @@ internal static string GetDisplayTypeNameOfValue(object val) if (val is PSObject valAsPSObject) { var typeNames = valAsPSObject.InternalTypeNames; - if ((typeNames != null) && (typeNames.Count >= 1)) + if ((typeNames is not null) && (typeNames.Count >= 1)) { displayTypeName = typeNames[0]; } @@ -1509,7 +1509,7 @@ public override string TypeNameOfValue if (val is PSObject valAsPSObject) { var typeNames = valAsPSObject.InternalTypeNames; - if ((typeNames != null) && (typeNames.Count >= 1)) + if ((typeNames is not null) && (typeNames.Count >= 1)) { // type name at 0-th index is the most specific type (i.e. system.string) // type names at other indices are less specific (i.e. system.object) @@ -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 is null) && (_getterScriptText is not null)) { _getterScript = ScriptBlock.Create(_getterScriptText); @@ -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 is null) && (_setterScriptText is not null)) { _setterScript = ScriptBlock.Create(_setterScriptText); @@ -1696,12 +1696,12 @@ public PSScriptProperty(string name, ScriptBlock getterScript, ScriptBlock sette throw PSTraceSource.NewArgumentException("getterScript setterScript"); } - if (getterScript != null) + if (getterScript is not null) { getterScript.DebuggerStepThrough = true; } - if (setterScript != null) + if (setterScript is not null) { setterScript.DebuggerStepThrough = true; } @@ -1771,12 +1771,12 @@ public override PSMemberInfo Copy() /// /// Gets true if this property can be set. /// - public override bool IsSettable => this._setterScript != null || this._setterScriptText != null; + public override bool IsSettable => this._setterScript is not null || this._setterScriptText is not null; /// /// Gets true if this property can be read. /// - public override bool IsGettable => this._getterScript != null || this._getterScriptText != null; + public override bool IsGettable => this._getterScript is not null || this._getterScriptText is not null; /// /// Gets and Sets the value of this property. @@ -1885,7 +1885,7 @@ public override string TypeNameOfValue { get { - if ((this.GetterScript != null) && + if ((this.GetterScript is not null) && (this.GetterScript.OutputType.Count > 0)) { return this.GetterScript.OutputType[0].Name; @@ -1996,7 +1996,7 @@ public override int GetHashCode() { int result = 61; - result = result * 397 + (MethodTargetType != null ? MethodTargetType.GetHashCode() : 0); + result = result * 397 + (MethodTargetType is not null ? MethodTargetType.GetHashCode() : 0); result = result * 397 + ParameterTypes.SequenceGetHashCode(); return result; @@ -2007,14 +2007,14 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); string separator = string.Empty; - if (MethodTargetType != null) + if (MethodTargetType is not null) { sb.Append("this: "); sb.Append(ToStringCodeMethods.Type(MethodTargetType, dropNamespaces: true)); separator = " "; } - if (_parameterTypes != null) + if (_parameterTypes is not null) { sb.Append(separator); sb.Append("args: "); @@ -2889,7 +2889,7 @@ public class PSParameterizedProperty : PSMethodInfo /// This property as a string. public override string ToString() { - Diagnostics.Assert((this.baseObject != null) && (this.adapter != null) && (this.adapterData != null), "it should have all these properties set"); + Diagnostics.Assert((this.baseObject is not null) && (this.adapter is not null) && (this.adapterData is not null), "it should have all these properties set"); return this.adapter.BaseParameterizedPropertyToString(this); } @@ -3116,7 +3116,7 @@ public PSMemberSet(string name, IEnumerable members) internal PSMemberSet(string name, PSMemberInfoInternalCollection members) { Diagnostics.Assert(!string.IsNullOrEmpty(name), "Caller needs to guarantee not null or empty."); - Diagnostics.Assert(members != null, "Caller needs to guarantee not null."); + Diagnostics.Assert(members is not null, "Caller needs to guarantee not null."); this.name = name; this.internalMembers = members; @@ -3355,7 +3355,7 @@ private void GenerateInternalMembersFromBase() { if (_psObject.IsDeserialized) { - if (_psObject.ClrMembers != null) + if (_psObject.ClrMembers is not null) { foreach (PSMemberInfo member in _psObject.ClrMembers) { @@ -3379,7 +3379,7 @@ private PSMemberInfoInternalCollection GetInternalMembersFromAdapt if (_psObject.IsDeserialized) { - if (_psObject.AdaptedMembers != null) + if (_psObject.AdaptedMembers is not null) { foreach (PSMemberInfo member in _psObject.AdaptedMembers) { @@ -3486,7 +3486,7 @@ public PSPropertySet(string name, IEnumerable referencedPropertyNames) internal PSPropertySet(string name, List referencedPropertyNameList) { Diagnostics.Assert(!string.IsNullOrEmpty(name), "Caller needs to guarantee not null or empty."); - Diagnostics.Assert(referencedPropertyNameList != null, "Caller needs to guarantee not null."); + Diagnostics.Assert(referencedPropertyNameList is not null, "Caller needs to guarantee not null."); // We use the constructor 'public Collection(IList list)' to create the collection, // so that the passed-in list is directly used as the backing store of the collection. @@ -3670,7 +3670,7 @@ internal class MemberMatch { internal static WildcardPattern GetNamePattern(string name) { - if (name != null && WildcardPattern.ContainsWildcardCharacters(name)) + if (name is not null && WildcardPattern.ContainsWildcardCharacters(name)) { return WildcardPattern.Get(name, WildcardOptions.IgnoreCase); } @@ -3704,7 +3704,7 @@ internal static PSMemberInfoInternalCollection Match(PSMemberInfoInternalC if (nameMatch is null) { T member = memberList[name]; - if (member != null && (member.MemberType & memberTypes) != 0) + if (member is not null && (member.MemberType & memberTypes) != 0) { returnValue.Add(member); } @@ -4034,14 +4034,14 @@ private void Replace(T oldMember, T newMember) /// internal void Replace(T newMember) { - Diagnostics.Assert(newMember != null, "called from internal code that checks for new member not null"); + Diagnostics.Assert(newMember is not null, "called from internal code that checks for new member not null"); // Save to a local variable to reduce property access. var members = Members; lock (members) { var oldMember = members[newMember.Name] as T; - Diagnostics.Assert(oldMember != null, "internal code checks member already exists"); + Diagnostics.Assert(oldMember is not null, "internal code checks member already exists"); Replace(oldMember, newMember); } } @@ -4454,7 +4454,7 @@ public static Collection PSTypeNames(PSObject o) internal static void GeneratePSTypeNames(object obj) { PSObject mshOwner = PSObject.AsPSObject(obj); - if (mshOwner.InstanceMembers[PSObject.PSTypeNames] != null) + if (mshOwner.InstanceMembers[PSObject.PSTypeNames] is not null) { // PSTypeNames member set is already generated..just return. return; @@ -4576,7 +4576,7 @@ public override void Add(T member, bool preValidated) ExtendedTypeSystem.CannotAddPropertyOrMethod); } - if (_memberSetOwner != null && _memberSetOwner.IsReservedMember) + if (_memberSetOwner is not null && _memberSetOwner.IsReservedMember) { throw new ExtendedTypeSystemException("CannotAddToReservedNameMemberset", null, @@ -4597,7 +4597,7 @@ internal void AddToReservedMemberSet(T member, bool preValidated) { if (!preValidated) { - if (_memberSetOwner != null && !_memberSetOwner.IsInstance) + if (_memberSetOwner is not null && !_memberSetOwner.IsInstance) { throw new ExtendedTypeSystemException("RemoveMemberFromStaticMemberSet", null, @@ -4644,12 +4644,12 @@ internal void AddToTypesXmlCache(T member, bool preValidated) PSMemberInfo memberToBeAdded = member.Copy(); - if (_mshOwner != null) + if (_mshOwner is not null) { if (!preValidated) { TypeTable typeTable = _mshOwner.GetTypeTable(); - if (typeTable != null) + if (typeTable is not null) { var typesXmlMembers = typeTable.GetMembers(_mshOwner.InternalTypeNames); var typesXmlMember = typesXmlMembers[member.Name]; @@ -4696,7 +4696,7 @@ public override void Remove(string name) throw PSTraceSource.NewArgumentException(nameof(name)); } - if (_mshOwner != null) + if (_mshOwner is not null) { _mshOwner.InstanceMembers.Remove(name); return; @@ -4780,7 +4780,7 @@ public override T this[string name] PSMemberInfo member; object delegateOwner; - if (_mshOwner != null) + if (_mshOwner is not null) { // this will check if name is a reserved name like PSBase, PSTypeNames // if it is a reserved name, ensures the value is loaded. @@ -4818,9 +4818,9 @@ public override T this[string name] delegateOwner = PSObject.AsPSObject(delegateOwner); foreach (CollectionEntry collection in Collections) { - Diagnostics.Assert(delegateOwner != null, "all integrating collections with non empty collections have an associated PSObject"); + Diagnostics.Assert(delegateOwner is not null, "all integrating collections with non empty collections have an associated PSObject"); T memberAsT = collection.GetMember((PSObject)delegateOwner, name); - if (memberAsT != null) + if (memberAsT is not null) { return collection.CloneOrReplicateObject(delegateOwner, memberAsT); } @@ -4837,7 +4837,7 @@ private PSMemberInfoInternalCollection GetIntegratedMembers(MshMemberMatchOpt { PSMemberInfoInternalCollection returnValue = new PSMemberInfoInternalCollection(); object delegateOwner; - if (_mshOwner != null) + if (_mshOwner is not null) { delegateOwner = _mshOwner; foreach (PSMemberInfo member in _mshOwner.InstanceMembers) @@ -4877,7 +4877,7 @@ private PSMemberInfoInternalCollection GetIntegratedMembers(MshMemberMatchOpt foreach (T member in members) { PSMemberInfo previousMember = returnValue[member.Name]; - if (previousMember != null) + if (previousMember is not null) { PSObject.MemberResolution.WriteLine("Member \"{0}\" of type \"{1}\" has been ignored because a member with the same name and type \"{2}\" is already present.", member.Name, member.MemberType, previousMember.MemberType); @@ -4949,7 +4949,7 @@ internal override ReadOnlyPSMemberInfoCollection Match(string name, PSMemberT throw PSTraceSource.NewArgumentException(nameof(name)); } - if (_mshOwner != null) + if (_mshOwner is not null) { GenerateAllReservedMembers(); } @@ -4976,7 +4976,7 @@ public override IEnumerator GetEnumerator() internal override T FirstOrDefault(MemberNamePredicate predicate) { object delegateOwner; - if (_mshOwner != null) + if (_mshOwner is not null) { delegateOwner = _mshOwner; foreach (PSMemberInfo member in _mshOwner.InstanceMembers) @@ -5010,7 +5010,7 @@ internal override T FirstOrDefault(MemberNamePredicate predicate) { var collectionEntry = Collections[i]; var member = collectionEntry.GetFirstOrDefault(ownerAsPSObj, predicate); - if (member != null) + if (member is not null) { return collectionEntry.CloneOrReplicateObject(ownerAsPSObj, member); } @@ -5041,7 +5041,7 @@ internal Enumerator(PSMemberInfoIntegratingCollection integratingCollection) _currentIndex = -1; _current = null; _allMembers = integratingCollection.GetIntegratedMembers(MshMemberMatchOptions.None); - if (integratingCollection._mshOwner != null) + if (integratingCollection._mshOwner is not null) { integratingCollection.GenerateAllReservedMembers(); PSObject.MemberResolution.WriteLine("Enumerating PSObject with type \"{0}\".", integratingCollection._mshOwner.ImmediateBaseObject.GetType().FullName); diff --git a/src/System.Management.Automation/engine/MshObject.cs b/src/System.Management.Automation/engine/MshObject.cs index 90a4177ebc3..a23e7881c40 100644 --- a/src/System.Management.Automation/engine/MshObject.cs +++ b/src/System.Management.Automation/engine/MshObject.cs @@ -53,7 +53,7 @@ public class PSObject : IFormattable, IComparable, ISerializable, IDynamicMetaOb internal TypeTable GetTypeTable() { - if (_typeTable != null && _typeTable.TryGetTarget(out TypeTable typeTable)) + if (_typeTable is not null && _typeTable.TryGetTarget(out TypeTable typeTable)) { return typeTable; } @@ -205,7 +205,7 @@ private static PSMemberInfoInternalCollection AdapterGetMembersDelegate(PS private static PSMemberInfoInternalCollection DotNetGetMembersDelegate(PSObject msjObj) where T : PSMemberInfo { // Don't lookup dotnet members if the object doesn't insist. - if (msjObj.InternalBaseDotNetAdapter != null) + if (msjObj.InternalBaseDotNetAdapter is not null) { PSMemberInfoInternalCollection retValue = msjObj.InternalBaseDotNetAdapter.BaseGetMembers(msjObj._immediateBaseObject); PSObject.MemberResolution.WriteLine("DotNet members: {0}.", retValue.VisibleCount); @@ -218,7 +218,7 @@ private static PSMemberInfoInternalCollection DotNetGetMembersDelegate(PSO private static T DotNetGetMemberDelegate(PSObject msjObj, string name) where T : PSMemberInfo { // Don't lookup dotnet member if the object doesn't insist. - if (msjObj.InternalBaseDotNetAdapter != null) + if (msjObj.InternalBaseDotNetAdapter is not null) { T retValue = msjObj.InternalBaseDotNetAdapter.BaseGetMember(msjObj._immediateBaseObject, name); PSObject.MemberResolution.WriteLine("DotNet member: {0}.", retValue is null ? "not found" : retValue.Name); @@ -410,7 +410,7 @@ internal static Collection> GetPropertyCollectio private void CommonInitialization(object obj) { - Diagnostics.Assert(obj != null, "checked by callers"); + Diagnostics.Assert(obj is not null, "checked by callers"); if (obj is PSCustomObject) { this.ImmediateBaseObjectIsEmpty = true; @@ -463,7 +463,7 @@ internal static AdapterSet GetMappedAdapter(object obj, TypeTable typeTable) PSObject.AdapterSet adapter = typeTable?.GetTypeAdapter(objectType); - if (adapter != null) + if (adapter is not null) { // We don't cache results found via the type table because type tables may differ b/w runspaces, // our cache is app domain wide, and the key is simply the type. @@ -480,7 +480,7 @@ internal static AdapterSet GetMappedAdapter(object obj, TypeTable typeTable) foreach (var mapper in s_adapterSetMappers) { result = mapper(obj); - if (result != null) + if (result is not null) { break; } @@ -509,14 +509,14 @@ internal static AdapterSet GetMappedAdapter(object obj, TypeTable typeTable) // (typically), the runtime type is always the same. That's why this if statement is here and returns. ComTypeInfo info = ComTypeInfo.GetDispatchTypeInfo(obj); - return info != null + return info is not null ? new AdapterSet(new ComAdapter(info), DotNetInstanceAdapter) : PSObject.s_dotNetInstanceAdapterSet; } else { ComTypeInfo info = ComTypeInfo.GetDispatchTypeInfo(obj); - result = info != null + result = info is not null ? new AdapterSet(new DotNetAdapterWithComTypeName(info), null) : PSObject.s_dotNetInstanceAdapterSet; } @@ -820,7 +820,7 @@ public object BaseObject { returnValue = mshObj._immediateBaseObject; mshObj = returnValue as PSObject; - } while (mshObj != null); + } while (mshObj is not null); return returnValue; } @@ -847,7 +847,7 @@ public Collection TypeNames object baseObj = BaseObject; // In most cases, the TypeNames will be modified after it's returned - if (baseObj != null) { PSVariableAssignmentBinder.NoteTypeHasInstanceMemberOrTypeName(baseObj.GetType()); } + if (baseObj is not null) { PSVariableAssignmentBinder.NoteTypeHasInstanceMemberOrTypeName(baseObj.GetType()); } return _typeNames; } @@ -925,7 +925,7 @@ internal static bool HasInstanceMembers(object obj, out PSMemberInfoInternalColl instanceMembers = psobj._instanceMembers; } - else if (obj != null) + else if (obj is not null) { s_instanceMembersResurrectionTable.TryGetValue(GetKeyForResurrectionTables(obj), out instanceMembers); } @@ -934,7 +934,7 @@ internal static bool HasInstanceMembers(object obj, out PSMemberInfoInternalColl instanceMembers = null; } - return instanceMembers != null && instanceMembers.Count > 0; + return instanceMembers is not null && instanceMembers.Count > 0; } private static readonly ConditionalWeakTable> s_instanceMembersResurrectionTable = @@ -1006,7 +1006,7 @@ internal static object Base(object obj) { returnValue = mshObj._immediateBaseObject; mshObj = returnValue as PSObject; - } while ((mshObj != null) && (!mshObj.ImmediateBaseObjectIsEmpty)); + } while ((mshObj is not null) && (!mshObj.ImmediateBaseObjectIsEmpty)); return returnValue; } @@ -1102,13 +1102,13 @@ internal static object GetKeyForResurrectionTables(object obj) private static string GetSeparator(ExecutionContext context, string separator) { - if (separator != null) + if (separator is not null) { return separator; } object obj = context?.GetVariableValue(SpecialVariables.OFSVarPath); - if (obj != null) + if (obj is not null) { return obj.ToString(); } @@ -1143,7 +1143,7 @@ internal static string ToStringEnumerable(ExecutionContext context, IEnumerable string separatorToUse = GetSeparator(context, separator); foreach (object obj in enumerable) { - if (obj != null) + if (obj is not null) { PSObject mshObj = PSObject.AsPSObject(obj); returnValue.Append(PSObject.ToString(context, mshObj, separator, format, formatProvider, false, false)); @@ -1325,7 +1325,7 @@ bool TryFastTrackPrimitiveTypes(object value, out string str) if (recurse) { IEnumerable enumerable = LanguagePrimitives.GetEnumerable(obj); - if (enumerable != null) + if (enumerable is not null) { try { @@ -1340,7 +1340,7 @@ bool TryFastTrackPrimitiveTypes(object value, out string str) if (unravelEnumeratorOnRecurse) { IEnumerator enumerator = LanguagePrimitives.GetEnumerator(obj); - if (enumerator != null) + if (enumerator is not null) { try { @@ -1363,7 +1363,7 @@ bool TryFastTrackPrimitiveTypes(object value, out string str) if (objFormattable is null) { Type type = obj as Type; - if (type != null) + if (type is not null) { return Microsoft.PowerShell.ToStringCodeMethods.Type(type); } @@ -1398,10 +1398,10 @@ bool TryFastTrackPrimitiveTypes(object value, out string str) if (mshObj.InternalTypeNames.Count != 0) { TypeTable table = mshObj.GetTypeTable(); - if (table != null) + if (table is not null) { method = table.GetMembers(mshObj.InternalTypeNames)["ToString"]; - if (method != null) + if (method is not null) { method = (PSMethodInfo)method.Copy(); method.instance = mshObj; @@ -1410,21 +1410,21 @@ bool TryFastTrackPrimitiveTypes(object value, out string str) } } - if (method != null) + if (method is not null) { try { // Even if a format specifier has been provided, if there is only one overload // then it can't take a format specified... object retObj; - if (formatProvider != null && method.OverloadDefinitions.Count > 1) + if (formatProvider is not null && method.OverloadDefinitions.Count > 1) { retObj = method.Invoke(format, formatProvider); - return retObj != null ? retObj.ToString() : string.Empty; + return retObj is not null ? retObj.ToString() : string.Empty; } retObj = method.Invoke(); - return retObj != null ? retObj.ToString() : string.Empty; + return retObj is not null ? retObj.ToString() : string.Empty; } catch (MethodException e) { @@ -1451,7 +1451,7 @@ bool TryFastTrackPrimitiveTypes(object value, out string str) } IEnumerable enumerable = LanguagePrimitives.GetEnumerable(mshObj); - if (enumerable != null) + if (enumerable is not null) { try { @@ -1466,7 +1466,7 @@ bool TryFastTrackPrimitiveTypes(object value, out string str) if (unravelEnumeratorOnRecurse) { IEnumerator enumerator = LanguagePrimitives.GetEnumerator(mshObj); - if (enumerator != null) + if (enumerator is not null) { try { @@ -1485,7 +1485,7 @@ bool TryFastTrackPrimitiveTypes(object value, out string str) // If we've cached a string representation for this object, use that. This // is used to preserve the original string for numeric literals. - if (mshObj.TokenText != null) + if (mshObj.TokenText is not null) { return mshObj.TokenText; } @@ -1527,7 +1527,7 @@ public override string ToString() { // If ToString value from deserialization is available, // simply return it. - if (ToStringFromDeserialization != null) + if (ToStringFromDeserialization is not null) { return ToStringFromDeserialization; } @@ -1548,7 +1548,7 @@ public string ToString(string format, IFormatProvider formatProvider) { // If ToString value from deserialization is available, // simply return it. - if (ToStringFromDeserialization != null) + if (ToStringFromDeserialization is not null) { return ToStringFromDeserialization; } @@ -1881,7 +1881,7 @@ internal int GetSerializationDepth(TypeTable backupTypeTable) int result = 0; TypeTable typeTable = backupTypeTable ?? this.GetTypeTable(); - if (typeTable != null) + if (typeTable is not null) { PSMemberSet standardMemberSet = TypeTableGetMemberDelegate(this, typeTable, TypeTable.PSStandardMembers); @@ -1918,7 +1918,7 @@ internal SerializationMethod GetSerializationMethod(TypeTable backupTypeTable) SerializationMethod result = TypeTable.DefaultSerializationMethod; TypeTable typeTable = backupTypeTable ?? this.GetTypeTable(); - if (typeTable != null) + if (typeTable is not null) { PSMemberSet standardMemberSet = TypeTableGetMemberDelegate(this, typeTable, TypeTable.PSStandardMembers); @@ -1934,7 +1934,7 @@ internal PSMemberSet PSStandardMembers get { var retVal = TypeTableGetMemberDelegate(this, TypeTable.PSStandardMembers); - if (retVal != null) + if (retVal is not null) { retVal = (PSMemberSet)retVal.Copy(); retVal.ReplicateInstance(this); @@ -1951,11 +1951,11 @@ internal PSMemberInfo GetPSStandardMember(TypeTable backupTypeTable, string memb PSMemberInfo result = null; TypeTable typeTable = backupTypeTable ?? this.GetTypeTable(); - if (typeTable != null) + if (typeTable is not null) { PSMemberSet standardMemberSet = TypeTableGetMemberDelegate( this, typeTable, TypeTable.PSStandardMembers); - if (standardMemberSet != null) + if (standardMemberSet is not null) { standardMemberSet.ReplicateInstance(this); PSMemberInfoIntegratingCollection members = @@ -1996,7 +1996,7 @@ internal Type GetTargetTypeForDeserialization(TypeTable backupTypeTable) internal Collection GetSpecificPropertiesToSerialize(TypeTable backupTypeTable) { TypeTable typeTable = backupTypeTable ?? this.GetTypeTable(); - if (typeTable != null) + if (typeTable is not null) { Collection tmp = typeTable.GetSpecificProperties(this.InternalTypeNames); return tmp; @@ -2009,7 +2009,7 @@ internal bool ShouldSerializeAdapter() { if (this.IsDeserialized) { - return this.AdaptedMembers != null; + return this.AdaptedMembers is not null; } return !this.ImmediateBaseObjectIsEmpty; @@ -2062,7 +2062,7 @@ internal static void CopyDeserializerFields(PSObject source, PSObject target) internal void SetCoreOnDeserialization(object value, bool overrideTypeInfo) { Diagnostics.Assert(this.ImmediateBaseObjectIsEmpty, "BaseObject should be PSCustomObject for deserialized objects"); - Diagnostics.Assert(value != null, "known objects are never null"); + Diagnostics.Assert(value is not null, "known objects are never null"); this.ImmediateBaseObjectIsEmpty = false; _immediateBaseObject = value; _adapterSet = GetMappedAdapter(_immediateBaseObject, GetTypeTable()); diff --git a/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs b/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs index 77baee2486a..71cfc2b6d61 100644 --- a/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs +++ b/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs @@ -236,7 +236,7 @@ private static PSObject GetComponentPSObject(object component) private object DealWithGetValueException(ExtendedTypeSystemException e, out bool shouldThrow) { GettingValueExceptionEventArgs eventArgs = new GettingValueExceptionEventArgs(e); - if (GettingValueException != null) + if (GettingValueException is not null) { GettingValueException.SafeInvoke(this, eventArgs); PSObjectTypeDescriptor.typeDescriptor.WriteLine( @@ -312,7 +312,7 @@ public override void SetValue(object component, object value) private void DealWithSetValueException(ExtendedTypeSystemException e, out bool shouldThrow) { SettingValueExceptionEventArgs eventArgs = new SettingValueExceptionEventArgs(e); - if (SettingValueException != null) + if (SettingValueException is not null) { SettingValueException.SafeInvoke(this, eventArgs); PSObjectTypeDescriptor.typeDescriptor.WriteLine( @@ -378,10 +378,10 @@ private void CheckAndAddProperty(PSPropertyInfo propertyInfo, Attribute[] attrib AttributeCollection propertyAttributes = null; Type propertyType = typeof(object); - if (attributes != null && attributes.Length != 0) + if (attributes is not null && attributes.Length != 0) { PSProperty property = propertyInfo as PSProperty; - if (property != null) + if (property is not null) { DotNetAdapter.PropertyCacheEntry propertyEntry = property.adapterData as DotNetAdapter.PropertyCacheEntry; if (propertyEntry is null) @@ -508,10 +508,10 @@ public override PropertyDescriptor GetDefaultProperty() string defaultProperty = null; PSMemberSet standardMembers = this.Instance.PSStandardMembers; - if (standardMembers != null) + if (standardMembers is not null) { PSNoteProperty note = standardMembers.Properties[TypeTable.DefaultDisplayProperty] as PSNoteProperty; - if (note != null) + if (note is not null) { defaultProperty = note.Value as string; } @@ -523,7 +523,7 @@ public override PropertyDescriptor GetDefaultProperty() if (defaultPropertyAttributes.Length == 1) { DefaultPropertyAttribute defaultPropertyAttribute = defaultPropertyAttributes[0] as DefaultPropertyAttribute; - if (defaultPropertyAttribute != null) + if (defaultPropertyAttribute is not null) { defaultProperty = defaultPropertyAttribute.Name; } @@ -532,7 +532,7 @@ public override PropertyDescriptor GetDefaultProperty() PropertyDescriptorCollection properties = this.GetProperties(); - if (defaultProperty != null) + if (defaultProperty is not null) { // There is a defaultProperty, but let's check if it is actually one of the properties we are // returning in GetProperties diff --git a/src/System.Management.Automation/engine/MshReference.cs b/src/System.Management.Automation/engine/MshReference.cs index 05077708608..009416835e3 100644 --- a/src/System.Management.Automation/engine/MshReference.cs +++ b/src/System.Management.Automation/engine/MshReference.cs @@ -49,7 +49,7 @@ public object Value { PSVariable variable = _value as PSVariable; - if (variable != null) + if (variable is not null) { return variable.Value; } @@ -61,7 +61,7 @@ public object Value { PSVariable variable = _value as PSVariable; - if (variable != null) + if (variable is not null) { variable.Value = value; return; diff --git a/src/System.Management.Automation/engine/MshSnapinQualifiedName.cs b/src/System.Management.Automation/engine/MshSnapinQualifiedName.cs index 86aed4ad1e3..61090bebeda 100644 --- a/src/System.Management.Automation/engine/MshSnapinQualifiedName.cs +++ b/src/System.Management.Automation/engine/MshSnapinQualifiedName.cs @@ -14,7 +14,7 @@ internal class PSSnapinQualifiedName { private PSSnapinQualifiedName(string[] splitName) { - Dbg.Assert(splitName != null, "splitName should not be null"); + Dbg.Assert(splitName is not null, "splitName should not be null"); Dbg.Assert(splitName.Length == 1 || splitName.Length == 2, "splitName should contain 1 or 2 elements"); if (splitName.Length == 1) diff --git a/src/System.Management.Automation/engine/NativeCommand.cs b/src/System.Management.Automation/engine/NativeCommand.cs index 822d4cf82d9..e2286f19131 100644 --- a/src/System.Management.Automation/engine/NativeCommand.cs +++ b/src/System.Management.Automation/engine/NativeCommand.cs @@ -26,7 +26,7 @@ internal override void DoStopProcessing() { try { - if (_myCommandProcessor != null) + if (_myCommandProcessor is not null) _myCommandProcessor.StopProcessing(); } catch (Exception) diff --git a/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs b/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs index e951f5b5f05..bfca5e52200 100644 --- a/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs +++ b/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs @@ -249,7 +249,7 @@ private void AppendOneNativeArgument(ExecutionContext context, object obj, Array } } } - while (list != null); + while (list is not null); } /// diff --git a/src/System.Management.Automation/engine/NativeCommandProcessor.cs b/src/System.Management.Automation/engine/NativeCommandProcessor.cs index 7d3ec0d2bfc..9baf68ce737 100644 --- a/src/System.Management.Automation/engine/NativeCommandProcessor.cs +++ b/src/System.Management.Automation/engine/NativeCommandProcessor.cs @@ -66,7 +66,7 @@ internal static class StringToMinishellStreamConverter internal static MinishellStream ToMinishellStream(string stream) { - Dbg.Assert(stream != null, "caller should validate the parameter"); + Dbg.Assert(stream is not null, "caller should validate the parameter"); MinishellStream ms = MinishellStream.Unknown; if (OutputStream.Equals(stream, StringComparison.OrdinalIgnoreCase)) @@ -193,7 +193,7 @@ private NativeCommand nativeCommand get { NativeCommand command = this.Command as NativeCommand; - Diagnostics.Assert(command != null, "this.Command is created in the constructor."); + Diagnostics.Assert(command is not null, "this.Command is created in the constructor."); return command; } } @@ -583,7 +583,7 @@ private void InitNativeProcess() // An exception was thrown while attempting to run the program // so wrap and rethrow it here... - if (exceptionToRethrow != null) + if (exceptionToRethrow is not null) { // It's a system exception so wrap it in one of ours and re-throw. string message = StringUtil.Format(ParserStrings.ProgramFailedToExecute, @@ -658,7 +658,7 @@ private void ConsumeAvailableNativeProcessOutput(bool blocking) if (_nativeProcess.StartInfo.RedirectStandardOutput || _nativeProcess.StartInfo.RedirectStandardError) { ProcessOutputObject record; - while ((record = DequeueProcessOutput(blocking)) != null) + while ((record = DequeueProcessOutput(blocking)) is not null) { if (this.Command.Context.CurrentPipelineStopping) { @@ -749,7 +749,7 @@ internal override void Complete() // An exception was thrown while attempting to run the program // so wrap and rethrow it here... - if (exceptionToRethrow != null) + if (exceptionToRethrow is not null) { // It's a system exception so wrap it in one of ours and re-throw. string message = StringUtil.Format(ParserStrings.ProgramFailedToExecute, @@ -860,7 +860,7 @@ private void ConstructParentId() _parentId = -1; Process parentProcess = PsUtils.GetParentProcess(OriginalProcessInstance); - if (parentProcess != null) + if (parentProcess is not null) { _parentId = parentProcess.Id; } @@ -987,7 +987,7 @@ internal void StopProcessing() _stopped = true; } - if (_nativeProcess != null) + if (_nativeProcess is not null) { if (!_runStandAlone) { @@ -1015,7 +1015,7 @@ private void CleanUp() try { // Dispose the process if it's already created - if (_nativeProcess != null) + if (_nativeProcess is not null) { _nativeProcess.Dispose(); } @@ -1027,12 +1027,12 @@ private void CleanUp() private void ProcessOutputRecord(ProcessOutputObject outputValue) { - Dbg.Assert(outputValue != null, "only object of type ProcessOutputObject expected"); + Dbg.Assert(outputValue is not null, "only object of type ProcessOutputObject expected"); if (outputValue.Stream == MinishellStream.Error) { ErrorRecord record = outputValue.Data as ErrorRecord; - Dbg.Assert(record != null, "ProcessReader should ensure that data is ErrorRecord"); + Dbg.Assert(record is not null, "ProcessReader should ensure that data is ErrorRecord"); record.SetInvocationInfo(this.Command.MyInvocation); this.commandRuntime._WriteErrorSkipAllowCheck(record, isNativeError: true); } @@ -1043,41 +1043,41 @@ private void ProcessOutputRecord(ProcessOutputObject outputValue) else if (outputValue.Stream == MinishellStream.Debug) { string temp = outputValue.Data as string; - Dbg.Assert(temp != null, "ProcessReader should ensure that data is string"); + Dbg.Assert(temp is not null, "ProcessReader should ensure that data is string"); this.Command.PSHostInternal.UI.WriteDebugLine(temp); } else if (outputValue.Stream == MinishellStream.Verbose) { string temp = outputValue.Data as string; - Dbg.Assert(temp != null, "ProcessReader should ensure that data is string"); + Dbg.Assert(temp is not null, "ProcessReader should ensure that data is string"); this.Command.PSHostInternal.UI.WriteVerboseLine(temp); } else if (outputValue.Stream == MinishellStream.Warning) { string temp = outputValue.Data as string; - Dbg.Assert(temp != null, "ProcessReader should ensure that data is string"); + Dbg.Assert(temp is not null, "ProcessReader should ensure that data is string"); this.Command.PSHostInternal.UI.WriteWarningLine(temp); } else if (outputValue.Stream == MinishellStream.Progress) { PSObject temp = outputValue.Data as PSObject; - if (temp != null) + if (temp is not null) { long sourceId = 0; PSMemberInfo info = temp.Properties["SourceId"]; - if (info != null) + if (info is not null) { sourceId = (long)info.Value; } info = temp.Properties["Record"]; ProgressRecord rec = null; - if (info != null) + if (info is not null) { rec = info.Value as ProgressRecord; } - if (rec != null) + if (rec is not null) { this.Command.PSHostInternal.UI.WriteProgress(sourceId, rec); } @@ -1086,7 +1086,7 @@ private void ProcessOutputRecord(ProcessOutputObject outputValue) else if (outputValue.Stream == MinishellStream.Information) { InformationRecord record = outputValue.Data as InformationRecord; - Dbg.Assert(record != null, "ProcessReader should ensure that data is InformationRecord"); + Dbg.Assert(record is not null, "ProcessReader should ensure that data is InformationRecord"); this.commandRuntime.WriteInformation(record); } } @@ -1167,11 +1167,11 @@ private ProcessStartInfo GetProcessStartInfo(bool redirectOutput, bool redirectE private bool IsDownstreamOutDefault(Pipe downstreamPipe) { - Diagnostics.Assert(downstreamPipe != null, "Caller makes sure the passed-in parameter is not null."); + Diagnostics.Assert(downstreamPipe is not null, "Caller makes sure the passed-in parameter is not null."); // Check if the downstream cmdlet is Out-Default, which is the default outputter. CommandProcessorBase outputProcessor = downstreamPipe.DownstreamCmdlet; - if (outputProcessor != null) + if (outputProcessor is not null) { // We have the test 'utscript\Engine\TestOutDefaultRedirection.ps1' to check that a user defined // Out-Default function should not cause a native command to be redirected. So here we should only @@ -1511,7 +1511,7 @@ private void decrementRefCount() private void OutputHandler(object sender, DataReceivedEventArgs outputReceived) { - if (outputReceived.Data != null) + if (outputReceived.Data is not null) { if (_isFirstOutput) { @@ -1543,7 +1543,7 @@ private void OutputHandler(object sender, DataReceivedEventArgs outputReceived) private void ErrorHandler(object sender, DataReceivedEventArgs errorReceived) { - if (errorReceived.Data != null) + if (errorReceived.Data is not null) { if (string.Equals(errorReceived.Data, XmlCliTag, StringComparison.Ordinal)) { @@ -1598,7 +1598,7 @@ private List DeserializeCliXmlObject(string xml, bool isOut // Decide the stream to which data belongs MinishellStream stream = MinishellStream.Unknown; - if (streamName != null) + if (streamName is not null) { stream = StringToMinishellStreamConverter.ToMinishellStream(streamName); } @@ -1714,7 +1714,7 @@ internal class ProcessInputWriter /// internal ProcessInputWriter(InternalCommand command) { - Dbg.Assert(command != null, "Caller should validate the parameter"); + Dbg.Assert(command is not null, "Caller should validate the parameter"); _command = command; } @@ -1807,7 +1807,7 @@ private void AddXmlInput(object input) /// internal void Start(Process process, NativeCommandIOFormat inputFormat) { - Dbg.Assert(process != null, "caller should validate the paramter"); + Dbg.Assert(process is not null, "caller should validate the paramter"); // Get the encoding for writing to native command. Note we get the Encoding // from the current scope so a script or function can use a different encoding @@ -1850,19 +1850,19 @@ internal void Dispose() // and once from Done() code path. // Even though Dispose() could be called multiple times, // the calls are on the same thread, so there is no race condition - if (_pipeline != null) + if (_pipeline is not null) { _pipeline.Dispose(); _pipeline = null; } - if (_xmlSerializer != null) + if (_xmlSerializer is not null) { _xmlSerializer = null; } // streamWriter can be null if we didn't call Start method - if (_streamWriter != null) + if (_streamWriter is not null) { try { @@ -1883,7 +1883,7 @@ internal void Done() { if (_inputFormat == NativeCommandIOFormat.Xml) { - if (_xmlSerializer != null) + if (_xmlSerializer is not null) { _xmlSerializer.Done(); } @@ -1892,7 +1892,7 @@ internal void Done() { // if _pipeline is null, we already called Dispose(), // for example, because downstream process finished - if (_pipeline != null) + if (_pipeline is not null) { var finalResults = _pipeline.End(); AddTextInputFromFormattedArray(finalResults); @@ -2190,7 +2190,7 @@ public override ErrorRecord ErrorRecord { get { - if (_remoteErrorRecord != null) + if (_remoteErrorRecord is not null) return _remoteErrorRecord; return base.ErrorRecord; diff --git a/src/System.Management.Automation/engine/ObjectEventRegistrationBase.cs b/src/System.Management.Automation/engine/ObjectEventRegistrationBase.cs index 3c385a6f7bf..079b778f209 100644 --- a/src/System.Management.Automation/engine/ObjectEventRegistrationBase.cs +++ b/src/System.Management.Automation/engine/ObjectEventRegistrationBase.cs @@ -157,7 +157,7 @@ protected PSEventSubscriber NewSubscriber /// protected override void BeginProcessing() { - if (((bool)_forward) && (_action != null)) + if (((bool)_forward) && (_action is not null)) { ThrowTerminatingError( new ErrorRecord( @@ -179,7 +179,7 @@ protected override void EndProcessing() try { if ( - ((inputObject != null) || (eventName != null)) && + ((inputObject is not null) || (eventName is not null)) && (Events.GetEventSubscribers(_sourceIdentifier).GetEnumerator().MoveNext()) ) { @@ -203,7 +203,7 @@ protected override void EndProcessing() eventName, _sourceIdentifier, _messageData, _action, (bool)_supportEvent, (bool)_forward, _maxTriggerCount); - if ((_action != null) && (!(bool)_supportEvent)) + if ((_action is not null) && (!(bool)_supportEvent)) WriteObject(_newSubscriber.Action); } } diff --git a/src/System.Management.Automation/engine/PSClassInfo.cs b/src/System.Management.Automation/engine/PSClassInfo.cs index 199f7f1b2b7..d3cd320f481 100644 --- a/src/System.Management.Automation/engine/PSClassInfo.cs +++ b/src/System.Management.Automation/engine/PSClassInfo.cs @@ -36,7 +36,7 @@ internal PSClassInfo(string name) /// Updated members. public void UpdateMembers(IList members) { - if (members != null) + if (members is not null) this.Members = new ReadOnlyCollection(members); } diff --git a/src/System.Management.Automation/engine/PSClassSearcher.cs b/src/System.Management.Automation/engine/PSClassSearcher.cs index 7bb815ba6e9..ef51336e3f7 100644 --- a/src/System.Management.Automation/engine/PSClassSearcher.cs +++ b/src/System.Management.Automation/engine/PSClassSearcher.cs @@ -22,10 +22,10 @@ internal PSClassSearcher( bool useWildCards, ExecutionContext context) { - Diagnostics.Assert(context != null, "caller to verify context is not null"); + Diagnostics.Assert(context is not null, "caller to verify context is not null"); _context = context; - Diagnostics.Assert(className != null, "caller to verify className is not null"); + Diagnostics.Assert(className is not null, "caller to verify className is not null"); _className = className; _useWildCards = useWildCards; _moduleInfoCache = new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -90,7 +90,7 @@ public bool MoveNext() { _currentMatch = GetNextClass(); - if (_currentMatch != null) + if (_currentMatch is not null) return true; return false; @@ -165,7 +165,7 @@ private bool FindTypeByModulePath(WildcardPattern classNameMatcher) string expandedModulePath = IO.Path.GetFullPath(modulePath); var cachedClasses = AnalysisCache.GetExportedClasses(expandedModulePath, _context); - if (cachedClasses != null) + if (cachedClasses is not null) { // Exact match if (!_useWildCards) @@ -173,7 +173,7 @@ private bool FindTypeByModulePath(WildcardPattern classNameMatcher) if (cachedClasses.ContainsKey(_className)) { var classInfo = CachedItemToPSClassInfo(classNameMatcher, modulePath); - if (classInfo != null) + if (classInfo is not null) { _matchingClassList.Add(classInfo); matchFound = true; @@ -187,7 +187,7 @@ private bool FindTypeByModulePath(WildcardPattern classNameMatcher) if (classNameMatcher.IsMatch(className)) { var classInfo = CachedItemToPSClassInfo(classNameMatcher, modulePath); - if (classInfo != null) + if (classInfo is not null) { _matchingClassList.Add(classInfo); matchFound = true; @@ -222,7 +222,7 @@ private PSClassInfo CachedItemToPSClassInfo(WildcardPattern classNameMatcher, st if (exportedTypes.TryGetValue(_className, out typeAst)) { ast = typeAst.Parent.Parent as ScriptBlockAst; - if (ast != null) + if (ast is not null) return ConvertToClassInfo(module, ast, typeAst); } } @@ -230,12 +230,12 @@ private PSClassInfo CachedItemToPSClassInfo(WildcardPattern classNameMatcher, st { foreach (var exportedType in exportedTypes) { - if (exportedType.Value != null && + if (exportedType.Value is not null && classNameMatcher.IsMatch(exportedType.Value.Name) && exportedType.Value.IsClass) { ast = exportedType.Value.Parent.Parent as ScriptBlockAst; - if (ast != null) + if (ast is not null) return ConvertToClassInfo(module, ast, exportedType.Value); } } @@ -254,7 +254,7 @@ private Collection GetPSModuleInfo(string modulePath) _moduleInfoCache.TryGetValue(modulePath, out moduleInfo); } - if (moduleInfo != null) + if (moduleInfo is not null) { var returnValue = new Collection(); returnValue.Add(moduleInfo); @@ -291,7 +291,7 @@ private Collection GetPSModuleInfo(string modulePath) private PSClassInfo ConvertToClassInfo(PSModuleInfo module, ScriptBlockAst ast, TypeDefinitionAst statement) { PSClassInfo classInfo = new PSClassInfo(statement.Name); - Dbg.Assert(statement.Name != null, "statement should have a name."); + Dbg.Assert(statement.Name is not null, "statement should have a name."); classInfo.Module = module; Collection properties = new Collection(); @@ -299,11 +299,11 @@ private PSClassInfo ConvertToClassInfo(PSModuleInfo module, ScriptBlockAst ast, { if (member is PropertyMemberAst propAst && !propAst.PropertyAttributes.HasFlag(PropertyAttributes.Hidden)) { - Dbg.Assert(propAst.Name != null, "PropName cannot be null"); - Dbg.Assert(propAst.PropertyType != null, "PropertyType cannot be null"); - Dbg.Assert(propAst.PropertyType.TypeName != null, "Property TypeName cannot be null"); - Dbg.Assert(propAst.Extent != null, "Property Extent cannot be null"); - Dbg.Assert(propAst.Extent.Text != null, "Property ExtentText cannot be null"); + Dbg.Assert(propAst.Name is not null, "PropName cannot be null"); + Dbg.Assert(propAst.PropertyType is not null, "PropertyType cannot be null"); + Dbg.Assert(propAst.PropertyType.TypeName is not null, "Property TypeName cannot be null"); + Dbg.Assert(propAst.Extent is not null, "Property Extent cannot be null"); + Dbg.Assert(propAst.Extent.Text is not null, "Property ExtentText cannot be null"); PSClassMemberInfo classProperty = new PSClassMemberInfo(propAst.Name, propAst.PropertyType.TypeName.FullName, @@ -315,7 +315,7 @@ private PSClassInfo ConvertToClassInfo(PSModuleInfo module, ScriptBlockAst ast, classInfo.UpdateMembers(properties); string mamlHelpFile = null; - if (ast.GetHelpContent() != null) + if (ast.GetHelpContent() is not null) mamlHelpFile = ast.GetHelpContent().MamlHelpFile; if (!string.IsNullOrEmpty(mamlHelpFile)) diff --git a/src/System.Management.Automation/engine/PSConfiguration.cs b/src/System.Management.Automation/engine/PSConfiguration.cs index 8912dd3c3fa..ed737fcb32c 100644 --- a/src/System.Management.Automation/engine/PSConfiguration.cs +++ b/src/System.Management.Automation/engine/PSConfiguration.cs @@ -414,7 +414,7 @@ private T ReadValueFromFile(ConfigScope scope, string key, T defaultValue = d // Set the configuration cache. JObject originalValue = Interlocked.CompareExchange(ref configRoots[(int)scope], configData, null); - if (originalValue != null) + if (originalValue is not null) { configData = originalValue; } diff --git a/src/System.Management.Automation/engine/PSVersionInfo.cs b/src/System.Management.Automation/engine/PSVersionInfo.cs index 3e31e1ac0f9..d46e325d2c2 100644 --- a/src/System.Management.Automation/engine/PSVersionInfo.cs +++ b/src/System.Management.Automation/engine/PSVersionInfo.cs @@ -142,10 +142,10 @@ private static Version GetWSManStackVersion() { using (RegistryKey wsManStackVersionKey = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\WSMAN")) { - if (wsManStackVersionKey != null) + if (wsManStackVersionKey is not null) { object wsManStackVersionObj = wsManStackVersionKey.GetValue("ServiceStackVersion"); - string wsManStackVersion = (wsManStackVersionObj != null) ? (string)wsManStackVersionObj : null; + string wsManStackVersion = (wsManStackVersionObj is not null) ? (string)wsManStackVersionObj : null; if (!string.IsNullOrEmpty(wsManStackVersion)) { version = new Version(wsManStackVersion.Trim()); @@ -571,13 +571,13 @@ public SemanticVersion(Version version) Patch = version.Build == -1 ? 0 : version.Build; var psobj = new PSObject(version); var preLabelNote = psobj.Properties[PreLabelPropertyName]; - if (preLabelNote != null) + if (preLabelNote is not null) { PreReleaseLabel = preLabelNote.Value as string; } var buildLabelNote = psobj.Properties[BuildLabelPropertyName]; - if (buildLabelNote != null) + if (buildLabelNote is not null) { BuildLabel = buildLabelNote.Value as string; } @@ -669,7 +669,7 @@ public static SemanticVersion Parse(string version) /// The return value when the string is a valid public static bool TryParse(string version, out SemanticVersion result) { - if (version != null) + if (version is not null) { var r = new VersionResult(); r.Init(false); @@ -778,8 +778,8 @@ private static bool TryParseVersion(string version, ref VersionResult result) return false; } - if (preLabel != null && !Regex.IsMatch(preLabel, LabelUnitRegEx) || - (buildLabel != null && !Regex.IsMatch(buildLabel, LabelUnitRegEx))) + if (preLabel is not null && !Regex.IsMatch(preLabel, LabelUnitRegEx) || + (buildLabel is not null && !Regex.IsMatch(buildLabel, LabelUnitRegEx))) { result.SetFailure(ParseFailureKind.FormatException); return false; @@ -821,12 +821,12 @@ public override string ToString() /// public static int Compare(SemanticVersion versionA, SemanticVersion versionB) { - if (versionA != null) + if (versionA is not null) { return versionA.CompareTo(versionB); } - if (versionB != null) + if (versionB is not null) { return -1; } @@ -889,7 +889,7 @@ public override bool Equals(object obj) public bool Equals(SemanticVersion other) { // SymVer 2.0 standard requires to ignore 'BuildLabel' (Build metadata). - return other != null && + return other is not null && (Major == other.Major) && (Minor == other.Minor) && (Patch == other.Patch) && string.Equals(PreReleaseLabel, other.PreReleaseLabel, StringComparison.Ordinal); } diff --git a/src/System.Management.Automation/engine/ParameterBinderBase.cs b/src/System.Management.Automation/engine/ParameterBinderBase.cs index 79176966a2c..fcf7c6ff147 100644 --- a/src/System.Management.Automation/engine/ParameterBinderBase.cs +++ b/src/System.Management.Automation/engine/ParameterBinderBase.cs @@ -93,9 +93,9 @@ internal ParameterBinderBase( ExecutionContext context, InternalCommand command) { - Diagnostics.Assert(target != null, "caller to verify target is not null."); - Diagnostics.Assert(invocationInfo != null, "caller to verify invocationInfo is not null."); - Diagnostics.Assert(context != null, "caller to verify context is not null."); + Diagnostics.Assert(target is not null, "caller to verify target is not null."); + Diagnostics.Assert(invocationInfo is not null, "caller to verify invocationInfo is not null."); + Diagnostics.Assert(context is not null, "caller to verify context is not null."); bindingTracer.ShowHeaders = false; @@ -125,8 +125,8 @@ internal ParameterBinderBase( ExecutionContext context, InternalCommand command) { - Diagnostics.Assert(invocationInfo != null, "caller to verify invocationInfo is not null."); - Diagnostics.Assert(context != null, "caller to verify context is not null."); + Diagnostics.Assert(invocationInfo is not null, "caller to verify invocationInfo is not null."); + Diagnostics.Assert(context is not null, "caller to verify context is not null."); bindingTracer.ShowHeaders = false; @@ -150,7 +150,7 @@ internal object Target get { Diagnostics.Assert( - _target != null, + _target is not null, "The target should always be set for the binder"); return _target; @@ -229,8 +229,8 @@ private void ValidatePSTypeName( bool retryOtherBindingAfterFailure, object parameterValue) { - Dbg.Assert(parameter != null, "Caller should verify parameter != null"); - Dbg.Assert(parameterMetadata != null, "Caller should verify parameterMetadata != null"); + Dbg.Assert(parameter is not null, "Caller should verify parameter is not null"); + Dbg.Assert(parameterMetadata is not null, "Caller should verify parameterMetadata is not null"); if (parameterValue is null) { @@ -246,7 +246,7 @@ private void ValidatePSTypeName( PSInvalidCastException e = new PSInvalidCastException(nameof(ErrorCategory.InvalidArgument), null, ParameterBinderStrings.MismatchedPSTypeName, - (_invocationInfo != null) && (_invocationInfo.MyCommand != null) ? _invocationInfo.MyCommand.Name : string.Empty, + (_invocationInfo is not null) && (_invocationInfo.MyCommand is not null) ? _invocationInfo.MyCommand.Name : string.Empty, parameterMetadata.Name, parameterMetadata.Type, parameterValue.GetType(), @@ -361,7 +361,7 @@ internal virtual bool BindParameter( // Now call any argument transformation attributes that might be present on the parameter ScriptParameterBinder spb = this as ScriptParameterBinder; bool usesCmdletBinding = false; - if (spb != null) + if (spb is not null) { usesCmdletBinding = spb.Script.UsesCmdletBinding; } @@ -392,7 +392,7 @@ internal virtual bool BindParameter( { ArgumentTypeConverterAttribute argumentTypeConverter = dma as ArgumentTypeConverterAttribute; - if (argumentTypeConverter != null) + if (argumentTypeConverter is not null) { if (coerceTypeIfNeeded) { @@ -412,7 +412,7 @@ internal virtual bool BindParameter( // 2. If we use script binding (ScriptParameterBinderController is used), then parameters won't have the // ParameterAttribute declared for them, and thus are definitely not mandatory. // So we check 'IsParameterMandatory' only if we are not binding default values. - if ((parameterValue != null) || + if ((parameterValue is not null) || (!isDefaultValue && (parameterMetadata.IsMandatoryInSomeParameterSet || parameterMetadata.CannotBeNull || dma.TransformNullOptionalParameters))) @@ -475,10 +475,10 @@ internal virtual bool BindParameter( } } - if ((parameterMetadata.PSTypeName != null) && (parameterValue != null)) + if ((parameterMetadata.PSTypeName is not null) && (parameterValue is not null)) { IEnumerable parameterValueAsEnumerable = LanguagePrimitives.GetEnumerable(parameterValue); - if (parameterValueAsEnumerable != null) + if (parameterValueAsEnumerable is not null) { foreach (object o in parameterValueAsEnumerable) { @@ -548,9 +548,9 @@ internal virtual bool BindParameter( // 1. We are binding parameters for a simple function/script // 2. We are not binding a default parameter value - if (parameterMetadata.ObsoleteAttribute != null && + if (parameterMetadata.ObsoleteAttribute is not null && (!isDefaultValue) && - spb != null && !usesCmdletBinding) + spb is not null && !usesCmdletBinding) { string obsoleteWarning = string.Format( CultureInfo.InvariantCulture, @@ -559,7 +559,7 @@ internal virtual bool BindParameter( parameterMetadata.ObsoleteAttribute.Message); var mshCommandRuntime = this.Command.commandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) + if (mshCommandRuntime is not null) { // Write out warning only if we are in the context of MshCommandRuntime. // This is because @@ -584,7 +584,7 @@ internal virtual bool BindParameter( bindError = setValueException; } - if (bindError != null) + if (bindError is not null) { Type specifiedType = (parameterValue is null) ? null : parameterValue.GetType(); ParameterBindingException bindingException = @@ -620,16 +620,16 @@ internal virtual bool BindParameter( } MshCommandRuntime cmdRuntime = this.Command.commandRuntime as MshCommandRuntime; - if ((cmdRuntime != null) && + if ((cmdRuntime is not null) && (cmdRuntime.LogPipelineExecutionDetail || _isTranscribing) && - (cmdRuntime.PipelineProcessor != null)) + (cmdRuntime.PipelineProcessor is not null)) { string stringToPrint = null; try { // Unroll parameter value IEnumerable values = LanguagePrimitives.GetEnumerable(parameterValue); - if (values != null) + if (values is not null) { var sb = new Text.StringBuilder(256); var sep = string.Empty; @@ -648,7 +648,7 @@ internal virtual bool BindParameter( stringToPrint = sb.ToString(); } - else if (parameterValue != null) + else if (parameterValue is not null) { stringToPrint = parameterValue.ToString(); } @@ -657,7 +657,7 @@ internal virtual bool BindParameter( { } - if (stringToPrint != null) + if (stringToPrint is not null) { cmdRuntime.PipelineProcessor.LogExecutionParameterBinding(this.InvocationInfo, parameter.ParameterName, stringToPrint); } @@ -722,7 +722,7 @@ private void ValidateNullOrEmptyArgument( // is not null and not empty or that the parameter can accept null or empty. string stringParamValue = parameterValue as string; Diagnostics.Assert( - stringParamValue != null, + stringParamValue is not null, "Type coercion should have already converted the argument value to a string"); if (stringParamValue.Length == 0 && !parameterMetadata.AllowsEmptyStringArgument) @@ -762,13 +762,13 @@ private void ValidateNullOrEmptyArgument( // All these collection types implement IEnumerable IEnumerator ienum = LanguagePrimitives.GetEnumerator(parameterValue); Diagnostics.Assert( - ienum != null, + ienum is not null, "Type coercion should have already converted the argument value to an IEnumerator"); // Ensure that each element abides by the metadata bool isEmpty = true; Type elementType = parameterMetadata.CollectionTypeInformation.ElementType; - bool isElementValueType = elementType != null && elementType.IsValueType; + bool isElementValueType = elementType is not null && elementType.IsValueType; // Note - we explicitly don't pass the context here because we don't want // the overhead of the calls that check for stopping. @@ -852,7 +852,7 @@ private bool ShouldContinueUncoercedBind( } var psobj = parameterValue as PSObject; - if (psobj != null && !psobj.ImmediateBaseObjectIsEmpty) + if (psobj is not null && !psobj.ImmediateBaseObjectIsEmpty) { // See if the base object is of the same type or // as subclass of the parameter @@ -1045,7 +1045,7 @@ private object CoerceTypeAsNeeded( // as is to a PSObject parameter in which case, we want to make // sure that we're using the same shell object instead of creating an // alias object. - if (_command != null && + if (_command is not null && currentValue == _command.CurrentPipelineObject.BaseObject) { currentValue = _command.CurrentPipelineObject; @@ -1187,7 +1187,7 @@ private object CoerceTypeAsNeeded( || collectionTypeInfo.ParameterCollectionType == ParameterCollectionType.IList) { object currentValueToConvert = PSObject.Base(currentValue); - if (currentValueToConvert != null) + if (currentValueToConvert is not null) { ConversionRank rank = LanguagePrimitives.GetConversionRank(currentValueToConvert.GetType(), toType); if (rank == ConversionRank.Constructor || rank == ConversionRank.ImplicitCast || rank == ConversionRank.ExplicitCast) @@ -1214,7 +1214,7 @@ private object CoerceTypeAsNeeded( collectionTypeInfo, toType, currentValue, - (collectionTypeInfo.ElementType != null), + (collectionTypeInfo.ElementType is not null), out ignored); break; @@ -1225,7 +1225,7 @@ private object CoerceTypeAsNeeded( // we don't want to attempt to bind a collection to a scalar unless // the parameter type is Object or PSObject or enum. - if (GetIList(currentValue) != null && + if (GetIList(currentValue) is not null && toType != typeof(object) && toType != typeof(PSObject) && toType != typeof(PSListModifier) && @@ -1322,7 +1322,7 @@ private object CoerceTypeAsNeeded( } } - if (result != null) + if (result is not null) { // Set the converted result object untrusted if necessary ExecutionContext.PropagateInputSource(originalValue, result, Context.LanguageMode); @@ -1490,7 +1490,7 @@ private object EncodeCollection( IList currentValueAsIList = GetIList(currentValue); - if (currentValueAsIList != null) + if (currentValueAsIList is not null) { numberOfElements = currentValueAsIList.Count; @@ -1572,7 +1572,7 @@ private object EncodeCollection( // extract the ICollection::Add(T) method const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance; Type elementType = collectionTypeInformation.ElementType; - Diagnostics.Assert(elementType != null, "null ElementType"); + Diagnostics.Assert(elementType is not null, "null ElementType"); Exception getMethodError = null; try { @@ -1684,7 +1684,7 @@ private object EncodeCollection( // Now that the new collection instance has been created, coerce each element type // of the current value to the element type of the property value and add it - if (currentValueAsIList != null) + if (currentValueAsIList is not null) { // Since arrays don't support the Add method, we must use indexing // to set the value. @@ -1717,7 +1717,7 @@ private object EncodeCollection( null, valueElement); } - else if (collectionElementType != null && currentValueElement != null) + else if (collectionElementType is not null && currentValueElement is not null) { Type currentValueElementType = currentValueElement.GetType(); Type desiredElementType = collectionElementType; @@ -1768,7 +1768,7 @@ private object EncodeCollection( // The inner exception to TargetInvocationException // (if present) has a better Message if (error is TargetInvocationException && - error.InnerException != null) + error.InnerException is not null) { error = error.InnerException; } @@ -1796,7 +1796,7 @@ private object EncodeCollection( "Argument type {0} is not IList, treating this as scalar", currentValue.GetType().Name); - if (collectionElementType != null) + if (collectionElementType is not null) { if (coerceElementTypeIfNeeded) { @@ -1865,7 +1865,7 @@ private object EncodeCollection( // The inner exception to TargetInvocationException // (if present) has a better Message if (error is TargetInvocationException && - error.InnerException != null) + error.InnerException is not null) { error = error.InnerException; } @@ -1903,7 +1903,7 @@ internal static IList GetIList(object value) { var baseObj = PSObject.Base(value); var result = baseObj as IList; - if (result != null) + if (result is not null) { // Reference comparison to determine if 'value' is a PSObject s_tracer.WriteLine(baseObj == value @@ -2014,7 +2014,7 @@ internal void MarkAsBoundPositionally(string name) internal void SetPSBoundParametersVariable(ExecutionContext context) { - Dbg.Assert(context != null, "caller should verify that context != null"); + Dbg.Assert(context is not null, "caller should verify that context is not null"); context.SetVariable(SpecialVariables.PSBoundParametersVarPath, _dictionary); } @@ -2026,7 +2026,7 @@ internal void SetImplicitUsingParameters(object obj) { // Handle downlevel V4 case where using parameters are passed as an array list. IList implicitArrayUsingParameters = PSObject.Base(obj) as IList; - if ((implicitArrayUsingParameters != null) && (implicitArrayUsingParameters.Count > 0)) + if ((implicitArrayUsingParameters is not null) && (implicitArrayUsingParameters.Count > 0)) { // Convert array to hash table. _dictionary.ImplicitUsingParameters = new Hashtable(); @@ -2050,7 +2050,7 @@ internal object GetValueToBindToPSBoundParameters() internal void UpdateInvocationInfo(InvocationInfo invocationInfo) { - Dbg.Assert(invocationInfo != null, "caller should verify that invocationInfo != null"); + Dbg.Assert(invocationInfo is not null, "caller should verify that invocationInfo is not null"); invocationInfo.BoundParameters = _dictionary; } diff --git a/src/System.Management.Automation/engine/ParameterBinderController.cs b/src/System.Management.Automation/engine/ParameterBinderController.cs index d69291bb2ca..92657817df7 100644 --- a/src/System.Management.Automation/engine/ParameterBinderController.cs +++ b/src/System.Management.Automation/engine/ParameterBinderController.cs @@ -35,9 +35,9 @@ internal abstract class ParameterBinderController /// internal ParameterBinderController(InvocationInfo invocationInfo, ExecutionContext context, ParameterBinderBase parameterBinder) { - Diagnostics.Assert(invocationInfo != null, "Caller to verify invocationInfo is not null."); - Diagnostics.Assert(parameterBinder != null, "Caller to verify parameterBinder is not null."); - Diagnostics.Assert(context != null, "call to verify context is not null."); + Diagnostics.Assert(invocationInfo is not null, "Caller to verify invocationInfo is not null."); + Diagnostics.Assert(parameterBinder is not null, "Caller to verify parameterBinder is not null."); + Diagnostics.Assert(context is not null, "call to verify context is not null."); this.DefaultParameterBinder = parameterBinder; Context = context; @@ -200,7 +200,7 @@ internal void ReparseUnboundArguments() true, new InvocationInfo(this.InvocationInfo.MyCommand, nextArgument.ParameterExtent)); - if ((nextMatchingParameter != null) || nextArgument.ParameterAndArgumentSpecified) + if ((nextMatchingParameter is not null) || nextArgument.ParameterAndArgumentSpecified) { // Since the next argument is a valid parameter that means the current // argument doesn't have a value @@ -313,10 +313,10 @@ internal static bool ArgumentLooksLikeParameter(string arg) /// internal static void AddArgumentsToCommandProcessor(CommandProcessorBase commandProcessor, object[] arguments) { - if ((arguments != null) && (arguments.Length > 0)) + if ((arguments is not null) && (arguments.Length > 0)) { PSBoundParametersDictionary boundParameters = arguments[0] as PSBoundParametersDictionary; - if ((boundParameters != null) && (arguments.Length == 1)) + if ((boundParameters is not null) && (arguments.Length == 1)) { // If they are supplying a dictionary of parameters, use those directly foreach (KeyValuePair boundParameter in boundParameters) @@ -410,7 +410,7 @@ internal virtual bool BindParameter( true, new InvocationInfo(this.InvocationInfo.MyCommand, argument.ParameterExtent)); - if (matchingParameter != null) + if (matchingParameter is not null) { // Now check to make sure it hasn't already been // bound by looking in the boundParameters collection @@ -840,7 +840,7 @@ out ParameterBindingException bindingException bindingException = e; } - if (parameterBindingExceptionToThrown != null) + if (parameterBindingExceptionToThrown is not null) { if (!DefaultParameterBindingInUse) { @@ -875,7 +875,7 @@ protected void ThrowElaboratedBindingException(ParameterBindingException pbex) throw PSTraceSource.NewArgumentNullException(nameof(pbex)); } - Diagnostics.Assert(pbex.ErrorRecord != null, "ErrorRecord should not be null in a ParameterBindingException"); + Diagnostics.Assert(pbex.ErrorRecord is not null, "ErrorRecord should not be null in a ParameterBindingException"); // Original error message string oldMsg = pbex.Message; @@ -1125,7 +1125,7 @@ internal void BindUnboundScriptParameterWithDefaultValue(MergedCompiledCommandPa // We may pass a magic parameter from the remote end with the values for the using expressions. // In this case, we want to use those values to evaluate the default value. e.g. param($a = $using:date) System.Collections.IDictionary implicitUsingParameters = null; - if (DefaultParameterBinder.CommandLineParameters != null) + if (DefaultParameterBinder.CommandLineParameters is not null) { implicitUsingParameters = DefaultParameterBinder.CommandLineParameters.GetImplicitUsingParameters(); } diff --git a/src/System.Management.Automation/engine/ParameterInfo.cs b/src/System.Management.Automation/engine/ParameterInfo.cs index 1bb9b875e31..562361aad10 100644 --- a/src/System.Management.Automation/engine/ParameterInfo.cs +++ b/src/System.Management.Automation/engine/ParameterInfo.cs @@ -118,7 +118,7 @@ internal CommandParameterInfo( private void SetAttributes(IList attributeMetadata) { Diagnostics.Assert( - attributeMetadata != null, + attributeMetadata is not null, "The compiled attribute collection should never be null"); Collection processedAttributes = new Collection(); diff --git a/src/System.Management.Automation/engine/ParameterSetInfo.cs b/src/System.Management.Automation/engine/ParameterSetInfo.cs index c328d4f8883..b157acab04c 100644 --- a/src/System.Management.Automation/engine/ParameterSetInfo.cs +++ b/src/System.Management.Automation/engine/ParameterSetInfo.cs @@ -263,7 +263,7 @@ internal static string GetParameterTypeString(Type type, IEnumerable { string parameterTypeString; PSTypeNameAttribute typeName; - if (attributes != null && (typeName = attributes.OfType().FirstOrDefault()) != null) + if (attributes is not null && (typeName = attributes.OfType().FirstOrDefault()) is not null) { // If we have a PSTypeName specified on the class, we assume it has a more useful type than the actual // parameter type. This is a reasonable assumption, the parameter binder does honor this attribute. @@ -314,7 +314,7 @@ internal static string GetParameterTypeString(Type type, IEnumerable private void Initialize(MergedCommandParameterMetadata parameterMetadata, uint parameterSetFlag) { Diagnostics.Assert( - parameterMetadata != null, + parameterMetadata is not null, "The parameterMetadata should never be null"); Collection processedParameters = @@ -326,7 +326,7 @@ private void Initialize(MergedCommandParameterMetadata parameterMetadata, uint p foreach (MergedCompiledCommandParameter parameter in compiledParameters) { - if (parameter != null) + if (parameter is not null) { processedParameters.Add( new CommandParameterInfo(parameter.Parameter, parameterSetFlag)); diff --git a/src/System.Management.Automation/engine/PathInterfaces.cs b/src/System.Management.Automation/engine/PathInterfaces.cs index 4ab103aad70..410f9ec15f0 100644 --- a/src/System.Management.Automation/engine/PathInterfaces.cs +++ b/src/System.Management.Automation/engine/PathInterfaces.cs @@ -61,7 +61,7 @@ public PathInfo CurrentLocation get { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); return _sessionState.CurrentLocation; @@ -86,7 +86,7 @@ public PathInfo CurrentLocation public PathInfo CurrentProviderLocation(string providerName) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -105,7 +105,7 @@ public PathInfo CurrentFileSystemLocation get { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); return CurrentProviderLocation(_sessionState.ExecutionContext.ProviderNames.FileSystem); @@ -142,7 +142,7 @@ public PathInfo CurrentFileSystemLocation public PathInfo SetLocation(string path) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -183,7 +183,7 @@ public PathInfo SetLocation(string path) internal PathInfo SetLocation(string path, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -227,7 +227,7 @@ internal PathInfo SetLocation(string path, CmdletProviderContext context) internal PathInfo SetLocation(string path, CmdletProviderContext context, bool literalPath) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -276,7 +276,7 @@ internal PathInfo SetLocation(string path, CmdletProviderContext context, bool l internal bool IsCurrentLocationOrAncestor(string path, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -293,7 +293,7 @@ internal bool IsCurrentLocationOrAncestor(string path, CmdletProviderContext con public void PushCurrentLocation(string stackName) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); _sessionState.PushCurrentLocation(stackName); @@ -331,7 +331,7 @@ public void PushCurrentLocation(string stackName) public PathInfo PopLocation(string stackName) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); return _sessionState.PopLocation(stackName); @@ -346,7 +346,7 @@ public PathInfo PopLocation(string stackName) public PathInfoStack LocationStack(string stackName) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); return _sessionState.LocationStack(stackName); @@ -364,7 +364,7 @@ public PathInfoStack LocationStack(string stackName) public PathInfoStack SetDefaultLocationStack(string stackName) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); return _sessionState.SetDefaultLocationStack(stackName); @@ -918,7 +918,7 @@ public bool IsPSAbsolute(string path, out string driveName) public string Combine(string parent, string child) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -960,7 +960,7 @@ public string Combine(string parent, string child) internal string Combine(string parent, string child, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -999,7 +999,7 @@ internal string Combine(string parent, string child, CmdletProviderContext conte public string ParseParent(string path, string root) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1040,7 +1040,7 @@ internal string ParseParent( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1087,7 +1087,7 @@ internal string ParseParent( bool useDefaultProvider) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1127,7 +1127,7 @@ internal string ParseParent( public string ParseChildName(string path) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1168,7 +1168,7 @@ internal string ParseChildName( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1215,7 +1215,7 @@ internal string ParseChildName( bool useDefaultProvider) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1256,7 +1256,7 @@ internal string ParseChildName( public string NormalizeRelativePath(string path, string basePath) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1299,7 +1299,7 @@ internal string NormalizeRelativePath( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1339,7 +1339,7 @@ internal string NormalizeRelativePath( public bool IsValid(string path) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1380,7 +1380,7 @@ internal bool IsValid( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1399,7 +1399,7 @@ private LocationGlobber PathResolver get { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); return _pathResolver ?? (_pathResolver = _sessionState.ExecutionContext.LocationGlobber); diff --git a/src/System.Management.Automation/engine/Pipe.cs b/src/System.Management.Automation/engine/Pipe.cs index a82c8bc090d..dfce69d6176 100644 --- a/src/System.Management.Automation/engine/Pipe.cs +++ b/src/System.Management.Automation/engine/Pipe.cs @@ -93,7 +93,7 @@ internal PipelineWriter ExternalWriter /// public override string ToString() { - if (_downstreamCmdlet != null) + if (_downstreamCmdlet is not null) return _downstreamCmdlet.ToString(); return base.ToString(); } @@ -136,10 +136,10 @@ internal bool Empty { get { - if (_enumeratorToProcess != null) + if (_enumeratorToProcess is not null) return _enumeratorToProcessIsEmpty; - if (ObjectQueue != null) + if (ObjectQueue is not null) return ObjectQueue.Count == 0; return true; } @@ -151,7 +151,7 @@ internal bool Empty /// internal bool IsRedirected { - get { return _downstreamCmdlet != null || _isRedirected; } + get { return _downstreamCmdlet is not null || _isRedirected; } } private bool _isRedirected; @@ -184,7 +184,7 @@ internal bool IsRedirected private static void AddToVarList(List varList, object obj) { - if (varList != null && varList.Count > 0) + if (varList is not null && varList.Count > 0) { for (int i = 0; i < varList.Count; i++) { @@ -277,7 +277,7 @@ internal void RemoveVariableList(VariableStreamKind kind, IList list) internal void RemovePipelineVariable() { - if (_pipelineVariableObject != null) + if (_pipelineVariableObject is not null) { _pipelineVariableObject.Value = null; _pipelineVariableObject = null; @@ -301,7 +301,7 @@ internal void SetVariableListForTemporaryPipe(Pipe tempPipe) private void CopyVariableToTempPipe(VariableStreamKind streamKind, List variableList, Pipe tempPipe) { - if (variableList != null && variableList.Count > 0) + if (variableList is not null && variableList.Count > 0) { for (int i = 0; i < variableList.Count; i++) { @@ -329,7 +329,7 @@ internal Pipe() /// internal Pipe(List resultList) { - Diagnostics.Assert(resultList != null, "resultList cannot be null"); + Diagnostics.Assert(resultList is not null, "resultList cannot be null"); _isRedirected = true; _resultList = resultList; } @@ -344,7 +344,7 @@ internal Pipe(List resultList) /// The collection to write into. internal Pipe(System.Collections.ObjectModel.Collection resultCollection) { - Diagnostics.Assert(resultCollection != null, "resultCollection cannot be null"); + Diagnostics.Assert(resultCollection is not null, "resultCollection cannot be null"); _isRedirected = true; _resultCollection = resultCollection; } @@ -359,8 +359,8 @@ internal Pipe(System.Collections.ObjectModel.Collection resultCollecti /// The pipeline to write into... internal Pipe(ExecutionContext context, PipelineProcessor outputPipeline) { - Diagnostics.Assert(outputPipeline != null, "outputPipeline cannot be null"); - Diagnostics.Assert(outputPipeline != null, "context cannot be null"); + Diagnostics.Assert(outputPipeline is not null, "outputPipeline cannot be null"); + Diagnostics.Assert(outputPipeline is not null, "context cannot be null"); _isRedirected = true; _context = context; PipelineProcessor = outputPipeline; @@ -372,7 +372,7 @@ internal Pipe(ExecutionContext context, PipelineProcessor outputPipeline) /// The enumerator to process... internal Pipe(IEnumerator enumeratorToProcess) { - Diagnostics.Assert(enumeratorToProcess != null, "enumeratorToProcess cannot be null"); + Diagnostics.Assert(enumeratorToProcess is not null, "enumeratorToProcess cannot be null"); _enumeratorToProcess = enumeratorToProcess; // since there is an enumerator specified, we @@ -412,7 +412,7 @@ internal void Add(object obj) return; // Store the current pipeline variable - if (_pipelineVariableObject != null) + if (_pipelineVariableObject is not null) { _pipelineVariableObject.Value = obj; } @@ -430,31 +430,31 @@ internal void AddWithoutAppendingOutVarList(object obj) private void AddToPipe(object obj) { - if (PipelineProcessor != null) + if (PipelineProcessor is not null) { // Put the pipeline on the notification stack for stop. _context.PushPipelineProcessor(PipelineProcessor); PipelineProcessor.Step(obj); _context.PopPipelineProcessor(false); } - else if (_resultCollection != null) + else if (_resultCollection is not null) { - _resultCollection.Add(obj != null ? PSObject.AsPSObject(obj) : null); + _resultCollection.Add(obj is not null ? PSObject.AsPSObject(obj) : null); } - else if (_resultList != null) + else if (_resultList is not null) { _resultList.Add(obj); } - else if (_externalWriter != null) + else if (_externalWriter is not null) { _externalWriter.Write(obj); } - else if (ObjectQueue != null) + else if (ObjectQueue is not null) { ObjectQueue.Enqueue(obj); // This is the "streamlet" recursive call - if (_downstreamCmdlet != null && ObjectQueue.Count > OutBufferCount) + if (_downstreamCmdlet is not null && ObjectQueue.Count > OutBufferCount) { _downstreamCmdlet.DoExecute(); } @@ -510,18 +510,18 @@ internal void AddItems(object objects) // If our object came from GetEnumerator (and hence is not IEnumerator), then we need to dispose // Otherwise, we don't own the object, so don't dispose. var disposable = ie as IDisposable; - if (disposable != null && !(objects is IEnumerator)) + if (disposable is not null && !(objects is IEnumerator)) { disposable.Dispose(); } } - if (_externalWriter != null) + if (_externalWriter is not null) return; // If there are objects waiting for the downstream command // call it now - if (_downstreamCmdlet != null && ObjectQueue != null && ObjectQueue.Count > OutBufferCount) + if (_downstreamCmdlet is not null && ObjectQueue is not null && ObjectQueue.Count > OutBufferCount) { _downstreamCmdlet.DoExecute(); } @@ -536,11 +536,11 @@ internal void AddItems(object objects) /// internal object Retrieve() { - if (ObjectQueue != null && ObjectQueue.Count != 0) + if (ObjectQueue is not null && ObjectQueue.Count != 0) { return ObjectQueue.Dequeue(); } - else if (_enumeratorToProcess != null) + else if (_enumeratorToProcess is not null) { if (_enumeratorToProcessIsEmpty) return AutomationNull.Value; @@ -553,7 +553,7 @@ internal object Retrieve() return ParserOps.Current(null, _enumeratorToProcess); } - else if (ExternalReader != null) + else if (ExternalReader is not null) { try { @@ -588,7 +588,7 @@ internal object Retrieve() /// internal void Clear() { - if (ObjectQueue != null) + if (ObjectQueue is not null) ObjectQueue.Clear(); } diff --git a/src/System.Management.Automation/engine/ProcessCodeMethods.cs b/src/System.Management.Automation/engine/ProcessCodeMethods.cs index 604ac3787ad..9f98054a14f 100644 --- a/src/System.Management.Automation/engine/ProcessCodeMethods.cs +++ b/src/System.Management.Automation/engine/ProcessCodeMethods.cs @@ -60,7 +60,7 @@ internal static int GetParentPid(Process process) #else internal static int GetParentPid(Process process) { - Diagnostics.Assert(process != null, "Ensure process is not null before calling"); + Diagnostics.Assert(process is not null, "Ensure process is not null before calling"); PROCESS_BASIC_INFORMATION pbi; int size; var res = NtQueryInformationProcess(process.Handle, 0, out pbi, Marshal.SizeOf(), out size); diff --git a/src/System.Management.Automation/engine/PropertyCmdletProviderInterfaces.cs b/src/System.Management.Automation/engine/PropertyCmdletProviderInterfaces.cs index 469b70aaede..9627405aa8a 100644 --- a/src/System.Management.Automation/engine/PropertyCmdletProviderInterfaces.cs +++ b/src/System.Management.Automation/engine/PropertyCmdletProviderInterfaces.cs @@ -109,7 +109,7 @@ public Collection Get( Collection providerSpecificPickList) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -160,7 +160,7 @@ public Collection Get( bool literalPath) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -212,7 +212,7 @@ internal void Get( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -260,7 +260,7 @@ internal object GetPropertyDynamicParameters( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -309,7 +309,7 @@ public Collection Set( PSObject propertyValue) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -362,7 +362,7 @@ public Collection Set( bool literalPath) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -411,7 +411,7 @@ internal void Set( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -458,7 +458,7 @@ internal object SetPropertyDynamicParameters( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -504,7 +504,7 @@ public void Clear( Collection propertyToClear) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -554,7 +554,7 @@ public void Clear( bool literalPath) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -600,7 +600,7 @@ internal void Clear( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -647,7 +647,7 @@ internal object ClearPropertyDynamicParameters( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -705,7 +705,7 @@ public Collection New( object value) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -767,7 +767,7 @@ public Collection New( bool literalPath) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -826,7 +826,7 @@ internal void New( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -881,7 +881,7 @@ internal object NewPropertyDynamicParameters( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -925,7 +925,7 @@ internal object NewPropertyDynamicParameters( public void Remove(string path, string propertyName) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -971,7 +971,7 @@ public void Remove(string path, string propertyName) public void Remove(string[] path, string propertyName, bool force, bool literalPath) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1017,7 +1017,7 @@ internal void Remove( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1064,7 +1064,7 @@ internal object RemovePropertyDynamicParameters( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1118,7 +1118,7 @@ public Collection Rename( string destinationProperty) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1176,7 +1176,7 @@ public Collection Rename( bool literalPath) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1231,7 +1231,7 @@ internal void Rename( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1282,7 +1282,7 @@ internal object RenamePropertyDynamicParameters( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1342,7 +1342,7 @@ public Collection Copy( string destinationProperty) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1412,7 +1412,7 @@ public Collection Copy( bool literalPath) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1480,7 +1480,7 @@ internal void Copy( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1541,7 +1541,7 @@ internal object CopyPropertyDynamicParameters( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1604,7 +1604,7 @@ public Collection Move( string destinationProperty) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1678,7 +1678,7 @@ public Collection Move( bool literalPath) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1749,7 +1749,7 @@ internal void Move( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -1810,7 +1810,7 @@ internal object MovePropertyDynamicParameters( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object diff --git a/src/System.Management.Automation/engine/ProviderInterfaces.cs b/src/System.Management.Automation/engine/ProviderInterfaces.cs index c03b30fcc83..356af98e34b 100644 --- a/src/System.Management.Automation/engine/ProviderInterfaces.cs +++ b/src/System.Management.Automation/engine/ProviderInterfaces.cs @@ -69,7 +69,7 @@ internal CmdletProviderManagementIntrinsics(SessionStateInternal sessionState) public Collection Get(string name) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -100,7 +100,7 @@ public Collection Get(string name) public ProviderInfo GetOne(string name) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -114,7 +114,7 @@ public ProviderInfo GetOne(string name) public IEnumerable GetAll() { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); return _sessionState.ProviderList; diff --git a/src/System.Management.Automation/engine/ProxyCommand.cs b/src/System.Management.Automation/engine/ProxyCommand.cs index 55ce7c64bfc..5d080c8bce5 100644 --- a/src/System.Management.Automation/engine/ProxyCommand.cs +++ b/src/System.Management.Automation/engine/ProxyCommand.cs @@ -250,7 +250,7 @@ public static string GetEnd(CommandMetadata commandMetadata) private static T GetProperty(PSObject obj, string property) where T : class { T result = null; - if (obj != null && obj.Properties[property] != null) + if (obj is not null && obj.Properties[property] is not null) { result = obj.Properties[property].Value as T; } @@ -263,7 +263,7 @@ private static string GetObjText(object obj) string text = null; PSObject psobj = obj as PSObject; - if (psobj != null) + if (psobj is not null) { text = GetProperty(psobj, "Text"); } @@ -273,7 +273,7 @@ private static string GetObjText(object obj) private static void AppendContent(StringBuilder sb, string section, object obj) { - if (obj != null) + if (obj is not null) { string text = GetObjText(obj); if (!string.IsNullOrEmpty(text)) @@ -289,7 +289,7 @@ private static void AppendContent(StringBuilder sb, string section, object obj) private static void AppendContent(StringBuilder sb, string section, PSObject[] array) { - if (array != null) + if (array is not null) { bool first = true; foreach (PSObject obj in array) @@ -321,7 +321,7 @@ private static void AppendType(StringBuilder sb, string section, PSObject parent { PSObject type = GetProperty(parent, "type"); PSObject name = GetProperty(type, "name"); - if (name != null) + if (name is not null) { sb.Append("\n\n"); sb.Append(section); @@ -332,7 +332,7 @@ private static void AppendType(StringBuilder sb, string section, PSObject parent else { PSObject uri = GetProperty(type, "uri"); - if (uri != null) + if (uri is not null) { sb.Append("\n\n"); sb.Append(section); @@ -380,7 +380,7 @@ public static string GetHelpComments(PSObject help) PSObject parameters = GetProperty(help, "Parameters"); PSObject[] parameter = GetProperty(parameters, "Parameter"); - if (parameter != null) + if (parameter is not null) { foreach (PSObject param in parameter) { @@ -403,18 +403,18 @@ public static string GetHelpComments(PSObject help) PSObject examples = GetProperty(help, "examples"); PSObject[] example = GetProperty(examples, "example"); - if (example != null) + if (example is not null) { foreach (PSObject ex in example) { StringBuilder exsb = new StringBuilder(); PSObject[] introduction = GetProperty(ex, "introduction"); - if (introduction != null) + if (introduction is not null) { foreach (PSObject intro in introduction) { - if (intro != null) + if (intro is not null) { exsb.Append(GetObjText(intro)); } @@ -422,13 +422,13 @@ public static string GetHelpComments(PSObject help) } PSObject code = GetProperty(ex, "code"); - if (code != null) + if (code is not null) { exsb.Append(code.ToString()); } PSObject[] remarks = GetProperty(ex, "remarks"); - if (remarks != null) + if (remarks is not null) { exsb.Append("\n"); foreach (PSObject remark in remarks) @@ -459,7 +459,7 @@ public static string GetHelpComments(PSObject help) PSObject relatedLinks = GetProperty(help, "relatedLinks"); PSObject[] navigationLink = GetProperty(relatedLinks, "navigationLink"); - if (navigationLink != null) + if (navigationLink is not null) { foreach (PSObject link in navigationLink) { diff --git a/src/System.Management.Automation/engine/PseudoParameterBinder.cs b/src/System.Management.Automation/engine/PseudoParameterBinder.cs index ab74c899e60..ad4e28e6726 100644 --- a/src/System.Management.Automation/engine/PseudoParameterBinder.cs +++ b/src/System.Management.Automation/engine/PseudoParameterBinder.cs @@ -94,7 +94,7 @@ internal override object GetDefaultParameterValue(string name) { object result = null; RuntimeDefinedParameter parameter; - if (this.Target.TryGetValue(name, out parameter) && parameter != null) + if (this.Target.TryGetValue(name, out parameter) && parameter is not null) { result = parameter.Value; } diff --git a/src/System.Management.Automation/engine/PseudoParameters.cs b/src/System.Management.Automation/engine/PseudoParameters.cs index bb9ff5d4a3e..373090687dc 100644 --- a/src/System.Management.Automation/engine/PseudoParameters.cs +++ b/src/System.Management.Automation/engine/PseudoParameters.cs @@ -64,7 +64,7 @@ public RuntimeDefinedParameter(string name, Type parameterType, Collection protected void CommonInitialization(ScriptBlock scriptBlock, ExecutionContext context, bool useLocalScope, CommandOrigin origin, SessionStateInternal sessionState) { - Diagnostics.Assert(context != null, "execution context cannot be null"); - Diagnostics.Assert(context.Engine != null, "context.engine cannot be null"); + Diagnostics.Assert(context is not null, "execution context cannot be null"); + Diagnostics.Assert(context.Engine is not null, "context.engine cannot be null"); this.CommandSessionState = sessionState; this._context = context; @@ -134,11 +134,11 @@ protected void CommonInitialization(ScriptBlock scriptBlock, ExecutionContext co /// true if user requested help; false otherwise. internal override bool IsHelpRequested(out string helpTarget, out HelpCategory helpCategory) { - if (arguments != null && CommandInfo != null && !string.IsNullOrEmpty(CommandInfo.Name) && _scriptBlock != null) + if (arguments is not null && CommandInfo is not null && !string.IsNullOrEmpty(CommandInfo.Name) && _scriptBlock is not null) { foreach (CommandParameterInternal parameter in this.arguments) { - Dbg.Assert(parameter != null, "CommandProcessor.arguments shouldn't have any null arguments"); + Dbg.Assert(parameter is not null, "CommandProcessor.arguments shouldn't have any null arguments"); if (parameter.IsDashQuestion()) { Dictionary scriptBlockTokenCache = new Dictionary(); @@ -380,7 +380,7 @@ internal override void ProcessRecord() else if (IsPipelineInputExpected()) { // 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 + Debug.Assert(this.Command.MyInvocation.PipelineIterationInfo is not null); // this should have been allocated when the pipe was started if (this.CommandRuntime.InputPipe.ExternalReader is null) { while (Read()) @@ -440,7 +440,7 @@ internal override void Complete() private void DoProcessRecordWithInput() { // block for input and execute "process" block for all input objects - Debug.Assert(this.Command.MyInvocation.PipelineIterationInfo != null); // this should have been allocated when the pipe was started + Debug.Assert(this.Command.MyInvocation.PipelineIterationInfo is not null); // this should have been allocated when the pipe was started var processBlock = _runOptimizedCode ? _scriptBlock.ProcessBlock : _scriptBlock.UnoptimizedProcessBlock; while (Read()) { @@ -536,7 +536,7 @@ private void RunClause(Action clause, object dollarUnderbar, ob else { IList list = inputToProcess as IList; - inputToProcess = (list != null) + inputToProcess = (list is not null) ? list.GetEnumerator() : LanguagePrimitives.GetEnumerator(inputToProcess); } diff --git a/src/System.Management.Automation/engine/SecurityDescriptorCmdletProviderInterfaces.cs b/src/System.Management.Automation/engine/SecurityDescriptorCmdletProviderInterfaces.cs index 6c0e6279b86..d7483100359 100644 --- a/src/System.Management.Automation/engine/SecurityDescriptorCmdletProviderInterfaces.cs +++ b/src/System.Management.Automation/engine/SecurityDescriptorCmdletProviderInterfaces.cs @@ -83,7 +83,7 @@ internal SecurityDescriptorCmdletProviderIntrinsics(SessionStateInternal session public Collection Get(string path, AccessControlSections includeSections) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -112,7 +112,7 @@ internal void Get(string path, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -139,7 +139,7 @@ internal void Get(string path, public Collection Set(string path, ObjectSecurity sd) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -167,7 +167,7 @@ public Collection Set(string path, ObjectSecurity sd) internal void Set(string path, ObjectSecurity sd, CmdletProviderContext context) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -196,7 +196,7 @@ internal void Set(string path, ObjectSecurity sd, CmdletProviderContext context) public ObjectSecurity NewFromPath(string path, AccessControlSections includeSections) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -223,7 +223,7 @@ public ObjectSecurity NewFromPath(string path, AccessControlSections includeSect public ObjectSecurity NewOfType(string providerId, string type, AccessControlSections includeSections) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object diff --git a/src/System.Management.Automation/engine/SecurityManagerBase.cs b/src/System.Management.Automation/engine/SecurityManagerBase.cs index 3cb4c9e7a70..b631b945ae9 100644 --- a/src/System.Management.Automation/engine/SecurityManagerBase.cs +++ b/src/System.Management.Automation/engine/SecurityManagerBase.cs @@ -89,7 +89,7 @@ internal void ShouldRunInternal(CommandInfo commandInfo, // If we are debugging, let the unit tests swap the file from beneath us if (commandInfo.CommandType == CommandTypes.ExternalScript) { - while (Environment.GetEnvironmentVariable("PSCommandDiscoveryPreDelay") != null) { System.Threading.Thread.Sleep(100); } + while (Environment.GetEnvironmentVariable("PSCommandDiscoveryPreDelay") is not null) { System.Threading.Thread.Sleep(100); } } #endif @@ -108,7 +108,7 @@ internal void ShouldRunInternal(CommandInfo commandInfo, // If we are debugging, let the unit tests swap the file from beneath us if (commandInfo.CommandType == CommandTypes.ExternalScript) { - while (Environment.GetEnvironmentVariable("PSCommandDiscoveryPostDelay") != null) { System.Threading.Thread.Sleep(100); } + while (Environment.GetEnvironmentVariable("PSCommandDiscoveryPostDelay") is not null) { System.Threading.Thread.Sleep(100); } } #endif } @@ -122,7 +122,7 @@ internal void ShouldRunInternal(CommandInfo commandInfo, if (!result) { - if (authorizationManagerException != null) + if (authorizationManagerException is not null) { if (authorizationManagerException is PSSecurityException) { @@ -171,7 +171,7 @@ protected internal virtual bool ShouldRun(CommandInfo commandInfo, PSHost host, out Exception reason) { - Dbg.Diagnostics.Assert(commandInfo != null, "caller should validate the parameter"); + Dbg.Diagnostics.Assert(commandInfo is not null, "caller should validate the parameter"); reason = null; diff --git a/src/System.Management.Automation/engine/SessionState.cs b/src/System.Management.Automation/engine/SessionState.cs index af3886ba708..31dd7998a64 100644 --- a/src/System.Management.Automation/engine/SessionState.cs +++ b/src/System.Management.Automation/engine/SessionState.cs @@ -81,7 +81,7 @@ internal SessionStateInternal(SessionStateInternal parent, bool linkToGlobal, Ex // that uses variables qualified by script: it works. GlobalScope.ScriptScope = GlobalScope; - if (parent != null) + if (parent is not null) { GlobalScope.Parent = parent.GlobalScope; @@ -89,7 +89,7 @@ internal SessionStateInternal(SessionStateInternal parent, bool linkToGlobal, Ex CopyProviders(parent); // During loading of core modules, providers are not populated. // We set the drive information later - if (Providers != null && Providers.Count > 0) + if (Providers is not null && Providers.Count > 0) { CurrentDrive = parent.CurrentDrive; } @@ -522,7 +522,7 @@ internal ProviderInvocationException NewProviderInvocationException( // ProviderInvocationException, and we don't want to // re-wrap it. ProviderInvocationException pie = e as ProviderInvocationException; - if (pie != null) + if (pie is not null) { pie._providerInfo = provider; return pie; diff --git a/src/System.Management.Automation/engine/SessionStateAliasAPIs.cs b/src/System.Management.Automation/engine/SessionStateAliasAPIs.cs index 7d6e9b9137a..f88c52683d2 100644 --- a/src/System.Management.Automation/engine/SessionStateAliasAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateAliasAPIs.cs @@ -144,7 +144,7 @@ internal AliasInfo GetAlias(string aliasName, CommandOrigin origin) { result = scope.GetAlias(aliasName); - if (result != null) + if (result is not null) { // Now check the visibility of the variable... SessionState.ThrowIfNotVisible(origin, result); @@ -217,7 +217,7 @@ internal AliasInfo GetAliasAtScope(string aliasName, string scopeID) // Make sure the alias isn't private or if it is that the current // scope is the same scope the alias was retrieved from. - if (result != null && + if (result is not null && (result.Options & ScopedItemOptions.Private) != 0 && scope != _currentScope) { @@ -539,7 +539,7 @@ internal void RemoveAlias(string aliasName, bool force) AliasInfo alias = scope.GetAlias(aliasName); - if (alias != null) + if (alias is not null) { // Make sure the alias isn't private or if it is that the current // scope is the same scope the alias was retrieved from. diff --git a/src/System.Management.Automation/engine/SessionStateCmdletAPIs.cs b/src/System.Management.Automation/engine/SessionStateCmdletAPIs.cs index 9e50b4e0a6a..41b5ca7e53d 100644 --- a/src/System.Management.Automation/engine/SessionStateCmdletAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateCmdletAPIs.cs @@ -58,7 +58,7 @@ internal CmdletInfo GetCmdlet(string cmdletName, CommandOrigin origin) { result = scope.GetCmdlet(cmdletName); - if (result != null) + if (result is not null) { // Now check the visibility of the cmdlet... SessionState.ThrowIfNotVisible(origin, result); @@ -117,7 +117,7 @@ internal CmdletInfo GetCmdletAtScope(string cmdletName, string scopeID) // Make sure the alias isn't private or if it is that the current // scope is the same scope the alias was retrieved from. - if (result != null && + if (result is not null && (result.Options & ScopedItemOptions.Private) != 0 && scope != _currentScope) { @@ -251,7 +251,7 @@ internal void RemoveCmdlet(string name, int index, bool force, CommandOrigin ori CmdletInfo cmdletInfo = scope.GetCmdlet(name); - if (cmdletInfo != null) + if (cmdletInfo is not null) { // Make sure the cmdlet isn't private or if it is that the current // scope is the same scope the cmdlet was retrieved from. @@ -302,7 +302,7 @@ internal void RemoveCmdletEntry(string name, bool force) CmdletInfo cmdletInfo = scope.GetCmdlet(name); - if (cmdletInfo != null) + if (cmdletInfo is not null) { // Make sure the cmdlet isn't private or if it is that the current // scope is the same scope the cmdlet was retrieved from. diff --git a/src/System.Management.Automation/engine/SessionStateContainer.cs b/src/System.Management.Automation/engine/SessionStateContainer.cs index cd1c72257c7..ae905f54532 100644 --- a/src/System.Management.Automation/engine/SessionStateContainer.cs +++ b/src/System.Management.Automation/engine/SessionStateContainer.cs @@ -170,15 +170,15 @@ internal bool ItemExists( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerId before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); ItemCmdletProvider itemCmdletProvider = @@ -315,15 +315,15 @@ private object ItemExistsDynamicParameters( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); ContainerCmdletProvider containerCmdletProvider = @@ -484,15 +484,15 @@ private bool IsValidPath( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); ItemCmdletProvider itemCmdletProvider = @@ -670,15 +670,15 @@ private bool IsItemContainer( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); bool result = false; @@ -904,15 +904,15 @@ internal void RemoveItem( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerId != null, + providerId is not null, "Caller should validate providerId before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); CmdletProvider providerInstance = GetProviderInstance(providerId); @@ -955,15 +955,15 @@ internal void RemoveItem( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); ContainerCmdletProvider containerCmdletProvider = @@ -1148,15 +1148,15 @@ private object RemoveItemDynamicParameters( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); ContainerCmdletProvider containerCmdletProvider = @@ -1357,7 +1357,7 @@ internal void GetChildItems( { if (!string.Equals(childName, "*", StringComparison.OrdinalIgnoreCase)) { - if (context.Include != null) + if (context.Include is not null) { context.Include.Add(childName); modifiedInclude = true; @@ -1420,9 +1420,9 @@ internal void GetChildItems( // To fix this Perf regression, using getChildrenBecauseNoGlob (+recurse) variables // to decide when to use ManualGetChildItems and when not to. if ( - (recurse && !getChildrenBecauseNoGlob && (include != null) && (include.Count == 0)) || - (include != null && include.Count > 0) || - (exclude != null && exclude.Count > 0)) + (recurse && !getChildrenBecauseNoGlob && (include is not null) && (include.Count == 0)) || + (include is not null && include.Count > 0) || + (exclude is not null && exclude.Count > 0)) { // Do the recursion manually so that we can apply the // include and exclude filters @@ -1483,7 +1483,7 @@ internal void GetChildItems( out provider, out drive); - if (drive != null) + if (drive is not null) { context.Drive = drive; } @@ -1491,8 +1491,8 @@ internal void GetChildItems( ContainerCmdletProvider providerInstance = GetContainerProviderInstance(provider); if ( - (context.Include != null && context.Include.Count > 0) || - (context.Exclude != null && context.Exclude.Count > 0)) + (context.Include is not null && context.Include.Count > 0) || + (context.Exclude is not null && context.Exclude.Count > 0)) { // Do the recursion manually so that we can apply the // include and exclude filters @@ -1508,7 +1508,7 @@ internal void GetChildItems( context.SuppressWildcardExpansion = true; } } - else if (path != null && this.ItemExists(providerInstance, path, context)) + else if (path is not null && this.ItemExists(providerInstance, path, context)) { if (IsItemContainer(providerInstance, path, context)) { @@ -1567,15 +1567,15 @@ private void GetChildItems( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); ContainerCmdletProvider containerCmdletProvider = @@ -1637,7 +1637,7 @@ private bool IsPathContainer( catch (ProviderInvocationException accessException) { // if providerinvocationexception is wrapping access denied error, it is ok to not terminate the pipeline - if (accessException.InnerException != null && + if (accessException.InnerException is not null && accessException.InnerException.GetType().Equals(typeof(System.UnauthorizedAccessException))) { context.WriteError(new ErrorRecord(accessException, "GetItemUnauthorizedAccessError", ErrorCategory.PermissionDenied, path)); @@ -1753,15 +1753,15 @@ private void ProcessPathItems( childrenNotMatchingFilterCriteria = 0; Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "The caller should have verified the providerInstance"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "The caller should have verified the path"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "The caller should have verified the context"); // Construct the include filter @@ -1819,7 +1819,7 @@ private void ProcessPathItems( foreach (PSObject filteredChildName in filteredChildNameObjects) { string filteredName = filteredChildName.BaseObject as string; - if (filteredName != null) + if (filteredName is not null) { filteredChildNameDictionary[filteredName] = true; } @@ -1871,7 +1871,7 @@ private void ProcessPathItems( false)) { bool emitItem = true; - if (filteredChildNameDictionary != null) + if (filteredChildNameDictionary is not null) { bool isChildNameInDictionary = false; emitItem = filteredChildNameDictionary.TryGetValue(childName, out isChildNameInDictionary); @@ -2038,21 +2038,21 @@ internal object GetChildItemsDynamicParameters( } } - if (providerPaths != null && providerPaths.Count > 0) + if (providerPaths is not null && providerPaths.Count > 0) { // Get the dynamic parameters for the first resolved path return GetChildItemsDynamicParameters(providerInstance, providerPaths[0], recurse, newContext); } else { - if (providerInstance != null) + if (providerInstance is not null) { PSDriveInfo drive = null; // If we get here, the GetProviderPath should always succeed. This method was already invoked // in the call to GetGlobbedProviderPathsFromMonadPath, and since "providerInstance" is not null, // the invocation in method GetGlobbedProviderPathsFromMonadPath should succeed. string providerPath = Globber.GetProviderPath(path, context, out provider, out drive); - if (providerPath != null) + if (providerPath is not null) { return GetChildItemsDynamicParameters(providerInstance, providerPath, recurse, newContext); } @@ -2076,11 +2076,11 @@ private bool HasGetChildItemDynamicParameters(ProviderInfo providerInfo) providerType = providerType.BaseType; } while ( (mi is null) && - (providerType != null) && + (providerType is not null) && (providerType != typeof(ContainerCmdletProvider)) ); - return (mi != null); + return (mi is not null); } /// @@ -2119,15 +2119,15 @@ private object GetChildItemsDynamicParameters( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); ContainerCmdletProvider containerCmdletProvider = @@ -2363,7 +2363,7 @@ internal void GetChildNames( out provider, out providerInstance); - if (resolvePathContext.Drive != null) + if (resolvePathContext.Drive is not null) { context.Drive = resolvePathContext.Drive; } @@ -2448,7 +2448,7 @@ internal void GetChildNames( ContainerCmdletProvider providerInstance = GetContainerProviderInstance(provider); - if (drive != null) + if (drive is not null) { context.Drive = drive; } @@ -2547,15 +2547,15 @@ private void DoGetChildNamesManually( uint depth) { Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "The providerInstance should have been verified by the caller"); Dbg.Diagnostics.Assert( - providerPath != null, + providerPath is not null, "The paths should have been verified by the caller"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "The context should have been verified by the caller"); string newProviderPath = @@ -2723,15 +2723,15 @@ private void GetChildNames( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); ContainerCmdletProvider containerCmdletProvider = @@ -2838,21 +2838,21 @@ internal object GetChildNamesDynamicParameters( } object result = null; - if (providerPaths != null && providerPaths.Count > 0) + if (providerPaths is not null && providerPaths.Count > 0) { // Get the dynamic parameters for the first resolved path result = GetChildNamesDynamicParameters(providerInstance, providerPaths[0], newContext); } else { - if (providerInstance != null) + if (providerInstance is not null) { PSDriveInfo drive = null; // If we get here, the GetProviderPath should always succeed. This method was already invoked // in the call to GetGlobbedProviderPathsFromMonadPath, and since "providerInstance" is not null, // the invocation in method GetGlobbedProviderPathsFromMonadPath should succeed. string providerPath = Globber.GetProviderPath(path, context, out provider, out drive); - if (providerPath != null) + if (providerPath is not null) { result = GetChildNamesDynamicParameters(providerInstance, providerPath, newContext); } @@ -2894,15 +2894,15 @@ private object GetChildNamesDynamicParameters( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerId before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); ContainerCmdletProvider containerCmdletProvider = @@ -3106,15 +3106,15 @@ private void RenameItem( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); ContainerCmdletProvider containerCmdletProvider = @@ -3255,15 +3255,15 @@ private object RenameItemDynamicParameters( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); ContainerCmdletProvider containerCmdletProvider = @@ -3485,7 +3485,7 @@ internal void NewItem( // Symbolic link targets are allowed to not exist on both Windows and Linux bool allowNonexistingPath = false; - if (type != null) + if (type is not null) { WildcardPattern typeEvaluator = WildcardPattern.Get(type + "*", WildcardOptions.IgnoreCase | WildcardOptions.Compiled); @@ -3579,11 +3579,11 @@ private void NewItemPrivate( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); ContainerCmdletProvider containerCmdletProvider = @@ -3731,15 +3731,15 @@ private object NewItemDynamicParameters( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); ContainerCmdletProvider containerCmdletProvider = @@ -3994,15 +3994,15 @@ private bool HasChildItems( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); ContainerCmdletProvider containerCmdletProvider = @@ -4176,15 +4176,15 @@ internal void CopyItem( string providerDestinationPath; Runspaces.PSSession session = null; - if (dynamicParams != null) + if (dynamicParams is not null) { - if (dynamicParams.FromSession != null) + if (dynamicParams.FromSession is not null) { sourceIsRemote = true; session = dynamicParams.FromSession; } - if (dynamicParams.ToSession != null) + if (dynamicParams.ToSession is not null) { destinationIsRemote = true; session = dynamicParams.ToSession; @@ -4470,15 +4470,15 @@ private void CopyItem( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); ContainerCmdletProvider containerCmdletProvider = @@ -4542,7 +4542,7 @@ private void CopyRecurseToSingleContainer( CmdletProviderContext context) { Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "The providerInstance should have been verified by the caller"); Dbg.Diagnostics.Assert( @@ -4554,7 +4554,7 @@ private void CopyRecurseToSingleContainer( "The destinationPath should have been verified by the caller"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "The context should have been verified by the caller"); ContainerCmdletProvider containerProviderInstance = @@ -4687,7 +4687,7 @@ internal object CopyItemDynamicParameters( } } - if (providerPath != null) + if (providerPath is not null) { // Get the dynamic parameters for the first resolved path return CopyItemDynamicParameters(providerInstance, providerPath, destination, recurse, newContext); @@ -4736,15 +4736,15 @@ private object CopyItemDynamicParameters( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); ContainerCmdletProvider containerCmdletProvider = @@ -4853,7 +4853,7 @@ private string ValidateRemotePathAndGetRoot(string path, Runspaces.PSSession ses } // If the remote path is not absolute, display an error to the user. - if (op["IsAbsolute"] != null) + if (op["IsAbsolute"] is not null) { bool isAbsolute = (bool)op["IsAbsolute"]; if (!isAbsolute) @@ -4872,10 +4872,10 @@ private string ValidateRemotePathAndGetRoot(string path, Runspaces.PSSession ses bool pathExist = false; string root = null; - if (op["Exists"] != null) + if (op["Exists"] is not null) pathExist = (bool)op["Exists"]; - if (op["Root"] != null) + if (op["Root"] is not null) root = (string)op["Root"]; // Here there are two scenarios: diff --git a/src/System.Management.Automation/engine/SessionStateContent.cs b/src/System.Management.Automation/engine/SessionStateContent.cs index 4184850461a..cfdf7bd1b47 100644 --- a/src/System.Management.Automation/engine/SessionStateContent.cs +++ b/src/System.Management.Automation/engine/SessionStateContent.cs @@ -134,7 +134,7 @@ internal Collection GetContentReader( { IContentReader reader = GetContentReaderPrivate(providerInstance, providerPath, context); - if (reader != null) + if (reader is not null) { results.Add(reader); } @@ -174,15 +174,15 @@ private IContentReader GetContentReaderPrivate( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); IContentReader result = null; @@ -312,15 +312,15 @@ private object GetContentReaderDynamicParameters( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); object result = null; @@ -475,7 +475,7 @@ internal Collection GetContentWriter( IContentWriter result = GetContentWriterPrivate(providerInstance, providerPath, context); - if (result != null) + if (result is not null) { results.Add(result); } @@ -513,15 +513,15 @@ private IContentWriter GetContentWriterPrivate( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); IContentWriter result = null; @@ -657,15 +657,15 @@ private object GetContentWriterDynamicParameters( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); object result = null; @@ -841,15 +841,15 @@ private void ClearContentPrivate( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); try @@ -981,15 +981,15 @@ private object ClearContentDynamicParameters( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); object result = null; diff --git a/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs b/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs index 3ff8ee56e72..4d947879693 100644 --- a/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs @@ -80,7 +80,7 @@ internal PSDriveInfo NewDrive(PSDriveInfo drive, string scopeID) Collection successObjects = context.GetAccumulatedObjects(); - if (successObjects != null && + if (successObjects is not null && successObjects.Count > 0) { Dbg.Diagnostics.Assert( @@ -270,11 +270,11 @@ private static bool IsValidDriveName(string name) private string GetProviderRootFromSpecifiedRoot(string root, ProviderInfo provider) { Dbg.Diagnostics.Assert( - root != null, + root is not null, "Caller should have verified the root"); Dbg.Diagnostics.Assert( - provider != null, + provider is not null, "Caller should have verified the provider"); string result = root; @@ -292,7 +292,7 @@ private string GetProviderRootFromSpecifiedRoot(string root, ProviderInfo provid // If a single path was resolved... - if (resolvedPaths != null && + if (resolvedPaths is not null && resolvedPaths.Count == 1) { // and the provider used to resolve the path, @@ -448,7 +448,7 @@ private PSDriveInfo GetDrive(string name, bool automount) { result = processingScope.GetDrive(name); - if (result != null) + if (result is not null) { if (result.IsAutoMounted) { @@ -460,7 +460,7 @@ private PSDriveInfo GetDrive(string name, bool automount) } } - if (result != null) + if (result is not null) { s_tracer.WriteLine("Drive found in scope {0}", scopeID); break; @@ -542,7 +542,7 @@ internal PSDriveInfo GetDrive(string name, string scopeID) { result = scope.GetDrive(name); - if (result != null) + if (result is not null) { if (result.IsAutoMounted) { @@ -554,7 +554,7 @@ internal PSDriveInfo GetDrive(string name, string scopeID) } } - if (result != null) + if (result is not null) { break; } @@ -571,7 +571,7 @@ internal PSDriveInfo GetDrive(string name, string scopeID) SessionStateScope scope = GetScopeByID(scopeID); result = scope.GetDrive(name); - if (result != null) + if (result is not null) { if (result.IsAutoMounted) { @@ -653,7 +653,7 @@ private PSDriveInfo AutomountFileSystemDrive(System.IO.DriveInfo systemDriveInfo DriveCmdletProvider driveProvider = GetDriveProviderInstance(this.ExecutionContext.ProviderNames.FileSystem); - if (driveProvider != null) + if (driveProvider is not null) { // Create a new drive string systemDriveName = systemDriveInfo.Name.Substring(0, 1); @@ -702,7 +702,7 @@ private PSDriveInfo AutomountFileSystemDrive(System.IO.DriveInfo systemDriveInfo newPSDriveInfo.DriveBeingCreated = false; - if (result != null && !context.HasErrors()) + if (result is not null && !context.HasErrors()) { // Create the drive in the global scope. GlobalScope.NewDrive(result); @@ -794,7 +794,7 @@ internal static void MountDefaultDrive(string name, ExecutionContext context) Exception exception = null; s_tracer.WriteLine("Attempting to load module: {0}", moduleName); CommandDiscovery.AutoloadSpecifiedModule(moduleName, context, commandInfo.Visibility, out exception); - if (exception != null) + if (exception is not null) { // Call-out to user code, catch-all OK } @@ -860,7 +860,7 @@ private bool ValidateOrRemoveAutoMountedDrive(PSDriveInfo drive, SessionStateSco { } - if (driveProvider != null) + if (driveProvider is not null) { CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); @@ -896,7 +896,7 @@ private bool IsAStaleVhdMountedDrive(PSDriveInfo drive) bool result = false; // check that drive's provider type is FileSystem - if ((drive.Provider != null) && (!drive.Provider.NameEquals(this.ExecutionContext.ProviderNames.FileSystem))) + if ((drive.Provider is not null) && (!drive.Provider.NameEquals(this.ExecutionContext.ProviderNames.FileSystem))) { return false; } @@ -910,7 +910,7 @@ private bool IsAStaleVhdMountedDrive(PSDriveInfo drive) // 3. Unmount the VHD in session 'A'. // The drive pointing to VHD in session 'B' gets detected as DriveType.NoRootDirectory // after the VHD is removed in session 'A'. - if (drive != null && !string.IsNullOrEmpty(drive.Name) && drive.Name.Length == 1) + if (drive is not null && !string.IsNullOrEmpty(drive.Name) && drive.Name.Length == 1) { try { @@ -961,7 +961,7 @@ internal Collection GetDrivesForProvider(string providerId) foreach (PSDriveInfo drive in Drives(null)) { - if (drive != null && + if (drive is not null && drive.Provider.NameEquals(providerId)) { drives.Add(drive); @@ -1040,7 +1040,7 @@ internal void RemoveDrive( } Dbg.Diagnostics.Assert( - context != null, + context is not null, "The caller should verify the context"); PSDriveInfo drive = GetDrive(driveName, scopeID); @@ -1167,7 +1167,7 @@ internal void RemoveDrive( try { PSDriveInfo result = scope.GetDrive(drive.Name); - if (result != null) + if (result is not null) { scope.RemoveDrive(drive); @@ -1289,7 +1289,7 @@ private bool CanRemoveDrive(PSDriveInfo drive, CmdletProviderContext context) e); } - if (result != null) + if (result is not null) { // Make sure the provider didn't try to pull a fast one on us // and substitute a different drive. @@ -1351,7 +1351,7 @@ internal Collection Drives(string scope) // drives to overwrite parent scope drives of // the same name. - if (drive != null) + if (drive is not null) { bool driveIsValid = true; @@ -1378,7 +1378,7 @@ internal Collection Drives(string scope) // If the scope was specified then don't loop // through the other scopes - if (scope != null && scope.Length > 0) + if (scope is not null && scope.Length > 0) { break; } @@ -1391,13 +1391,13 @@ internal Collection Drives(string scope) { foreach (System.IO.DriveInfo fsDriveInfo in alldrives) { - if (fsDriveInfo != null) + if (fsDriveInfo is not null) { string fsDriveName = fsDriveInfo.Name.Substring(0, 1); if (!driveTable.ContainsKey(fsDriveName)) { PSDriveInfo automountedDrive = AutomountFileSystemDrive(fsDriveInfo); - if (automountedDrive != null) + if (automountedDrive is not null) { driveTable[automountedDrive.Name] = automountedDrive; } diff --git a/src/System.Management.Automation/engine/SessionStateDynamicProperty.cs b/src/System.Management.Automation/engine/SessionStateDynamicProperty.cs index 2282d57cf5b..55c6cfd7fbf 100644 --- a/src/System.Management.Automation/engine/SessionStateDynamicProperty.cs +++ b/src/System.Management.Automation/engine/SessionStateDynamicProperty.cs @@ -214,19 +214,19 @@ private void NewProperty( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - property != null, + property is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); try @@ -383,15 +383,15 @@ private object NewPropertyDynamicParameters( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); object result = null; @@ -588,19 +588,19 @@ private void RemoveProperty( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - property != null, + property is not null, "Caller should validate property before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); try @@ -741,15 +741,15 @@ private object RemovePropertyDynamicParameters( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); object result = null; @@ -1037,27 +1037,27 @@ private void CopyProperty( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - sourcePath != null, + sourcePath is not null, "Caller should validate sourcePath before calling this method"); Dbg.Diagnostics.Assert( - sourceProperty != null, + sourceProperty is not null, "Caller should validate sourceProperty before calling this method"); Dbg.Diagnostics.Assert( - destinationPath != null, + destinationPath is not null, "Caller should validate destinationPath before calling this method"); Dbg.Diagnostics.Assert( - destinationProperty != null, + destinationProperty is not null, "Caller should validate destinationProperty before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); try @@ -1220,15 +1220,15 @@ private object CopyPropertyDynamicParameters( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); object result = null; @@ -1523,27 +1523,27 @@ private void MoveProperty( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - sourcePath != null, + sourcePath is not null, "Caller should validate sourcePath before calling this method"); Dbg.Diagnostics.Assert( - sourceProperty != null, + sourceProperty is not null, "Caller should validate sourceProperty before calling this method"); Dbg.Diagnostics.Assert( - destinationPath != null, + destinationPath is not null, "Caller should validate destinationPath before calling this method"); Dbg.Diagnostics.Assert( - destinationProperty != null, + destinationProperty is not null, "Caller should validate destinationProperty before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); try @@ -1706,15 +1706,15 @@ private object MovePropertyDynamicParameters( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); object result = null; @@ -1948,23 +1948,23 @@ private void RenameProperty( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - sourcePath != null, + sourcePath is not null, "Caller should validate sourcePath before calling this method"); Dbg.Diagnostics.Assert( - sourceProperty != null, + sourceProperty is not null, "Caller should validate sourceProperty before calling this method"); Dbg.Diagnostics.Assert( - destinationProperty != null, + destinationProperty is not null, "Caller should validate destinationProperty before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); try @@ -2118,15 +2118,15 @@ private object RenamePropertyDynamicParameters( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); object result = null; diff --git a/src/System.Management.Automation/engine/SessionStateFunctionAPIs.cs b/src/System.Management.Automation/engine/SessionStateFunctionAPIs.cs index 8960f872271..a1c07c62d93 100644 --- a/src/System.Management.Automation/engine/SessionStateFunctionAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateFunctionAPIs.cs @@ -193,7 +193,7 @@ private bool IsFunctionVisibleInDebugger(FunctionInfo fnInfo, CommandOrigin orig // Check both InNestedPrompt and Debugger.InBreakpoint to ensure we don't miss a case. // Function is not visible if function and context language modes are different. var runspace = this.ExecutionContext.CurrentRunspace; - if ((runspace != null) && + if ((runspace is not null) && (runspace.InNestedPrompt || (runspace.Debugger?.InBreakpoint == true)) && (fnInfo.DefiningLanguageMode.HasValue && (fnInfo.DefiningLanguageMode != this.ExecutionContext.LanguageMode))) { @@ -771,11 +771,11 @@ internal void RemoveFunction(string name, bool force) /// internal void RemoveFunction(string name, PSModuleInfo module) { - Dbg.Assert(module != null, "Caller should verify that module parameter is not null"); + Dbg.Assert(module is not null, "Caller should verify that module parameter is not null"); FunctionInfo func = GetFunction(name) as FunctionInfo; - if (func != null && func.ScriptBlock != null - && func.ScriptBlock.File != null + if (func is not null && func.ScriptBlock is not null + && func.ScriptBlock.File is not null && func.ScriptBlock.File.Equals(module.Path, StringComparison.OrdinalIgnoreCase)) { RemoveFunction(name, true); diff --git a/src/System.Management.Automation/engine/SessionStateItem.cs b/src/System.Management.Automation/engine/SessionStateItem.cs index c8a51c90e2d..ecd2350d4ad 100644 --- a/src/System.Management.Automation/engine/SessionStateItem.cs +++ b/src/System.Management.Automation/engine/SessionStateItem.cs @@ -170,15 +170,15 @@ private void GetItemPrivate( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); ItemCmdletProvider itemCmdletProvider = @@ -308,15 +308,15 @@ private object GetItemDynamicParameters( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); ItemCmdletProvider itemCmdletProvider = @@ -472,7 +472,7 @@ internal void SetItem( out provider, out providerInstance); - if (providerPaths != null) + if (providerPaths is not null) { foreach (string providerPath in providerPaths) { @@ -514,15 +514,15 @@ private void SetItem( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); ItemCmdletProvider itemCmdletProvider = @@ -659,15 +659,15 @@ private object SetItemDynamicParameters( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); ItemCmdletProvider itemCmdletProvider = @@ -821,7 +821,7 @@ internal void ClearItem( out provider, out providerInstance); - if (providerPaths != null) + if (providerPaths is not null) { foreach (string providerPath in providerPaths) { @@ -859,15 +859,15 @@ private void ClearItemPrivate( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); ItemCmdletProvider itemCmdletProvider = @@ -997,15 +997,15 @@ private object ClearItemDynamicParameters( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); ItemCmdletProvider itemCmdletProvider = @@ -1148,7 +1148,7 @@ internal void InvokeDefaultAction( out provider, out providerInstance); - if (providerPaths != null) + if (providerPaths is not null) { foreach (string providerPath in providerPaths) { @@ -1186,15 +1186,15 @@ private void InvokeDefaultActionPrivate( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); ItemCmdletProvider itemCmdletProvider = @@ -1324,15 +1324,15 @@ private object InvokeDefaultActionDynamicParameters( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); ItemCmdletProvider itemCmdletProvider = diff --git a/src/System.Management.Automation/engine/SessionStateLocationAPIs.cs b/src/System.Management.Automation/engine/SessionStateLocationAPIs.cs index c260f866dd3..a32e73d6f5a 100644 --- a/src/System.Management.Automation/engine/SessionStateLocationAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateLocationAPIs.cs @@ -321,7 +321,7 @@ internal PathInfo SetLocation(string path, CmdletProviderContext context, bool l context = new CmdletProviderContext(this.ExecutionContext); } - if (CurrentDrive != null) + if (CurrentDrive is not null) { context.Drive = CurrentDrive; } @@ -580,7 +580,7 @@ internal PathInfo SetLocation(string path, CmdletProviderContext context, bool l this.SetVariable(SpecialVariables.PWDVarPath, this.CurrentLocation, false, true, CommandOrigin.Internal); // If an action has been defined for location changes, invoke it now. - if (PublicSessionState.InvokeCommand.LocationChangedAction != null) + if (PublicSessionState.InvokeCommand.LocationChangedAction is not null) { var eventArgs = new LocationChangedEventArgs(PublicSessionState, current, CurrentLocation); PublicSessionState.InvokeCommand.LocationChangedAction.Invoke(ExecutionContext.CurrentRunspace, eventArgs); @@ -649,18 +649,18 @@ internal bool IsCurrentLocationOrAncestor(string path, CmdletProviderContext con out provider, out drive); - if (drive != null) + if (drive is not null) { s_tracer.WriteLine("Tracing drive"); drive.Trace(); } Dbg.Diagnostics.Assert( - providerSpecificPath != null, + providerSpecificPath is not null, "There should always be a way to generate a provider path for a " + "given path"); - if (drive != null) + if (drive is not null) { context.Drive = drive; } @@ -946,7 +946,7 @@ internal PathInfo PopLocation(string stackName) PathInfo poppedWorkingDirectory = locationStack.Pop(); Dbg.Diagnostics.Assert( - poppedWorkingDirectory != null, + poppedWorkingDirectory is not null, "All items in the workingLocationStack should be " + "of type PathInfo"); @@ -1062,7 +1062,7 @@ internal PathInfoStack SetDefaultLocationStack(string stackName) Stack locationStack = _workingLocationStack[_defaultStackName]; - if (locationStack != null) + if (locationStack is not null) { return new PathInfoStack(_defaultStackName, locationStack); } diff --git a/src/System.Management.Automation/engine/SessionStateNavigation.cs b/src/System.Management.Automation/engine/SessionStateNavigation.cs index cc3e7dfd840..2b1273090e3 100644 --- a/src/System.Management.Automation/engine/SessionStateNavigation.cs +++ b/src/System.Management.Automation/engine/SessionStateNavigation.cs @@ -165,7 +165,7 @@ internal string GetParentPath( return null; } - if (drive != null) + if (drive is not null) { context.Drive = drive; } @@ -246,7 +246,7 @@ private string AddQualifier(string path, ProviderInfo provider, string qualifier private string RemoveQualifier(string path, ProviderInfo provider, out string qualifier, out bool isProviderQualified, out bool isDriveQualified) { Dbg.Diagnostics.Assert( - path != null, + path is not null, "Path should be verified by the caller"); string result = path; @@ -328,19 +328,19 @@ internal string GetParentPath( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - provider != null, + provider is not null, "Caller should validate provider before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - root != null, + root is not null, "Caller should validate root before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); CmdletProvider providerInstance = GetProviderInstance(provider); @@ -386,19 +386,19 @@ internal string GetParentPath( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - root != null, + root is not null, "Caller should validate root before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); NavigationCmdletProvider navigationCmdletProvider = @@ -551,7 +551,7 @@ internal string NormalizeRelativePath( return null; } - if (basePath != null) + if (basePath is not null) { PSDriveInfo baseDrive = null; ProviderInfo baseProvider = null; @@ -562,7 +562,7 @@ internal string NormalizeRelativePath( out baseProvider, out baseDrive); - if (drive != null && baseDrive != null) + if (drive is not null && baseDrive is not null) { if (!drive.Name.Equals(baseDrive.Name, StringComparison.OrdinalIgnoreCase)) { @@ -580,7 +580,7 @@ internal string NormalizeRelativePath( } } - if (drive != null) + if (drive is not null) { context.Drive = drive; @@ -681,15 +681,15 @@ internal string NormalizeRelativePath( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - provider != null, + provider is not null, "Caller should validate provider before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); // Get an instance of the provider @@ -697,7 +697,7 @@ internal string NormalizeRelativePath( Provider.CmdletProvider providerInstance = GetProviderInstance(provider); NavigationCmdletProvider navigationCmdletProvider = providerInstance as NavigationCmdletProvider; - if (navigationCmdletProvider != null) + if (navigationCmdletProvider is not null) { try { @@ -828,7 +828,7 @@ internal string MakePath( // Set the drive data for the context ProviderInfo provider = null; - if (CurrentDrive != null) + if (CurrentDrive is not null) { provider = CurrentDrive.Provider; } @@ -911,11 +911,11 @@ internal string MakePath( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - provider != null, + provider is not null, "Caller should validate provider before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); // Get an instance of the provider @@ -960,11 +960,11 @@ internal string MakePath( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); // Get an instance of the provider @@ -973,7 +973,7 @@ internal string MakePath( NavigationCmdletProvider navigationCmdletProvider = providerInstance as NavigationCmdletProvider; - if (navigationCmdletProvider != null) + if (navigationCmdletProvider is not null) { try { @@ -1147,15 +1147,15 @@ internal string GetChildName( } Dbg.Diagnostics.Assert( - workingPath != null, + workingPath is not null, "There should always be a way to generate a UniversalResourceName for a " + "given path"); Dbg.Diagnostics.Assert( - provider != null, + provider is not null, "There should always be a way to get the provider ID for a given path or else GetProviderPath should have thrown an exception"); - if (drive != null) + if (drive is not null) { context.Drive = drive; } @@ -1191,15 +1191,15 @@ private string GetChildName( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - provider != null, + provider is not null, "Caller should validate provider before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before callin g this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); CmdletProvider providerInstance = provider.CreateInstance(); @@ -1241,15 +1241,15 @@ bool acceptNonContainerProviders { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); string result = null; @@ -1545,15 +1545,15 @@ private void MoveItemPrivate( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); NavigationCmdletProvider navigationCmdletProvider = @@ -1693,15 +1693,15 @@ private object MoveItemDynamicParameters( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); NavigationCmdletProvider navigationCmdletProvider = diff --git a/src/System.Management.Automation/engine/SessionStateProperty.cs b/src/System.Management.Automation/engine/SessionStateProperty.cs index aaaa57db794..60be80b68f0 100644 --- a/src/System.Management.Automation/engine/SessionStateProperty.cs +++ b/src/System.Management.Automation/engine/SessionStateProperty.cs @@ -180,15 +180,15 @@ private void GetPropertyPrivate( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); try @@ -329,15 +329,15 @@ private object GetPropertyDynamicParameters( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); object result = null; @@ -506,7 +506,7 @@ internal void SetProperty( out provider, out providerInstance); - if (providerPaths != null) + if (providerPaths is not null) { foreach (string providerPath in providerPaths) { @@ -548,19 +548,19 @@ private void SetPropertyPrivate( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - property != null, + property is not null, "Caller should validate properties before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); try @@ -701,15 +701,15 @@ private object SetPropertyDynamicParameters( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); object result = null; @@ -910,19 +910,19 @@ private void ClearPropertyPrivate( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - propertyToClear != null, + propertyToClear is not null, "Caller should validate propertyToClear before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); try @@ -1063,15 +1063,15 @@ private object ClearPropertyDynamicParameters( { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); object result = null; diff --git a/src/System.Management.Automation/engine/SessionStateProviderAPIs.cs b/src/System.Management.Automation/engine/SessionStateProviderAPIs.cs index df1ab0f3786..895fcb67671 100644 --- a/src/System.Management.Automation/engine/SessionStateProviderAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateProviderAPIs.cs @@ -154,7 +154,7 @@ private ProviderInfo AddProvider(Type implementingType, string name, string help private PSDriveInfo ValidateDriveWithProvider(PSDriveInfo drive, CmdletProviderContext context, bool resolvePathIfPossible) { Dbg.Diagnostics.Assert( - drive != null, + drive is not null, "drive should have been validated by the caller"); DriveCmdletProvider namespaceProvider = @@ -170,11 +170,11 @@ private PSDriveInfo ValidateDriveWithProvider( bool resolvePathIfPossible) { Dbg.Diagnostics.Assert( - drive != null, + drive is not null, "drive should have been validated by the caller"); Dbg.Diagnostics.Assert( - driveProvider != null, + driveProvider is not null, "driveProvider should have been validated by the caller"); // Mark the drive as being created so that the provider can modify the @@ -184,11 +184,11 @@ private PSDriveInfo ValidateDriveWithProvider( // Only try to resolve the root as an MSH path if there is a current drive. - if (CurrentDrive != null && resolvePathIfPossible) + if (CurrentDrive is not null && resolvePathIfPossible) { string newRoot = GetProviderRootFromSpecifiedRoot(drive.Root, drive.Provider); - if (newRoot != null) + if (newRoot is not null) { drive.SetRoot(newRoot); } @@ -751,7 +751,7 @@ internal bool IsProviderLoaded(string name) { ProviderInfo providerInfo = GetSingleProvider(name); - result = providerInfo != null; + result = providerInfo is not null; } catch (ProviderNotFoundException) { @@ -1002,12 +1002,12 @@ internal void InitializeProvider( DriveCmdletProvider driveProvider = GetDriveProviderInstance(providerInstance); - if (driveProvider != null) + if (driveProvider is not null) { try { Collection drives = driveProvider.InitializeDefaultDrives(context); - if (drives != null && drives.Count > 0) + if (drives is not null && drives.Count > 0) { newDrives.AddRange(drives); ProvidersCurrentWorkingDrive[provider] = drives[0]; @@ -1044,7 +1044,7 @@ internal void InitializeProvider( } } - if (newDrives != null && newDrives.Count > 0) + if (newDrives is not null && newDrives.Count > 0) { // Add the drives. @@ -1066,7 +1066,7 @@ internal void InitializeProvider( { PSDriveInfo validatedNewDrive = ValidateDriveWithProvider(driveProvider, newDrive, context, false); - if (validatedNewDrive != null) + if (validatedNewDrive is not null) { // Since providers are global then the drives created // through InitializeDefaultDrives should also be global. @@ -1113,7 +1113,7 @@ internal ProviderInfo NewProvider(ProviderInfo provider) // throw the exception so that we give a better error // message. ProviderInfo existingProvider = ProviderExists(provider); - if (existingProvider != null) + if (existingProvider is not null) { // If it's an already loaded provider, don't return an error... if (existingProvider.ImplementingType == provider.ImplementingType) @@ -1438,7 +1438,7 @@ internal void RemoveProvider( int driveCount = 0; foreach (PSDriveInfo drive in GetDrivesForProvider(providerName)) { - if (drive != null) + if (drive is not null) { ++driveCount; break; @@ -1453,7 +1453,7 @@ internal void RemoveProvider( foreach (PSDriveInfo drive in GetDrivesForProvider(providerName)) { - if (drive != null) + if (drive is not null) { RemoveDrive(drive, true, null); } diff --git a/src/System.Management.Automation/engine/SessionStatePublic.cs b/src/System.Management.Automation/engine/SessionStatePublic.cs index a8894e1dfe5..054b0f488b5 100644 --- a/src/System.Management.Automation/engine/SessionStatePublic.cs +++ b/src/System.Management.Automation/engine/SessionStatePublic.cs @@ -188,7 +188,7 @@ public static void ThrowIfNotVisible(CommandOrigin origin, object valueToCheck) if (!IsVisible(origin, valueToCheck)) { PSVariable sv = valueToCheck as PSVariable; - if (sv != null) + if (sv is not null) { exception = new SessionStateException( @@ -202,10 +202,10 @@ public static void ThrowIfNotVisible(CommandOrigin origin, object valueToCheck) } CommandInfo cinfo = valueToCheck as CommandInfo; - if (cinfo != null) + if (cinfo is not null) { string commandName = cinfo.Name; - if (commandName != null) + if (commandName is not null) { // If we have a name, use it in the error message exception = @@ -254,7 +254,7 @@ public static bool IsVisible(CommandOrigin origin, object valueToCheck) if (origin == CommandOrigin.Internal) return true; IHasSessionStateEntryVisibility obj = valueToCheck as IHasSessionStateEntryVisibility; - if (obj != null) + if (obj is not null) { return (obj.Visibility == SessionStateEntryVisibility.Public); } diff --git a/src/System.Management.Automation/engine/SessionStateScope.cs b/src/System.Management.Automation/engine/SessionStateScope.cs index 77ee2e62027..8491b656d52 100644 --- a/src/System.Management.Automation/engine/SessionStateScope.cs +++ b/src/System.Management.Automation/engine/SessionStateScope.cs @@ -28,7 +28,7 @@ internal SessionStateScope(SessionStateScope parentScope) ScopeOrigin = CommandOrigin.Internal; Parent = parentScope; - if (parentScope != null) + if (parentScope is not null) { // Now copy the script: scope stack from the parent _scriptScope = parentScope.ScriptScope; @@ -68,7 +68,7 @@ internal SessionStateScope ScriptScope set { - Diagnostics.Assert(value != null, "Caller to verify scope is not null"); + Diagnostics.Assert(value is not null, "Caller to verify scope is not null"); _scriptScope = value; } } @@ -319,7 +319,7 @@ internal PSVariable GetVariable(string name) /// True if there is a variable in scope, false otherwise. internal bool TryGetVariable(string name, CommandOrigin origin, bool fromNewOrSet, out PSVariable variable) { - Diagnostics.Assert(name != null, "The caller should verify the name"); + Diagnostics.Assert(name is not null, "The caller should verify the name"); if (TryGetLocalVariableFromTuple(name, fromNewOrSet, out variable)) { @@ -353,7 +353,7 @@ internal object GetAutomaticVariableValue(AutomaticVariable variable) // LocalsTuple should not be null, but the test infrastructure creates scopes // and doesn't set LocalsTuple - if (LocalsTuple != null && LocalsTuple.IsValueSet(index)) + if (LocalsTuple is not null && LocalsTuple.IsValueSet(index)) { return LocalsTuple.GetValue(index); } @@ -396,7 +396,7 @@ internal object GetAutomaticVariableValue(AutomaticVariable variable) /// internal PSVariable SetVariable(string name, object value, bool asValue, bool force, SessionStateInternal sessionState, CommandOrigin origin = CommandOrigin.Internal, bool fastPath = false) { - Diagnostics.Assert(name != null, "The caller should verify the name"); + Diagnostics.Assert(name is not null, "The caller should verify the name"); PSVariable variable; PSVariable variableToSet = value as PSVariable; @@ -405,7 +405,7 @@ internal PSVariable SetVariable(string name, object value, bool asValue, bool fo // can only be used for global scope otherwise the slow path is used. if (fastPath) { - if (Parent != null) + if (Parent is not null) { throw new NotImplementedException("fastPath"); } @@ -420,7 +420,7 @@ internal PSVariable SetVariable(string name, object value, bool asValue, bool fo // Initialize the private variable dictionary if it's not yet if (_variables is null) { GetPrivateVariables(); } - if (!asValue && variableToSet != null) + if (!asValue && variableToSet is not null) { if (varExists) { @@ -483,13 +483,13 @@ internal PSVariable SetVariable(string name, object value, bool asValue, bool fo variable = variableToSet; } } - else if (variable != null) + else if (variable is not null) { variable.Value = value; } else { - variable = (LocalsTuple != null ? LocalsTuple.TrySetVariable(name, value) : null) ?? new PSVariable(name, value); + variable = (LocalsTuple is not null ? LocalsTuple.TrySetVariable(name, value) : null) ?? new PSVariable(name, value); } if (ExecutionContext.HasEverUsedConstrainedLanguage) @@ -511,7 +511,7 @@ internal PSVariable SetVariable(string name, object value, bool asValue, bool fo /// internal void SetVariableForce(PSVariable variableToSet, SessionStateInternal sessionState) { - if (Parent != null) + if (Parent is not null) { throw new NotImplementedException("SetVariableForce"); } @@ -615,7 +615,7 @@ internal PSVariable NewVariable(PSVariable newVariable, bool force, SessionState internal void RemoveVariable(string name, bool force) { Diagnostics.Assert( - name != null, + name is not null, "The caller should verify the name"); PSVariable variable = GetVariable(name); @@ -661,7 +661,7 @@ internal bool TrySetLocalParameterValue(string name, object value) } } - return LocalsTuple != null && LocalsTuple.TrySetParameter(name, value); + return LocalsTuple is not null && LocalsTuple.TrySetParameter(name, value); } /// @@ -681,7 +681,7 @@ internal bool TryGetLocalVariableFromTuple(string name, bool fromNewOrSet, out P } result = null; - return LocalsTuple != null && LocalsTuple.TryGetLocalVariable(name, fromNewOrSet, out result); + return LocalsTuple is not null && LocalsTuple.TryGetLocalVariable(name, fromNewOrSet, out result); } #endregion variables @@ -711,7 +711,7 @@ internal IEnumerable AliasTable internal AliasInfo GetAlias(string name) { Diagnostics.Assert( - name != null, + name is not null, "The caller should verify the name"); AliasInfo result; @@ -747,7 +747,7 @@ internal AliasInfo GetAlias(string name) internal AliasInfo SetAliasValue(string name, string value, ExecutionContext context, bool force, CommandOrigin origin) { Diagnostics.Assert( - name != null, + name is not null, "The caller should verify the name"); var aliasInfos = GetAliases(); @@ -828,7 +828,7 @@ internal AliasInfo SetAliasValue( CommandOrigin origin) { Diagnostics.Assert( - name != null, + name is not null, "The caller should verify the name"); var aliasInfos = GetAliases(); @@ -930,7 +930,7 @@ internal AliasInfo SetAliasValue( internal AliasInfo SetAliasItem(AliasInfo aliasToSet, bool force, CommandOrigin origin = CommandOrigin.Internal) { Diagnostics.Assert( - aliasToSet != null, + aliasToSet is not null, "The caller should verify the aliasToSet"); var aliasInfos = GetAliases(); @@ -996,7 +996,7 @@ internal AliasInfo SetAliasItem(AliasInfo aliasToSet, bool force, CommandOrigin internal void RemoveAlias(string name, bool force) { Diagnostics.Assert( - name != null, + name is not null, "The caller should verify the name"); // Make sure the alias isn't constant or readonly @@ -1052,7 +1052,7 @@ internal Dictionary FunctionTable internal FunctionInfo GetFunction(string name) { Diagnostics.Assert( - name != null, + name is not null, "The caller should verify the name"); FunctionInfo result; @@ -1239,7 +1239,7 @@ internal FunctionInfo SetFunction( Func functionFactory) { Diagnostics.Assert( - name != null, + name is not null, "The caller should verify the name"); var functionInfos = GetFunctions(); @@ -1349,7 +1349,7 @@ internal FunctionInfo SetFunction( internal void RemoveFunction(string name, bool force) { Diagnostics.Assert( - name != null, + name is not null, "The caller should verify the name"); var functionInfos = GetFunctions(); @@ -1405,7 +1405,7 @@ internal Dictionary> CmdletTable internal CmdletInfo GetCmdlet(string name) { Diagnostics.Assert( - name != null, + name is not null, "The caller should verify the name"); CmdletInfo result = null; @@ -1414,7 +1414,7 @@ internal CmdletInfo GetCmdlet(string name) if (_cmdlets.TryGetValue(name, out cmdlets)) { - if (cmdlets != null && cmdlets.Count > 0) + if (cmdlets is not null && cmdlets.Count > 0) { result = cmdlets[0]; } @@ -1455,7 +1455,7 @@ internal CmdletInfo AddCmdletToCache( try { Diagnostics.Assert( - name != null, + name is not null, "The caller should verify the name"); List cmdlets; @@ -1551,7 +1551,7 @@ internal CmdletInfo AddCmdletToCache( internal void RemoveCmdlet(string name, int index, bool force) { Diagnostics.Assert( - name != null, + name is not null, "The caller should verify the name"); List cmdlets; @@ -1591,7 +1591,7 @@ internal void RemoveCmdlet(string name, int index, bool force) internal void RemoveCmdletEntry(string name, bool force) { Diagnostics.Assert( - name != null, + name is not null, "The caller should verify the name"); _cmdlets.Remove(name); @@ -1607,12 +1607,12 @@ internal Language.TypeResolutionState TypeResolutionState { get { - if (_typeResolutionState != null) + if (_typeResolutionState is not null) { return _typeResolutionState; } - return Parent != null ? Parent.TypeResolutionState : Language.TypeResolutionState.UsingSystem; + return Parent is not null ? Parent.TypeResolutionState : Language.TypeResolutionState.UsingSystem; } set { _typeResolutionState = value; } @@ -1668,7 +1668,7 @@ private static FunctionInfo CreateFunction(string name, ScriptBlock function, Fu { newValue = new ConfigurationInfo(name, (ConfigurationInfo)originalFunction); } - else if (originalFunction != null) + else if (originalFunction is not null) { newValue = new FunctionInfo(name, originalFunction); } @@ -1767,7 +1767,7 @@ private Dictionary GetAliases() // Create the alias table _alias = new Dictionary(StringComparer.OrdinalIgnoreCase); - if (Parent != null) + if (Parent is not null) { // Propagate all aliases that are marked AllScope foreach (AliasInfo newAlias in Parent.GetAliases().Values) @@ -1797,7 +1797,7 @@ private Dictionary GetFunctions() // Create the functions table _functions = new Dictionary(StringComparer.OrdinalIgnoreCase); - if (Parent != null && Parent._allScopeFunctions != null) + if (Parent is not null && Parent._allScopeFunctions is not null) { // Propagate all functions that are marked AllScope foreach (FunctionInfo newFunc in Parent._allScopeFunctions.Values) @@ -1823,7 +1823,7 @@ private Dictionary GetAllScopeFunctions() { if (_allScopeFunctions is null) { - if (Parent != null && Parent._allScopeFunctions != null) + if (Parent is not null && Parent._allScopeFunctions is not null) { return Parent._allScopeFunctions; } @@ -1953,7 +1953,7 @@ private void RemoveAliasFromCache(string alias, string value) else { string itemToRemove = list.Find(item => item.Equals(alias, StringComparison.OrdinalIgnoreCase)); - if (itemToRemove != null) + if (itemToRemove is not null) { list.Remove(itemToRemove); } diff --git a/src/System.Management.Automation/engine/SessionStateScopeAPIs.cs b/src/System.Management.Automation/engine/SessionStateScopeAPIs.cs index 6271adf387b..5a87570ec1f 100644 --- a/src/System.Management.Automation/engine/SessionStateScopeAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateScopeAPIs.cs @@ -130,7 +130,7 @@ internal SessionStateScope GetScopeByID(int scopeID) SessionStateScope processingScope = _currentScope; int originalID = scopeID; - while (scopeID > 0 && processingScope != null) + while (scopeID > 0 && processingScope is not null) { processingScope = processingScope.Parent; scopeID--; @@ -175,7 +175,7 @@ internal SessionStateScope CurrentScope set { Diagnostics.Assert( - value != null, + value is not null, "A null scope should never be set"); #if DEBUG // This code is ifdef'd for DEBUG because it may pose a significant @@ -188,7 +188,7 @@ internal SessionStateScope CurrentScope SessionStateScope scope = value; bool inGlobalScopeLineage = false; - while (scope != null) + while (scope is not null) { if (scope == GlobalScope) { @@ -227,7 +227,7 @@ internal SessionStateScope CurrentScope internal SessionStateScope NewScope(bool isScriptScope) { Diagnostics.Assert( - _currentScope != null, + _currentScope is not null, "The currentScope should always be set."); // Create the new child scope. @@ -255,7 +255,7 @@ internal SessionStateScope NewScope(bool isScriptScope) internal void RemoveScope(SessionStateScope scope) { Diagnostics.Assert( - _currentScope != null, + _currentScope is not null, "The currentScope should always be set."); if (scope == GlobalScope) @@ -313,7 +313,7 @@ internal void RemoveScope(SessionStateScope scope) // If the scope being removed is the current scope, // then it must be removed from the tree. - if (scope == _currentScope && _currentScope.Parent != null) + if (scope == _currentScope && _currentScope.Parent is not null) { _currentScope = _currentScope.Parent; } diff --git a/src/System.Management.Automation/engine/SessionStateScopeEnumerator.cs b/src/System.Management.Automation/engine/SessionStateScopeEnumerator.cs index e807c92131c..8efc235867d 100644 --- a/src/System.Management.Automation/engine/SessionStateScopeEnumerator.cs +++ b/src/System.Management.Automation/engine/SessionStateScopeEnumerator.cs @@ -17,7 +17,7 @@ internal sealed class SessionStateScopeEnumerator : IEnumerator internal SessionStateScopeEnumerator(SessionStateScope scope) { - Diagnostics.Assert(scope != null, "Caller to verify scope argument"); + Diagnostics.Assert(scope is not null, "Caller to verify scope argument"); _initialScope = scope; } @@ -37,7 +37,7 @@ public bool MoveNext() // If the current scope is the global scope there is nowhere else // to do the lookup, so return false. - return (_currentEnumeratedScope != null); + return (_currentEnumeratedScope is not null); } /// diff --git a/src/System.Management.Automation/engine/SessionStateSecurityDescriptorInterface.cs b/src/System.Management.Automation/engine/SessionStateSecurityDescriptorInterface.cs index 692d99127b3..48f4aaef5de 100644 --- a/src/System.Management.Automation/engine/SessionStateSecurityDescriptorInterface.cs +++ b/src/System.Management.Automation/engine/SessionStateSecurityDescriptorInterface.cs @@ -138,15 +138,15 @@ private void GetSecurityDescriptor( { // All parameters should have been validated by caller Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); // This just verifies that the provider supports the interface. @@ -284,19 +284,19 @@ private void SetSecurityDescriptor( { // All parameters should have been validated by caller Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Diagnostics.Assert( - securityDescriptor != null, + securityDescriptor is not null, "Caller should validate securityDescriptor before calling this method"); Diagnostics.Assert( - context != null, + context is not null, "Caller should validate context before calling this method"); // This just verifies that the provider supports the interface. @@ -434,15 +434,15 @@ private ObjectSecurity NewSecurityDescriptorFromPath( // All parameters should have been validated by caller Diagnostics.Assert( - providerInstance != null, + providerInstance is not null, "Caller should validate providerInstance before calling this method"); Diagnostics.Assert( - path != null, + path is not null, "Caller should validate path before calling this method"); Diagnostics.Assert( - ExecutionContext != null, + ExecutionContext is not null, "Caller should validate context before calling this method"); // This just verifies that the provider supports the interface. diff --git a/src/System.Management.Automation/engine/SessionStateUtils.cs b/src/System.Management.Automation/engine/SessionStateUtils.cs index 7b8b8466760..e202edc38af 100644 --- a/src/System.Management.Automation/engine/SessionStateUtils.cs +++ b/src/System.Management.Automation/engine/SessionStateUtils.cs @@ -118,7 +118,7 @@ internal static class SessionStateUtilities internal static Collection ConvertArrayToCollection(T[] array) { Collection result = new Collection(); - if (array != null) + if (array is not null) { foreach (T element in array) { @@ -160,7 +160,7 @@ internal static bool CollectionContainsValue(IEnumerable collection, object valu foreach (object item in collection) { - if (comparer != null) + if (comparer is not null) { if (comparer.Compare(item, value) == 0) { @@ -201,7 +201,7 @@ internal static Collection CreateWildcardsFromStrings( { Collection result = new Collection(); - if (globPatterns != null) + if (globPatterns is not null) { // Loop through the patterns and construct a wildcard pattern for each one @@ -245,7 +245,7 @@ internal static bool MatchesAnyWildcardPattern( bool result = false; bool patternsNonEmpty = false; - if (patterns != null) + if (patterns is not null) { // Loop through each of the patterns until a match is found foreach (WildcardPattern pattern in patterns) diff --git a/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs b/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs index d99c5de2daa..c481ee8dd42 100644 --- a/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs @@ -217,7 +217,7 @@ internal object GetVariableValue( if (variablePath.IsVariable) { PSVariable variable = GetVariableItem(variablePath, out scope); - if (variable != null) + if (variable is not null) { result = variable.Value; } @@ -425,7 +425,7 @@ internal object GetVariableValueFromProvider( // Read all the content IList resultList = reader.Read(-1); - if (resultList != null) + if (resultList is not null) { if (resultList.Count == 0) { @@ -475,7 +475,7 @@ internal object GetVariableValueFromProvider( Collection items = context.GetAccumulatedObjects (); - if (items != null && + if (items is not null && items.Count > 0) { result = items[0]; @@ -707,7 +707,7 @@ internal object GetVariableValueAtScope(string name, string scopeID) { PSDriveInfo drive = lookupScope.GetDrive(variablePath.DriveName); - if (drive != null) + if (drive is not null) { CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); context.Drive = drive; @@ -814,7 +814,7 @@ internal object GetVariableValueAtScope(string name, string scopeID) // Read all the content IList resultList = reader.Read(-1); - if (resultList != null) + if (resultList is not null) { if (resultList.Count == 0) { @@ -857,7 +857,7 @@ internal object GetVariableValueAtScope(string name, string scopeID) Collection results = context.GetAccumulatedObjects (); - if (results != null & + if (results is not null & results.Count > 0) { // Only return the first value. If the caller wants globbing @@ -879,11 +879,11 @@ internal object GetVariableValueAtScope(string name, string scopeID) // If we get a PSVariable or DictionaryEntry returned then we have to // grab the value from it and return that instead. - if (resultItem != null) + if (resultItem is not null) { PSVariable variable = resultItem as PSVariable; - if (variable != null) + if (variable is not null) { resultItem = variable.Value; } @@ -1177,7 +1177,7 @@ internal object SetVariable( // If the name is scoped as private we need to mark the // variable as private - if (variablePath.IsPrivate && varResult != null) + if (variablePath.IsPrivate && varResult is not null) { varResult.Options = varResult.Options | ScopedItemOptions.Private; } @@ -1199,7 +1199,7 @@ internal object SetVariable( try { - if (context != null) + if (context is not null) { try { @@ -1343,7 +1343,7 @@ internal object SetVariable( writer.Close(); } #else - if (context != null) + if (context is not null) { context.Force = force; SetItem (variablePath.LookupPath.ToString (), newValue, context); @@ -1355,7 +1355,7 @@ internal object SetVariable( Collection setItemResult = SetItem (variablePath.LookupPath.ToString (), newValue); - if (setItemResult != null && + if (setItemResult is not null && setItemResult.Count > 0) { result = setItemResult[0]; @@ -1572,7 +1572,7 @@ internal void RemoveVariable(string name, bool force) if (variablePath.IsVariable) { - if (GetVariableItem(variablePath, out scope) != null) + if (GetVariableItem(variablePath, out scope) is not null) { scope.RemoveVariable(variablePath.QualifiedName, force); } @@ -1630,7 +1630,7 @@ internal void RemoveVariable(PSVariable variable, bool force) SessionStateScope scope = null; - if (GetVariableItem(variablePath, out scope) != null) + if (GetVariableItem(variablePath, out scope) is not null) { scope.RemoveVariable(variablePath.QualifiedName, force); } @@ -1718,7 +1718,7 @@ internal void RemoveVariableAtScope(string name, string scopeID, bool force) { PSDriveInfo drive = lookupScope.GetDrive(variablePath.DriveName); - if (drive != null) + if (drive is not null) { CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); context.Drive = drive; @@ -1839,7 +1839,7 @@ private void GetScopeVariableTable(SessionStateScope scope, Dictionary 0) + if (context is not null && context._debuggingMode > 0) { context.Debugger.CheckVariableRead(Name); } @@ -235,10 +235,10 @@ internal void DebuggerCheckVariableRead() internal void DebuggerCheckVariableWrite() { - var context = SessionState != null + var context = SessionState is not null ? SessionState.ExecutionContext : LocalPipeline.GetExecutionContextFromTLS(); - if (context != null && context._debuggingMode > 0) + if (context is not null && context._debuggingMode > 0) { context.Debugger.CheckVariableWrite(Name); } @@ -292,7 +292,7 @@ public string ModuleName { get { - if (Module != null) + if (Module is not null) return Module.Name; return string.Empty; } @@ -412,7 +412,7 @@ public virtual bool IsValidValue(object value) internal static bool IsValidValue(IEnumerable attributes, object value) { - if (attributes != null) + if (attributes is not null) { foreach (Attribute attribute in attributes) { @@ -443,7 +443,7 @@ internal static bool IsValidValue(object value, Attribute attribute) bool result = true; ValidateArgumentsAttribute validationAttribute = attribute as ValidateArgumentsAttribute; - if (validationAttribute != null) + if (validationAttribute is not null) { try { @@ -452,7 +452,7 @@ internal static bool IsValidValue(object value, Attribute attribute) ExecutionContext context = Runspaces.LocalPipeline.GetExecutionContextFromTLS(); EngineIntrinsics engine = null; - if (context != null) + if (context is not null) { engine = context.EngineIntrinsics; } @@ -486,7 +486,7 @@ internal static bool IsValidValue(object value, Attribute attribute) /// internal static object TransformValue(IEnumerable attributes, object value) { - Diagnostics.Assert(attributes != null, "caller to verify attributes is not null"); + Diagnostics.Assert(attributes is not null, "caller to verify attributes is not null"); object result = value; @@ -495,7 +495,7 @@ internal static object TransformValue(IEnumerable attributes, object ExecutionContext context = Runspaces.LocalPipeline.GetExecutionContextFromTLS(); EngineIntrinsics engine = null; - if (context != null) + if (context is not null) { engine = context.EngineIntrinsics; } @@ -504,7 +504,7 @@ internal static object TransformValue(IEnumerable attributes, object { ArgumentTransformationAttribute transformationAttribute = attribute as ArgumentTransformationAttribute; - if (transformationAttribute != null) + if (transformationAttribute is not null) { result = transformationAttribute.TransformInternal(engine, result); } @@ -641,7 +641,7 @@ private void SetValue(object value) // Now perform all ArgumentTransformations that are needed object transformedValue = value; - if (_attributes != null && _attributes.Count > 0) + if (_attributes is not null && _attributes.Count > 0) { transformedValue = TransformValue(_attributes, value); @@ -654,13 +654,13 @@ private void SetValue(object value) null, Metadata.InvalidValueFailure, Name, - ((transformedValue != null) ? transformedValue.ToString() : "$null")); + ((transformedValue is not null) ? transformedValue.ToString() : "$null")); throw e; } } - if (transformedValue != null) + if (transformedValue is not null) { transformedValue = CopyMutableValues(transformedValue); } @@ -699,7 +699,7 @@ internal void WrapValue() { if (!this.IsConstant) { - if (_value != null) + if (_value is not null) { _value = PSObject.AsPSObject(_value); } @@ -723,10 +723,10 @@ private static object PreserveValueType(object value) return value; PSObject valueAsPSObject = value as PSObject; - if (valueAsPSObject != null) + if (valueAsPSObject is not null) { object baseObject = valueAsPSObject.BaseObject; - if (baseObject != null) + if (baseObject is not null) { valueType = baseObject.GetType(); if (valueType.IsValueType && !valueType.IsPrimitive) diff --git a/src/System.Management.Automation/engine/ThirdPartyAdapter.cs b/src/System.Management.Automation/engine/ThirdPartyAdapter.cs index 757fdaae99e..9041275eaff 100644 --- a/src/System.Management.Automation/engine/ThirdPartyAdapter.cs +++ b/src/System.Management.Automation/engine/ThirdPartyAdapter.cs @@ -120,7 +120,7 @@ protected override PSProperty DoGetProperty(object obj, string propertyName) ExtendedTypeSystem.GetProperty, propertyName, obj.ToString()); } - if (property != null) + if (property is not null) { InitializeProperty(property, obj); } @@ -144,7 +144,7 @@ protected override PSProperty DoGetFirstPropertyOrDefault(object obj, MemberName ExtendedTypeSystem.GetProperty, nameof(predicate), obj.ToString()); } - if (property != null) + if (property is not null) { InitializeProperty(property, obj); } @@ -171,7 +171,7 @@ protected override bool PropertyIsSettable(PSProperty property) { PSAdaptedProperty adaptedProperty = property as PSAdaptedProperty; - Diagnostics.Assert(adaptedProperty != null, "ThirdPartyAdapter should only receive PSAdaptedProperties"); + Diagnostics.Assert(adaptedProperty is not null, "ThirdPartyAdapter should only receive PSAdaptedProperties"); try { @@ -193,7 +193,7 @@ protected override bool PropertyIsGettable(PSProperty property) { PSAdaptedProperty adaptedProperty = property as PSAdaptedProperty; - Diagnostics.Assert(adaptedProperty != null, "ThirdPartyAdapter should only receive PSAdaptedProperties"); + Diagnostics.Assert(adaptedProperty is not null, "ThirdPartyAdapter should only receive PSAdaptedProperties"); try { @@ -215,7 +215,7 @@ protected override object PropertyGet(PSProperty property) { PSAdaptedProperty adaptedProperty = property as PSAdaptedProperty; - Diagnostics.Assert(adaptedProperty != null, "ThirdPartyAdapter should only receive PSAdaptedProperties"); + Diagnostics.Assert(adaptedProperty is not null, "ThirdPartyAdapter should only receive PSAdaptedProperties"); try { @@ -237,7 +237,7 @@ protected override void PropertySet(PSProperty property, object setValue, bool c { PSAdaptedProperty adaptedProperty = property as PSAdaptedProperty; - Diagnostics.Assert(adaptedProperty != null, "ThirdPartyAdapter should only receive PSAdaptedProperties"); + Diagnostics.Assert(adaptedProperty is not null, "ThirdPartyAdapter should only receive PSAdaptedProperties"); try { @@ -260,7 +260,7 @@ protected override string PropertyType(PSProperty property, bool forDisplay) { PSAdaptedProperty adaptedProperty = property as PSAdaptedProperty; - Diagnostics.Assert(adaptedProperty != null, "ThirdPartyAdapter should only receive PSAdaptedProperties"); + Diagnostics.Assert(adaptedProperty is not null, "ThirdPartyAdapter should only receive PSAdaptedProperties"); string propertyTypeName = null; @@ -303,7 +303,7 @@ public virtual Collection GetTypeNameHierarchy(object baseObject) Collection types = new Collection(); - for (Type type = baseObject.GetType(); type != null; type = type.BaseType) + for (Type type = baseObject.GetType(); type is not null; type = type.BaseType) { types.Add(type.FullName); } diff --git a/src/System.Management.Automation/engine/TransactedString.cs b/src/System.Management.Automation/engine/TransactedString.cs index 948cf1d9d81..22994063e09 100644 --- a/src/System.Management.Automation/engine/TransactedString.cs +++ b/src/System.Management.Automation/engine/TransactedString.cs @@ -79,7 +79,7 @@ public void Append(string text) { ValidateTransactionOrEnlist(); - if (_enlistedTransaction != null) + if (_enlistedTransaction is not null) { _temporaryValue.Append(text); } @@ -102,7 +102,7 @@ public void Remove(int startIndex, int length) { ValidateTransactionOrEnlist(); - if (_enlistedTransaction != null) + if (_enlistedTransaction is not null) { _temporaryValue.Remove(startIndex, length); } @@ -162,7 +162,7 @@ public override string ToString() private void ValidateTransactionOrEnlist() { // We're in a transaction - if (Transaction.Current != null) + if (Transaction.Current is not null) { // We haven't yet been called inside of a transaction. So enlist // in the transaction, and store our save point @@ -187,7 +187,7 @@ private void ValidateTransactionOrEnlist() else { // If we're not subscribed to a transaction, modify the underlying value - if (_enlistedTransaction != null) + if (_enlistedTransaction is not null) { throw new InvalidOperationException("Cannot modify string. It has been modified by another transaction."); } diff --git a/src/System.Management.Automation/engine/TransactionManager.cs b/src/System.Management.Automation/engine/TransactionManager.cs index bf86d90e812..7131f06c3e5 100644 --- a/src/System.Management.Automation/engine/TransactionManager.cs +++ b/src/System.Management.Automation/engine/TransactionManager.cs @@ -142,7 +142,7 @@ internal bool IsRolledBack // Check if it's been aborted underneath us if ( (!_isRolledBack) && - (_transaction != null) && + (_transaction is not null) && (_transaction.TransactionInformation.Status == TransactionStatus.Aborted)) { _isRolledBack = true; @@ -193,7 +193,7 @@ public void Dispose(bool disposing) { if (disposing) { - if (_transaction != null) + if (_transaction is not null) { _transaction.Dispose(); } @@ -295,7 +295,7 @@ internal PSTransactionManager() /// internal static IDisposable GetEngineProtectionScope() { - if (s_engineProtectionEnabled && (Transaction.Current != null)) + if (s_engineProtectionEnabled && (Transaction.Current is not null)) { return new System.Transactions.TransactionScope( System.Transactions.TransactionScopeOption.Suppress); @@ -359,7 +359,7 @@ internal void CreateOrJoin(RollbackSeverity rollbackPreference, TimeSpan timeout PSTransaction currentTransaction = _transactionStack.Peek(); // There is a transaction on the stack - if (currentTransaction != null) + if (currentTransaction is not null) { // If you are already in a transaction that has been aborted, or committed, // create it. @@ -517,7 +517,7 @@ internal void SetBaseTransaction(CommittableTransaction transaction, RollbackSev PSTransaction currentTransaction = _transactionStack.Peek(); // If there is a "used" transaction at the top of the stack, clean it up - while (_transactionStack.Peek() != null && + while (_transactionStack.Peek() is not null && (_transactionStack.Peek().IsRolledBack || _transactionStack.Peek().IsCommitted)) { _transactionStack.Pop().Dispose(); @@ -609,7 +609,7 @@ internal bool HasTransaction { PSTransaction currentTransaction = _transactionStack.Peek(); - if ((currentTransaction != null) && + if ((currentTransaction is not null) && (!currentTransaction.IsCommitted) && (!currentTransaction.IsRolledBack)) { @@ -631,7 +631,7 @@ internal bool IsLastTransactionCommitted { PSTransaction currentTransaction = _transactionStack.Peek(); - if (currentTransaction != null) + if (currentTransaction is not null) { return currentTransaction.IsCommitted; } @@ -651,7 +651,7 @@ internal bool IsLastTransactionRolledBack { PSTransaction currentTransaction = _transactionStack.Peek(); - if (currentTransaction != null) + if (currentTransaction is not null) { return currentTransaction.IsRolledBack; } @@ -693,7 +693,7 @@ public void Dispose(bool disposing) { ResetActive(); - while (_transactionStack.Peek() != null) + while (_transactionStack.Peek() is not null) { PSTransaction currentTransaction = _transactionStack.Pop(); diff --git a/src/System.Management.Automation/engine/TypeMetadata.cs b/src/System.Management.Automation/engine/TypeMetadata.cs index cb6ea928162..400ae1b1903 100644 --- a/src/System.Management.Automation/engine/TypeMetadata.cs +++ b/src/System.Management.Automation/engine/TypeMetadata.cs @@ -39,7 +39,7 @@ public sealed class ParameterSetMetadata /// internal ParameterSetMetadata(ParameterSetSpecificMetadata psMD) { - Dbg.Assert(psMD != null, "ParameterSetSpecificMetadata cannot be null"); + Dbg.Assert(psMD is not null, "ParameterSetSpecificMetadata cannot be null"); Initialize(psMD); } @@ -485,7 +485,7 @@ public ParameterMetadata(ParameterMetadata other) /// internal ParameterMetadata(CompiledCommandParameter cmdParameterMD) { - Dbg.Assert(cmdParameterMD != null, + Dbg.Assert(cmdParameterMD is not null, "CompiledCommandParameter cannot be null"); Initialize(cmdParameterMD); @@ -599,7 +599,7 @@ public bool SwitchParameter { get { - if (_parameterType != null) + if (_parameterType is not null) { return _parameterType.Equals(typeof(SwitchParameter)); } @@ -678,7 +678,7 @@ internal void Initialize(CompiledCommandParameter compiledParameterMD) internal static Dictionary GetParameterMetadata(MergedCommandParameterMetadata cmdParameterMetadata) { - Dbg.Assert(cmdParameterMetadata != null, "cmdParameterMetadata cannot be null"); + Dbg.Assert(cmdParameterMetadata is not null, "cmdParameterMetadata cannot be null"); Dictionary result = new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -696,7 +696,7 @@ internal static Dictionary GetParameterMetadata(Merge internal bool IsMatchingType(PSTypeName psTypeName) { Type dotNetType = psTypeName.Type; - if (dotNetType != null) + if (dotNetType is not null) { // ConstrainedLanguage note - This conversion is analyzed, but actually invoked via regular conversion. bool parameterAcceptsObjects = @@ -709,12 +709,12 @@ internal bool IsMatchingType(PSTypeName psTypeName) if (parameterAcceptsObjects) { - return (psTypeName.Type != null) && (psTypeName.Type.Equals(typeof(object))); + return (psTypeName.Type is not null) && (psTypeName.Type.Equals(typeof(object))); } // ConstrainedLanguage note - This conversion is analyzed, but actually invoked via regular conversion. var conversionData = LanguagePrimitives.FigureConversion(dotNetType, this.ParameterType); - if (conversionData != null) + if (conversionData is not null) { if ((int)(conversionData.Rank) >= (int)(ConversionRank.NumericImplicitS2A)) { @@ -738,10 +738,10 @@ internal bool IsMatchingType(PSTypeName psTypeName) return true; } - if (this.Attributes != null) + if (this.Attributes is not null) { PSTypeNameAttribute typeNameAttribute = this.Attributes.OfType().FirstOrDefault(); - if (typeNameAttribute != null && wildcardPattern.IsMatch(typeNameAttribute.PSTypeName)) + if (typeNameAttribute is not null && wildcardPattern.IsMatch(typeNameAttribute.PSTypeName)) { return true; } @@ -792,7 +792,7 @@ internal string GetProxyParameterData(string prefix, string paramNameOverride, b { Text.StringBuilder result = new System.Text.StringBuilder(); - if (_parameterSets != null && isProxyForCmdlet) + if (_parameterSets is not null && isProxyForCmdlet) { foreach (var pair in _parameterSets) { @@ -824,7 +824,7 @@ internal string GetProxyParameterData(string prefix, string paramNameOverride, b } } - if ((_aliases != null) && (_aliases.Count > 0)) + if ((_aliases is not null) && (_aliases.Count > 0)) { Text.StringBuilder aliasesData = new System.Text.StringBuilder(); string comma = string.Empty; // comma is not need for the first element @@ -842,7 +842,7 @@ internal string GetProxyParameterData(string prefix, string paramNameOverride, b result.AppendFormat(CultureInfo.InvariantCulture, AliasesFormat, prefix, aliasesData.ToString()); } - if ((_attributes != null) && (_attributes.Count > 0)) + if ((_attributes is not null) && (_attributes.Count > 0)) { foreach (Attribute attrib in _attributes) { @@ -858,7 +858,7 @@ internal string GetProxyParameterData(string prefix, string paramNameOverride, b { result.AppendFormat(CultureInfo.InvariantCulture, ParameterTypeFormat, prefix, "switch"); } - else if (_parameterType != null) + else if (_parameterType is not null) { result.AppendFormat(CultureInfo.InvariantCulture, ParameterTypeFormat, prefix, ToStringCodeMethods.Type(_parameterType)); } @@ -866,7 +866,7 @@ internal string GetProxyParameterData(string prefix, string paramNameOverride, b /* 1. CredentialAttribute needs to go after the type * 2. To avoid risk, I don't want to move other attributes to go here / after the type */ CredentialAttribute credentialAttrib = _attributes.OfType().FirstOrDefault(); - if (credentialAttrib != null) + if (credentialAttrib is not null) { string attribData = string.Format(CultureInfo.InvariantCulture, CredentialAttributeFormat, prefix); if (!string.IsNullOrEmpty(attribData)) @@ -900,7 +900,7 @@ private string GetProxyAttributeData(Attribute attrib, string prefix) string result; ValidateLengthAttribute validLengthAttrib = attrib as ValidateLengthAttribute; - if (validLengthAttrib != null) + if (validLengthAttrib is not null) { result = string.Format( CultureInfo.InvariantCulture, @@ -911,7 +911,7 @@ private string GetProxyAttributeData(Attribute attrib, string prefix) } ValidateRangeAttribute validRangeAttrib = attrib as ValidateRangeAttribute; - if (validRangeAttrib != null) + if (validRangeAttrib is not null) { if (validRangeAttrib.RangeKind.HasValue) { @@ -947,7 +947,7 @@ private string GetProxyAttributeData(Attribute attrib, string prefix) } AllowNullAttribute allowNullAttrib = attrib as AllowNullAttribute; - if (allowNullAttrib != null) + if (allowNullAttrib is not null) { result = string.Format(CultureInfo.InvariantCulture, AllowNullFormat, prefix); @@ -955,7 +955,7 @@ private string GetProxyAttributeData(Attribute attrib, string prefix) } AllowEmptyStringAttribute allowEmptyStringAttrib = attrib as AllowEmptyStringAttribute; - if (allowEmptyStringAttrib != null) + if (allowEmptyStringAttrib is not null) { result = string.Format(CultureInfo.InvariantCulture, AllowEmptyStringFormat, prefix); @@ -963,7 +963,7 @@ private string GetProxyAttributeData(Attribute attrib, string prefix) } AllowEmptyCollectionAttribute allowEmptyColAttrib = attrib as AllowEmptyCollectionAttribute; - if (allowEmptyColAttrib != null) + if (allowEmptyColAttrib is not null) { result = string.Format(CultureInfo.InvariantCulture, AllowEmptyCollectionFormat, prefix); @@ -971,7 +971,7 @@ private string GetProxyAttributeData(Attribute attrib, string prefix) } ValidatePatternAttribute patternAttrib = attrib as ValidatePatternAttribute; - if (patternAttrib != null) + if (patternAttrib is not null) { /* TODO: Validate Pattern dont support Options in ScriptCmdletText. StringBuilder regexOps = new System.Text.StringBuilder(); @@ -1002,7 +1002,7 @@ private string GetProxyAttributeData(Attribute attrib, string prefix) } ValidateCountAttribute countAttrib = attrib as ValidateCountAttribute; - if (countAttrib != null) + if (countAttrib is not null) { result = string.Format(CultureInfo.InvariantCulture, ValidateCountFormat, prefix, countAttrib.MinLength, countAttrib.MaxLength); @@ -1010,7 +1010,7 @@ private string GetProxyAttributeData(Attribute attrib, string prefix) } ValidateNotNullAttribute notNullAttrib = attrib as ValidateNotNullAttribute; - if (notNullAttrib != null) + if (notNullAttrib is not null) { result = string.Format(CultureInfo.InvariantCulture, ValidateNotNullFormat, prefix); @@ -1018,7 +1018,7 @@ private string GetProxyAttributeData(Attribute attrib, string prefix) } ValidateNotNullOrEmptyAttribute notNullEmptyAttrib = attrib as ValidateNotNullOrEmptyAttribute; - if (notNullEmptyAttrib != null) + if (notNullEmptyAttrib is not null) { result = string.Format(CultureInfo.InvariantCulture, ValidateNotNullOrEmptyFormat, prefix); @@ -1026,7 +1026,7 @@ private string GetProxyAttributeData(Attribute attrib, string prefix) } ValidateSetAttribute setAttrib = attrib as ValidateSetAttribute; - if (setAttrib != null) + if (setAttrib is not null) { Text.StringBuilder values = new System.Text.StringBuilder(); string comma = string.Empty; @@ -1046,7 +1046,7 @@ private string GetProxyAttributeData(Attribute attrib, string prefix) } ValidateScriptAttribute scriptAttrib = attrib as ValidateScriptAttribute; - if (scriptAttrib != null) + if (scriptAttrib is not null) { // Talked with others and I think it is okay to use *unescaped* value from sb.ToString() // 1. implicit remoting is not bringing validation scripts across @@ -1058,7 +1058,7 @@ private string GetProxyAttributeData(Attribute attrib, string prefix) } PSTypeNameAttribute psTypeNameAttrib = attrib as PSTypeNameAttribute; - if (psTypeNameAttrib != null) + if (psTypeNameAttrib is not null) { result = string.Format( CultureInfo.InvariantCulture, @@ -1069,7 +1069,7 @@ private string GetProxyAttributeData(Attribute attrib, string prefix) } ObsoleteAttribute obsoleteAttrib = attrib as ObsoleteAttribute; - if (obsoleteAttrib != null) + if (obsoleteAttrib is not null) { string parameters = string.Empty; if (obsoleteAttrib.IsError) @@ -1077,7 +1077,7 @@ private string GetProxyAttributeData(Attribute attrib, string prefix) string message = "'" + CodeGeneration.EscapeSingleQuotedStringContent(obsoleteAttrib.Message) + "'"; parameters = message + ", $true"; } - else if (obsoleteAttrib.Message != null) + else if (obsoleteAttrib.Message is not null) { parameters = "'" + CodeGeneration.EscapeSingleQuotedStringContent(obsoleteAttrib.Message) + "'"; } @@ -1173,7 +1173,7 @@ internal static InternalParameterMetadata Get(Type type, ExecutionContext contex { result = new InternalParameterMetadata(type, processingDynamicParameters); - if (context != null) + if (context is not null) { s_parameterMetadataCache.TryAdd(type.AssemblyQualifiedName, result); } @@ -1305,7 +1305,7 @@ private void ConstructCompiledParametersUsingRuntimeDefinedParameters( bool checkNames) { Diagnostics.Assert( - runtimeDefinedParameters != null, + runtimeDefinedParameters is not null, "This method should only be called when constructed with a valid runtime-defined parameter collection"); foreach (RuntimeDefinedParameter parameterDefinition in runtimeDefinedParameters.Values) @@ -1336,7 +1336,7 @@ private void ConstructCompiledParametersUsingRuntimeDefinedParameters( private void ConstructCompiledParametersUsingReflection(bool processingDynamicParameters) { Diagnostics.Assert( - _type != null, + _type is not null, "This method should only be called when constructed with the Type"); // Get the property and field info @@ -1501,7 +1501,7 @@ private static bool IsMemberAParameter(MemberInfo member) try { var expAttribute = member.GetCustomAttributes(inherit: false).FirstOrDefault(); - if (expAttribute != null && expAttribute.ToHide) { return false; } + if (expAttribute is not null && expAttribute.ToHide) { return false; } var hasAnyVisibleParamAttributes = false; var paramAttributes = member.GetCustomAttributes(inherit: false); diff --git a/src/System.Management.Automation/engine/TypeTable.cs b/src/System.Management.Automation/engine/TypeTable.cs index ad9700f69e1..6c95846b2e7 100644 --- a/src/System.Management.Automation/engine/TypeTable.cs +++ b/src/System.Management.Automation/engine/TypeTable.cs @@ -188,7 +188,7 @@ private ScriptBlock GetScriptBlock(string text, int initialLine) return null; } - if (scriptBlock != null) + if (scriptBlock is not null) { if (_context.IsFullyTrusted) { @@ -203,7 +203,7 @@ private Type ResolveType(string typeName, int line) { Exception exception; var type = TypeResolver.ResolveType(typeName, out exception); - if (exception != null) + if (exception is not null) { _context.AddError(line, exception.Message); } @@ -257,7 +257,7 @@ private bool BoolConverter(object value, string name) private void CheckStandardNote(TypeMemberData member, TypeData typeData, Action setter, Func converter) { var note = member as NotePropertyData; - if (note != null) + if (note is not null) { T value; if (note.Value.GetType() != typeof(T)) @@ -280,7 +280,7 @@ private void CheckStandardNote(TypeMemberData member, TypeData typeData, Acti private bool CheckStandardPropertySet(TypeMemberData member, TypeData typeData, Action setter) { var propertySet = member as PropertySetData; - if (propertySet != null) + if (propertySet is not null) { setter(typeData, propertySet); return true; @@ -329,7 +329,7 @@ private IEnumerable Read_Types() if ((object)_reader.LocalName == (object)_idType) { var p = Read_Type(); - if (p != null) + if (p is not null) { yield return p; } @@ -377,7 +377,7 @@ private TypeData Read_Type() { if ((object)_reader.LocalName == (object)_idName) { - if (name != null) + if (name is not null) { NotMoreThanOnce(_idName, _idType); } @@ -386,7 +386,7 @@ private TypeData Read_Type() } else if ((object)_reader.LocalName == (object)_idMembers) { - if (members != null) + if (members is not null) { NotMoreThanOnce(_idMembers, _idType); } @@ -395,7 +395,7 @@ private TypeData Read_Type() } else if ((object)_reader.LocalName == (object)_idTypeConverter) { - if (typeConverter != null) + if (typeConverter is not null) { NotMoreThanOnce(_idTypeConverter, _idType); } @@ -404,7 +404,7 @@ private TypeData Read_Type() } else if ((object)_reader.LocalName == (object)_idTypeAdapter) { - if (typeAdapter != null) + if (typeAdapter is not null) { NotMoreThanOnce(_idTypeAdapter, _idType); } @@ -442,7 +442,7 @@ private TypeData Read_Type() } var typeData = new TypeData(name, true); - if (members != null) + if (members is not null) { foreach (var m in members) { @@ -453,7 +453,7 @@ private TypeData Read_Type() typeData.TypeAdapter = typeAdapter; typeData.TypeConverter = typeConverter; - if (standardMembers != null) + if (standardMembers is not null) { foreach (var m in standardMembers.Members) { @@ -486,7 +486,7 @@ private TypeData Read_Type() else if (m.Name.Equals(TypeTable.StringSerializationSource, StringComparison.OrdinalIgnoreCase)) { var aliasData = m as AliasPropertyData; - if (aliasData != null) + if (aliasData is not null) { typeData.StringSerializationSource = aliasData.ReferencedMemberName; } @@ -544,7 +544,7 @@ private Type Read_TypeX(string elementName) { if ((object)_reader.LocalName == (object)_idTypeName) { - if (typeName != null) + if (typeName is not null) { NotMoreThanOnce(_idTypeName, elementName); } @@ -605,7 +605,7 @@ private Collection Read_Members(out MemberSetData standardMember if ((object)_reader.LocalName == (object)_idNoteProperty) { var p = Read_NoteProperty(); - if (p != null) + if (p is not null) { members.Add(p); } @@ -613,7 +613,7 @@ private Collection Read_Members(out MemberSetData standardMember else if ((object)_reader.LocalName == (object)_idAliasProperty) { var p = Read_AliasProperty(); - if (p != null) + if (p is not null) { members.Add(p); } @@ -621,7 +621,7 @@ private Collection Read_Members(out MemberSetData standardMember else if ((object)_reader.LocalName == (object)_idScriptProperty) { var p = Read_ScriptProperty(); - if (p != null) + if (p is not null) { members.Add(p); } @@ -629,7 +629,7 @@ private Collection Read_Members(out MemberSetData standardMember else if ((object)_reader.LocalName == (object)_idCodeProperty) { var p = Read_CodeProperty(); - if (p != null) + if (p is not null) { members.Add(p); } @@ -637,7 +637,7 @@ private Collection Read_Members(out MemberSetData standardMember else if ((object)_reader.LocalName == (object)_idScriptMethod) { var p = Read_ScriptMethod(); - if (p != null) + if (p is not null) { members.Add(p); } @@ -645,7 +645,7 @@ private Collection Read_Members(out MemberSetData standardMember else if ((object)_reader.LocalName == (object)_idCodeMethod) { var p = Read_CodeMethod(); - if (p != null) + if (p is not null) { members.Add(p); } @@ -653,7 +653,7 @@ private Collection Read_Members(out MemberSetData standardMember else if ((object)_reader.LocalName == (object)_idPropertySet) { var p = Read_PropertySet(); - if (p != null) + if (p is not null) { members.Add(p); } @@ -661,7 +661,7 @@ private Collection Read_Members(out MemberSetData standardMember else if ((object)_reader.LocalName == (object)_idMemberSet) { var p = Read_MemberSet(); - if (p != null) + if (p is not null) { if (p.Name.Equals(TypeTable.PSStandardMembers, StringComparison.OrdinalIgnoreCase)) { @@ -717,7 +717,7 @@ private MemberSetData Read_MemberSet() { if ((object)_reader.LocalName == (object)_idName) { - if (name != null) + if (name is not null) { NotMoreThanOnce(_idName, _idMemberSet); } @@ -735,14 +735,14 @@ private MemberSetData Read_MemberSet() } else if ((object)_reader.LocalName == (object)_idMembers) { - if (members != null) + if (members is not null) { NotMoreThanOnce(_idMembers, _idMemberSet); } MemberSetData standardMembers; members = Read_Members(out standardMembers); - if (standardMembers != null) + if (standardMembers is not null) { // Somewhat pointless - but if we see PSStandardMembers inside a memberset, it's // really just another ordinary member. @@ -818,7 +818,7 @@ private PropertySetData Read_PropertySet() { if ((object)_reader.LocalName == (object)_idName) { - if (name != null) + if (name is not null) { NotMoreThanOnce(_idName, _idPropertySet); } @@ -922,7 +922,7 @@ private CodeMethodData Read_CodeMethod() { if ((object)_reader.LocalName == (object)_idName) { - if (name != null) + if (name is not null) { NotMoreThanOnce(_idName, _idCodeMethod); } @@ -931,7 +931,7 @@ private CodeMethodData Read_CodeMethod() } else if ((object)_reader.LocalName == (object)_idCodeReference) { - if (codeReference != null) + if (codeReference is not null) { NotMoreThanOnce(_idCodeReference, _idCodeMethod); } @@ -961,7 +961,7 @@ private CodeMethodData Read_CodeMethod() NodeNotFound(lineNumber, _idName, _idCodeMethod); if (codeReference is null && methodLineNumber == 0) NodeNotFound(lineNumber, _idCodeReference, _idCodeMethod); - if (codeReference != null && !PSCodeMethod.CheckMethodInfo(codeReference)) + if (codeReference is not null && !PSCodeMethod.CheckMethodInfo(codeReference)) _context.AddError(methodLineNumber, ExtendedTypeSystem.CodeMethodMethodFormat); if (_context.errors.Count != errorCount) @@ -998,7 +998,7 @@ private MethodInfo Read_CodeReference() { if ((object)_reader.LocalName == (object)_idTypeName) { - if (typeName != null) + if (typeName is not null) { NotMoreThanOnce(_idTypeName, _idCodeReference); } @@ -1008,7 +1008,7 @@ private MethodInfo Read_CodeReference() } else if ((object)_reader.LocalName == (object)_idMethodName) { - if (methodName != null) + if (methodName is not null) { NotMoreThanOnce(_idMethodName, _idCodeReference); } @@ -1044,7 +1044,7 @@ private MethodInfo Read_CodeReference() MethodInfo member = null; var type = ResolveType(typeName, typeLineNumber); - if (type != null) + if (type is not null) { try { @@ -1084,7 +1084,7 @@ private ScriptMethodData Read_ScriptMethod() { if ((object)_reader.LocalName == (object)_idName) { - if (name != null) + if (name is not null) { NotMoreThanOnce(_idName, _idScriptMethod); } @@ -1093,7 +1093,7 @@ private ScriptMethodData Read_ScriptMethod() } else if ((object)_reader.LocalName == (object)_idScript) { - if (script != null) + if (script is not null) { NotMoreThanOnce(_idScript, _idScriptMethod); } @@ -1164,7 +1164,7 @@ private CodePropertyData Read_CodeProperty() { if ((object)_reader.LocalName == (object)_idName) { - if (name != null) + if (name is not null) { NotMoreThanOnce(_idName, _idCodeProperty); } @@ -1173,7 +1173,7 @@ private CodePropertyData Read_CodeProperty() } else if ((object)_reader.LocalName == (object)_idGetCodeReference) { - if (getter != null) + if (getter is not null) { NotMoreThanOnce(_idGetCodeReference, _idCodeProperty); } @@ -1187,7 +1187,7 @@ private CodePropertyData Read_CodeProperty() } else if ((object)_reader.LocalName == (object)_idSetCodeReference) { - if (setter != null) + if (setter is not null) { NotMoreThanOnce(_idSetCodeReference, _idCodeProperty); } @@ -1225,12 +1225,12 @@ private CodePropertyData Read_CodeProperty() _context.AddError(lineNumber, TypesXmlStrings.CodePropertyShouldHaveGetterOrSetter); } - if (getter != null && !PSCodeProperty.CheckGetterMethodInfo(getter)) + if (getter is not null && !PSCodeProperty.CheckGetterMethodInfo(getter)) { _context.AddError(getterLineNumber, ExtendedTypeSystem.CodePropertyGetterFormat); } - if (setter != null && !PSCodeProperty.CheckSetterMethodInfo(setter, getter)) + if (setter is not null && !PSCodeProperty.CheckSetterMethodInfo(setter, getter)) { _context.AddError(setterLineNumber, ExtendedTypeSystem.CodePropertySetterFormat); } @@ -1273,7 +1273,7 @@ private ScriptPropertyData Read_ScriptProperty() { if ((object)_reader.LocalName == (object)_idName) { - if (name != null) + if (name is not null) { NotMoreThanOnce(_idName, _idScriptProperty); } @@ -1282,7 +1282,7 @@ private ScriptPropertyData Read_ScriptProperty() } else if ((object)_reader.LocalName == (object)_idGetScriptBlock) { - if (getScriptBlock != null) + if (getScriptBlock is not null) { NotMoreThanOnce(_idGetScriptBlock, _idScriptProperty); } @@ -1292,7 +1292,7 @@ private ScriptPropertyData Read_ScriptProperty() } else if ((object)_reader.LocalName == (object)_idSetScriptBlock) { - if (setScriptBlock != null) + if (setScriptBlock is not null) { NotMoreThanOnce(_idSetScriptBlock, _idScriptProperty); } @@ -1366,7 +1366,7 @@ private AliasPropertyData Read_AliasProperty() { if ((object)_reader.LocalName == (object)_idName) { - if (name != null) + if (name is not null) { NotMoreThanOnce(_idName, _idAliasProperty); } @@ -1375,7 +1375,7 @@ private AliasPropertyData Read_AliasProperty() } else if ((object)_reader.LocalName == (object)_idReferencedMemberName) { - if (referencedMemberName != null) + if (referencedMemberName is not null) { NotMoreThanOnce(_idReferencedMemberName, _idAliasProperty); } @@ -1384,7 +1384,7 @@ private AliasPropertyData Read_AliasProperty() } else if ((object)_reader.LocalName == (object)_idTypeName) { - if (typeName != null) + if (typeName is not null) { NotMoreThanOnce(_idTypeName, _idAliasProperty); } @@ -1418,7 +1418,7 @@ private AliasPropertyData Read_AliasProperty() NodeNotFound(lineNumber, _idReferencedMemberName, _idAliasProperty); } - Type convertToType = (typeName != null) ? ResolveType(typeName, typeLineNumber) : null; + Type convertToType = (typeName is not null) ? ResolveType(typeName, typeLineNumber) : null; if (_context.errors.Count != errorCount) { @@ -1457,7 +1457,7 @@ private NotePropertyData Read_NoteProperty() { if ((object)_reader.LocalName == (object)_idName) { - if (name != null) + if (name is not null) { NotMoreThanOnce(_idName, _idNoteProperty); } @@ -1466,7 +1466,7 @@ private NotePropertyData Read_NoteProperty() } else if ((object)_reader.LocalName == (object)_idValue) { - if (valueAsString != null) + if (valueAsString is not null) { NotMoreThanOnce(_idValue, _idNoteProperty); } @@ -1475,7 +1475,7 @@ private NotePropertyData Read_NoteProperty() } else if ((object)_reader.LocalName == (object)_idTypeName) { - if (typeName != null) + if (typeName is not null) { NotMoreThanOnce(_idTypeName, _idNoteProperty); } @@ -1510,8 +1510,8 @@ private NotePropertyData Read_NoteProperty() } object value = valueAsString; - Type convertToType = (typeName != null) ? ResolveType(typeName, typeLineNumber) : null; - if (convertToType != null) + Type convertToType = (typeName is not null) ? ResolveType(typeName, typeLineNumber) : null; + if (convertToType is not null) { try { @@ -1849,7 +1849,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont base.GetObjectData(info, context); // If there are simple fields, serialize them with info.AddValue - if (_errors != null) + if (_errors is not null) { int errorCount = _errors.Count; info.AddValue("ErrorCount", errorCount); @@ -2134,7 +2134,7 @@ public string StringSerializationSource // If we set the standard member via StringSerializationSourceProperty, we // don't want to remove it, so only remove the member if our previous // backing field was not null. - if (_stringSerializationSource != null) + if (_stringSerializationSource is not null) { StandardMembers.Remove(TypeTable.StringSerializationSource); } @@ -2144,7 +2144,7 @@ public string StringSerializationSource } _stringSerializationSource = value; - if (_stringSerializationSourceProperty != null) + if (_stringSerializationSourceProperty is not null) { // Remove existing property StandardMembers.Remove(TypeTable.StringSerializationSource); @@ -2182,7 +2182,7 @@ public TypeMemberData StringSerializationSourceProperty // If we set the standard member via StringSerializationSource, we // don't want to remove it, so only remove the member if our previous // backing field was not null. - if (_stringSerializationSourceProperty != null) + if (_stringSerializationSourceProperty is not null) { StandardMembers.Remove(TypeTable.StringSerializationSource); } @@ -2219,7 +2219,7 @@ public PropertySetData DefaultDisplayPropertySet set { _defaultDisplayPropertySet = value; - if (_defaultDisplayPropertySet != null) + if (_defaultDisplayPropertySet is not null) { _defaultDisplayPropertySet.Name = TypeTable.DefaultDisplayPropertySet; } @@ -2239,7 +2239,7 @@ public PropertySetData DefaultKeyPropertySet set { _defaultKeyPropertySet = value; - if (_defaultKeyPropertySet != null) + if (_defaultKeyPropertySet is not null) { _defaultKeyPropertySet.Name = TypeTable.DefaultKeyPropertySet; } @@ -2259,7 +2259,7 @@ public PropertySetData PropertySerializationSet set { _propertySerializationSet = value; - if (_propertySerializationSet != null) + if (_propertySerializationSet is not null) { _propertySerializationSet.Name = TypeTable.PropertySerializationSet; } @@ -2922,7 +2922,7 @@ private static void AddMember(ConcurrentBag errors, string typeName, PSM return; } - if (membersCollection[member.name] != null && !isOverride) + if (membersCollection[member.name] is not null && !isOverride) { AddError(errors, typeName, TypesXmlStrings.DuplicateMember, member.name); return; @@ -2970,7 +2970,7 @@ private static bool GetCheckNote(ConcurrentBag errors, string typeName, if (noteType.GetTypeCode().Equals(TypeCode.Boolean)) { string sourceValueAsString = sourceValue as string; - if (sourceValueAsString != null) + if (sourceValueAsString is not null) { if (sourceValueAsString.Length == 0) { @@ -3096,7 +3096,7 @@ private static bool CheckStandardMembers(ConcurrentBag errors, string ty } SerializationMethod serializationMethod = SerializationMethod.AllPublicProperties; - if (serializationMethodNote != null) + if (serializationMethodNote is not null) { serializationMethod = (SerializationMethod)serializationMethodNote.Value; } @@ -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 is not null && inheritPropertiesNote.Value.Equals(false) && propertySerializationSet is null) { AddError( errors, @@ -3226,7 +3226,7 @@ private static bool CheckStandardMembers(ConcurrentBag errors, string ty } else { - if (targetTypeForDeserialization != null) + if (targetTypeForDeserialization is not null) { // GetCheckNote converts the value from string to System.Type.. We should store value as Type // as this will save time spent converting string to Type. @@ -3269,7 +3269,7 @@ private static bool CreateInstance(ConcurrentBag errors, string typeName } #pragma warning restore 56500 - if (instanceException != null) + if (instanceException is not null) { AddError(errors, typeName, errorFormatString, type.FullName, instanceException.Message); return false; @@ -3623,7 +3623,7 @@ private static void ProcessTypeConverter( } } - if (instance != null && !typeConverters.TryAdd(typeName, instance)) + if (instance is not null && !typeConverters.TryAdd(typeName, instance)) { if (!isOverride) { @@ -3663,7 +3663,7 @@ private static void ProcessTypeAdapter( } } - if (adapterSet != null && !typeAdapters.TryAdd(typeName, adapterSet)) + if (adapterSet is not null && !typeAdapters.TryAdd(typeName, adapterSet)) { if (!isOverride) { @@ -3680,17 +3680,17 @@ private void ProcessTypeDataToAdd(ConcurrentBag errors, TypeData typeDat Dbg.Assert(!string.IsNullOrEmpty(typeName), "TypeData class guarantees the typeName is not null and not empty"); var propertySets = new Collection(); - if (typeData.DefaultDisplayPropertySet != null) + if (typeData.DefaultDisplayPropertySet is not null) { propertySets.Add(typeData.DefaultDisplayPropertySet); } - if (typeData.DefaultKeyPropertySet != null) + if (typeData.DefaultKeyPropertySet is not null) { propertySets.Add(typeData.DefaultKeyPropertySet); } - if (typeData.PropertySerializationSet != null) + if (typeData.PropertySerializationSet is not null) { propertySets.Add(typeData.PropertySerializationSet); } @@ -3728,12 +3728,12 @@ private void ProcessTypeDataToAdd(ConcurrentBag errors, TypeData typeDat ProcessStandardMembers(errors, typeName, typeData.StandardMembers.Values, propertySets, typeMembers, typeData.IsOverride); } - if (typeData.TypeConverter != null) + if (typeData.TypeConverter is not null) { ProcessTypeConverter(errors, typeName, typeData.TypeConverter, _typeConverters, typeData.IsOverride); } - if (typeData.TypeAdapter != null) + if (typeData.TypeAdapter is not null) { ProcessTypeAdapter(errors, typeName, typeData.TypeAdapter, _typeAdapters, typeData.IsOverride); } @@ -3796,7 +3796,7 @@ private void Update(LoadContext context) { var xs = new TypesPs1xmlReader(context); var types = xs.Read(); - if (types != null) + if (types is not null) { foreach (var t in types) { @@ -4151,19 +4151,19 @@ internal PSObject.AdapterSet GetTypeAdapter(Type type) private TypeMemberData GetTypeMemberDataFromPSMemberInfo(PSMemberInfo member) { var note = member as PSNoteProperty; - if (note != null) + if (note is not null) { return new NotePropertyData(note.Name, note.Value); } var alias = member as PSAliasProperty; - if (alias != null) + if (alias is not null) { return new AliasPropertyData(alias.Name, alias.ReferencedMemberName); } var scriptProperty = member as PSScriptProperty; - if (scriptProperty != null) + if (scriptProperty is not null) { ScriptBlock getter = scriptProperty.IsGettable ? scriptProperty.GetterScript : null; ScriptBlock setter = scriptProperty.IsSettable ? scriptProperty.SetterScript : null; @@ -4171,7 +4171,7 @@ private TypeMemberData GetTypeMemberDataFromPSMemberInfo(PSMemberInfo member) } var codeProperty = member as PSCodeProperty; - if (codeProperty != null) + if (codeProperty is not null) { MethodInfo getter = codeProperty.IsGettable ? codeProperty.GetterCodeReference : null; MethodInfo setter = codeProperty.IsSettable ? codeProperty.SetterCodeReference : null; @@ -4179,19 +4179,19 @@ private TypeMemberData GetTypeMemberDataFromPSMemberInfo(PSMemberInfo member) } var scriptMethod = member as PSScriptMethod; - if (scriptMethod != null) + if (scriptMethod is not null) { return new ScriptMethodData(scriptMethod.Name, scriptMethod.Script); } var codeMethod = member as PSCodeMethod; - if (codeMethod != null) + if (codeMethod is not null) { return new CodeMethodData(codeMethod.Name, codeMethod.CodeReference); } var memberSet = member as PSMemberSet; - if (memberSet != null) + if (memberSet is not null) { if (memberSet.Name.Equals(PSStandardMembers, StringComparison.OrdinalIgnoreCase)) { @@ -4217,18 +4217,18 @@ private TypeMemberData GetTypeMemberDataFromPSMemberInfo(PSMemberInfo member) /// private void LoadMembersToTypeData(PSMemberInfo member, TypeData typeData) { - Dbg.Assert(member != null, "caller should guarantee that member is not null"); - Dbg.Assert(typeData != null, "caller should guarantee that typeData is not null"); + Dbg.Assert(member is not null, "caller should guarantee that member is not null"); + Dbg.Assert(typeData is not null, "caller should guarantee that typeData is not null"); var memberData = GetTypeMemberDataFromPSMemberInfo(member); - if (memberData != null) + if (memberData is not null) { typeData.Members.Add(memberData.Name, memberData); return; } var memberSet = member as PSMemberSet; - if (memberSet != null) + if (memberSet is not null) { if (memberSet.Name.Equals(PSStandardMembers, StringComparison.OrdinalIgnoreCase)) { @@ -4284,7 +4284,7 @@ private void LoadStandardMembersToTypeData(PSMemberSet memberSet, TypeData typeD else if (memberName.Equals(StringSerializationSource, StringComparison.OrdinalIgnoreCase)) { var aliasProperty = standardMember as PSAliasProperty; - if (aliasProperty != null) + if (aliasProperty is not null) { typeData.StringSerializationSource = aliasProperty.ReferencedMemberName; } @@ -4377,13 +4377,13 @@ internal Dictionary GetAllTypeData() private bool RetrieveMembersToTypeData(TypeData typeData) { - Dbg.Assert(typeData != null && typeData.TypeName != null, "The caller needs to make sure typeData != null"); + Dbg.Assert(typeData is not null && typeData.TypeName is not null, "The caller needs to make sure typeData is not null"); string typeName = typeData.TypeName; PSMemberInfoInternalCollection typeMembers; if (_extendedMembers.TryGetValue(typeName, out typeMembers)) { - Dbg.Assert(typeMembers != null, "members should not be null"); + Dbg.Assert(typeMembers is not null, "members should not be null"); foreach (PSMemberInfo member in typeMembers) { PSMemberInfo newMember = member.Copy(); @@ -4398,13 +4398,13 @@ private bool RetrieveMembersToTypeData(TypeData typeData) private bool RetrieveConverterToTypeData(TypeData typeData) { - Dbg.Assert(typeData != null && typeData.TypeName != null, "The caller needs to make sure typeData != null"); + Dbg.Assert(typeData is not null && typeData.TypeName is not null, "The caller needs to make sure typeData is not null"); string typeName = typeData.TypeName; object converterResult; if (_typeConverters.TryGetValue(typeName, out converterResult)) { - Dbg.Assert(converterResult != null, "converter should not be null"); + Dbg.Assert(converterResult is not null, "converter should not be null"); typeData.TypeConverter = converterResult.GetType(); return true; } @@ -4414,13 +4414,13 @@ private bool RetrieveConverterToTypeData(TypeData typeData) private bool RetrieveAdapterToTypeData(TypeData typeData) { - Dbg.Assert(typeData != null && typeData.TypeName != null, "The caller needs to make sure typeData != null"); + Dbg.Assert(typeData is not null && typeData.TypeName is not null, "The caller needs to make sure typeData is not null"); string typeName = typeData.TypeName; PSObject.AdapterSet adapterResult; if (_typeAdapters.TryGetValue(typeName, out adapterResult)) { - Dbg.Assert(adapterResult != null, "adapter should not be null"); + Dbg.Assert(adapterResult is not null, "adapter should not be null"); typeData.TypeAdapter = ((ThirdPartyAdapter)(adapterResult.OriginalAdapter)).ExternalAdapterType; return true; } @@ -4607,7 +4607,7 @@ private string GetModuleContents( } // Check authorization. - if (authorizationManager != null) + if (authorizationManager is not null) { try { @@ -4769,7 +4769,7 @@ internal void Update( var fileContents = GetModuleContents(moduleName, filePath, errors, authorizationManager, host, out isFullyTrusted, out failToLoadFile, out isProductCode); - if (fileContents != null) + if (fileContents is not null) { UpdateWithModuleContents(fileContents, moduleName, filePath, isFullyTrusted, isProductCode, errors); } diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index aeb6abe527a..90928db5210 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -426,7 +426,7 @@ internal static TypeTable GetTypeTableFromExecutionContextTLS() internal static string GetApplicationBaseFromRegistry(string shellId) { bool wantPsHome = (object)shellId == (object)DefaultPowerShellShellID; - if (wantPsHome && s_pshome != null) + if (wantPsHome && s_pshome is not null) return s_pshome; string engineKeyPath = RegistryStrings.MonadRootKeyPath + "\\" + @@ -434,7 +434,7 @@ internal static string GetApplicationBaseFromRegistry(string shellId) using (RegistryKey engineKey = Registry.LocalMachine.OpenSubKey(engineKeyPath)) { - if (engineKey != null) + if (engineKey is not null) { var result = engineKey.GetValue(RegistryStrings.MonadEngine_ApplicationBase) as string; result = Environment.ExpandEnvironmentVariables(result); @@ -463,7 +463,7 @@ internal static string GetWindowsPowerShellVersionFromRegistry() return InternalTestHooks.TestWindowsPowerShellVersionString; } - if (s_windowsPowerShellVersion != null) + if (s_windowsPowerShellVersion is not null) { return s_windowsPowerShellVersion; } @@ -473,7 +473,7 @@ internal static string GetWindowsPowerShellVersionFromRegistry() using (RegistryKey engineKey = Registry.LocalMachine.OpenSubKey(engineKeyPath)) { - if (engineKey != null) + if (engineKey is not null) { s_windowsPowerShellVersion = engineKey.GetValue(RegistryStrings.MonadEngine_MonadVersion) as string; return s_windowsPowerShellVersion; @@ -569,14 +569,14 @@ internal static bool IsWinPEHost() // HKLM\System\CurrentControlSet\Control\MiniNT winPEKey = Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\Control\MiniNT"); - return winPEKey != null; + return winPEKey is not null; } catch (ArgumentException) { } catch (SecurityException) { } catch (ObjectDisposedException) { } finally { - if (winPEKey != null) + if (winPEKey is not null) { winPEKey.Dispose(); } @@ -755,7 +755,7 @@ internal static bool IsValidPSEditionValue(string editionValue) // On Windows, group policy settings from registry take precedence. // If the requested policy is not defined in registry, we query the configuration file. policy = GetPolicySettingFromGPO(preferenceOrder); - if (policy != null) { return policy; } + if (policy is not null) { return policy; } #endif policy = GetPolicySettingFromConfigFile(preferenceOrder); return policy; @@ -785,7 +785,7 @@ internal static bool IsValidPSEditionValue(string editionValue) } } - if (policies != null) + if (policies is not null) { PolicyBase result = null; switch (typeof(T).Name) @@ -816,7 +816,7 @@ internal static bool IsValidPSEditionValue(string editionValue) break; } - if (result != null) { return (T)result; } + if (result is not null) { return (T)result; } } } @@ -870,7 +870,7 @@ private static bool TrySetPolicySettingsFromRegistryKey(object instance, Type in var subKeyNameSet = subKeyNames.Length > 0 ? new HashSet(subKeyNames, StringComparer.OrdinalIgnoreCase) : null; // If there are any values or subkeys in the registry key - read them into the policy instance object - if ((valueNameSet != null) || (subKeyNameSet != null)) + if ((valueNameSet is not null) || (subKeyNameSet is not null)) { foreach (var property in properties) { @@ -878,15 +878,15 @@ private static bool TrySetPolicySettingsFromRegistryKey(object instance, Type in object rawRegistryValue = null; // Get the raw value from registry. - if (valueNameSet != null && valueNameSet.Contains(settingName)) + if (valueNameSet is not null && valueNameSet.Contains(settingName)) { rawRegistryValue = gpoKey.GetValue(settingName); } - else if (subKeyNameSet != null && subKeyNameSet.Contains(settingName)) + else if (subKeyNameSet is not null && subKeyNameSet.Contains(settingName)) { using (RegistryKey subKey = gpoKey.OpenSubKey(settingName)) { - if (subKey != null) + if (subKey is not null) { rawRegistryValue = subKey.GetValueNames(); } @@ -895,7 +895,7 @@ private static bool TrySetPolicySettingsFromRegistryKey(object instance, Type in // Get the actual property value based on the property type. // If the final property value is not null, then set the property. - if (rawRegistryValue != null) + if (rawRegistryValue is not null) { Type propertyType = property.PropertyType; object propertyValue = null; @@ -939,7 +939,7 @@ private static bool TrySetPolicySettingsFromRegistryKey(object instance, Type in } // Set the property if the value is not null - if (propertyValue != null) + if (propertyValue is not null) { property.SetValue(instance, propertyValue); isAnyPropertySet = true; @@ -961,7 +961,7 @@ private static bool TrySetPolicySettingsFromRegistryKey(object instance, Type in RegistryKey rootKey = (scope == ConfigScope.AllUsers) ? Registry.LocalMachine : Registry.CurrentUser; GroupPolicyKeys.TryGetValue(tType.Name, out string gpoKeyPath); - Diagnostics.Assert(gpoKeyPath != null, StringUtil.Format("The GPO registry key path should be pre-defined for {0}", tType.Name)); + Diagnostics.Assert(gpoKeyPath is not null, StringUtil.Format("The GPO registry key path should be pre-defined for {0}", tType.Name)); using (RegistryKey gpoKey = rootKey.OpenSubKey(gpoKeyPath)) { @@ -982,7 +982,7 @@ private static bool TrySetPolicySettingsFromRegistryKey(object instance, Type in { // when PolicySettingFallbackKey flag is set (REG_DWORD "1") use Windows PS policy reg key WindowsPowershellGroupPolicyKeys.TryGetValue(tType.Name, out string winPowershellGpoKeyPath); - Diagnostics.Assert(winPowershellGpoKeyPath != null, StringUtil.Format("The Windows PS GPO registry key path should be pre-defined for {0}", tType.Name)); + Diagnostics.Assert(winPowershellGpoKeyPath is not null, StringUtil.Format("The Windows PS GPO registry key path should be pre-defined for {0}", tType.Name)); using (RegistryKey winPowershellGpoKey = rootKey.OpenSubKey(winPowershellGpoKeyPath)) { // If the corresponding Windows PS GPO key doesn't exist, return null @@ -1019,7 +1019,7 @@ private static bool TrySetPolicySettingsFromRegistryKey(object instance, Type in } } - if (policy != null) { return (T)policy; } + if (policy is not null) { return (T)policy; } } return null; @@ -1033,7 +1033,7 @@ private static bool TrySetPolicySettingsFromRegistryKey(object instance, Type in internal static void EnsureModuleLoaded(string module, ExecutionContext context) { - if (context != null && !context.AutoLoadingModuleInProgress.Contains(module)) + if (context is not null && !context.AutoLoadingModuleInProgress.Contains(module)) { List loadedModules = context.Modules.GetModules(new string[] { module }, false); @@ -1069,7 +1069,7 @@ internal static void EnsureModuleLoaded(string module, ExecutionContext context) finally { context.AutoLoadingModuleInProgress.Remove(module); - if (ps != null) + if (ps is not null) { ps.Dispose(); } @@ -1111,7 +1111,7 @@ internal static List GetModules(string module, ExecutionContext co .AddParameter("ListAvailable"); Collection gmoOutPut = ps.Invoke(); - if (gmoOutPut != null) + if (gmoOutPut is not null) { if (result is null) { @@ -1129,7 +1129,7 @@ internal static List GetModules(string module, ExecutionContext co } finally { - if (ps != null) + if (ps is not null) { ps.Dispose(); } @@ -1171,7 +1171,7 @@ internal static List GetModules(ModuleSpecification fullyQualified .AddParameter("ListAvailable"); Collection gmoOutput = ps.Invoke(); - if (gmoOutput != null) + if (gmoOutput is not null) { if (result is null) { @@ -1190,7 +1190,7 @@ internal static List GetModules(ModuleSpecification fullyQualified } finally { - if (ps != null) + if (ps is not null) { ps.Dispose(); } @@ -1211,7 +1211,7 @@ private static bool TryGetWindowsCurrentIdentity(out WindowsIdentity currentIden currentIdentity = null; } - return (currentIdentity != null); + return (currentIdentity is not null); } /// @@ -1330,7 +1330,7 @@ internal static bool IsPowerShellAssembly(string assemblyName) ? Path.GetFileNameWithoutExtension(assemblyName) : assemblyName; - if ((fixedName != null) && PowerShellAssemblies.Contains(fixedName)) + if ((fixedName is not null) && PowerShellAssemblies.Contains(fixedName)) { return true; } @@ -1348,7 +1348,7 @@ internal static string GetPowerShellAssemblyStrongName(string assemblyName) ? Path.GetFileNameWithoutExtension(assemblyName) : assemblyName; - if ((fixedName != null) && PowerShellAssemblies.Contains(fixedName)) + if ((fixedName is not null) && PowerShellAssemblies.Contains(fixedName)) { return string.Format(CultureInfo.InvariantCulture, PowerShellAssemblyStrongNameFormat, fixedName); } @@ -1511,7 +1511,7 @@ private static void WorkItemCallback(object callBackArgs) WaitCallback callback = args[1] as WaitCallback; object state = args[2]; - if (identityToImpersonate != null) + if (identityToImpersonate is not null) { WindowsIdentity.RunImpersonated( identityToImpersonate.AccessToken, @@ -1601,7 +1601,7 @@ internal static bool IsComObject(object obj) #if UNIX return false; #else - return obj != null && Marshal.IsComObject(obj); + return obj is not null && Marshal.IsComObject(obj); #endif } @@ -1684,7 +1684,7 @@ internal static bool TryRunAsImplicitBatch(string command, Runspace runspace) string errorId; string errorMsg; scriptBlockAst.GetSimplePipeline(true, out errorId, out errorMsg); - if (errorId != null) + if (errorId is not null) { WriteVerbose(ps, ParserStrings.ImplicitRemotingPipelineBatchingNotASimplePipeline); return false; @@ -1971,7 +1971,7 @@ public override AstVisitAction VisitCommand(CommandAst commandAst) } var commandName = commandAst.GetCommandName(); - if (commandName != null) + if (commandName is not null) { Commands.Add(commandName); } @@ -2091,7 +2091,7 @@ public static class InternalTestHooks public static void SetTestHook(string property, object value) { var fieldInfo = typeof(InternalTestHooks).GetField(property, BindingFlags.Static | BindingFlags.NonPublic); - if (fieldInfo != null) + if (fieldInfo is not null) { fieldInfo.SetValue(null, value); } diff --git a/src/System.Management.Automation/engine/VariableAttributeCollection.cs b/src/System.Management.Automation/engine/VariableAttributeCollection.cs index 0e8fe3c1d10..884f3b24da6 100644 --- a/src/System.Management.Automation/engine/VariableAttributeCollection.cs +++ b/src/System.Management.Automation/engine/VariableAttributeCollection.cs @@ -120,14 +120,14 @@ private object VerifyNewAttribute(Attribute item) // Perform transformation before validating ArgumentTransformationAttribute argumentTransformation = item as ArgumentTransformationAttribute; - if (argumentTransformation != null) + if (argumentTransformation is not null) { // Get an EngineIntrinsics instance using the context of the thread. ExecutionContext context = Runspaces.LocalPipeline.GetExecutionContextFromTLS(); EngineIntrinsics engine = null; - if (context != null) + if (context is not null) { engine = context.EngineIntrinsics; } @@ -142,7 +142,7 @@ private object VerifyNewAttribute(Attribute item) null, Metadata.InvalidMetadataForCurrentValue, _variable.Name, - ((_variable.Value != null) ? _variable.Value.ToString() : string.Empty)); + ((_variable.Value is not null) ? _variable.Value.ToString() : string.Empty)); throw e; } diff --git a/src/System.Management.Automation/engine/VariableInterfaces.cs b/src/System.Management.Automation/engine/VariableInterfaces.cs index d3af0300456..7b39f7c09f7 100644 --- a/src/System.Management.Automation/engine/VariableInterfaces.cs +++ b/src/System.Management.Automation/engine/VariableInterfaces.cs @@ -61,7 +61,7 @@ internal PSVariableIntrinsics(SessionStateInternal sessionState) public PSVariable Get(string name) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -72,7 +72,7 @@ public PSVariable Get(string name) // 2. If the requested variable is not null and does not exist in the session scope, then a null value is returned to the pipeline. // 3. If the requested variable is null then an NewArgumentNullException is thrown. // PowerShell V3 has the similar experience. - if (name != null && name.Equals(string.Empty)) + if (name is not null && name.Equals(string.Empty)) { return null; } @@ -109,7 +109,7 @@ public PSVariable Get(string name) internal PSVariable GetAtScope(string name, string scope) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -146,7 +146,7 @@ internal PSVariable GetAtScope(string name, string scope) public object GetValue(string name) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -188,7 +188,7 @@ public object GetValue(string name) public object GetValue(string name, object defaultValue) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -238,7 +238,7 @@ public object GetValue(string name, object defaultValue) internal object GetValueAtScope(string name, string scope) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -278,7 +278,7 @@ internal object GetValueAtScope(string name, string scope) public void Set(string name, object value) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -301,7 +301,7 @@ public void Set(string name, object value) public void Set(PSVariable variable) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -338,7 +338,7 @@ public void Set(PSVariable variable) public void Remove(string name) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -361,7 +361,7 @@ public void Remove(string name) public void Remove(PSVariable variable) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -397,7 +397,7 @@ public void Remove(PSVariable variable) internal void RemoveAtScope(string name, string scope) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object @@ -429,7 +429,7 @@ internal void RemoveAtScope(string name, string scope) internal void RemoveAtScope(PSVariable variable, string scope) { Dbg.Diagnostics.Assert( - _sessionState != null, + _sessionState is not null, "The only constructor for this class should always set the sessionState field"); // Parameter validation is done in the session state object diff --git a/src/System.Management.Automation/engine/VariablePath.cs b/src/System.Management.Automation/engine/VariablePath.cs index 0e33ae620c5..812affa6b14 100644 --- a/src/System.Management.Automation/engine/VariablePath.cs +++ b/src/System.Management.Automation/engine/VariablePath.cs @@ -137,7 +137,7 @@ internal VariablePath(string path, VariablePathFlags knownFlags) break; } - if (candidateScope != null) + if (candidateScope is not null) { currentCharIndex += 1; // First character already matched. int j; diff --git a/src/System.Management.Automation/engine/cmdlet.cs b/src/System.Management.Automation/engine/cmdlet.cs index 70436fb40fe..41cc16e3e17 100644 --- a/src/System.Management.Automation/engine/cmdlet.cs +++ b/src/System.Management.Automation/engine/cmdlet.cs @@ -137,7 +137,7 @@ internal override void DoBeginProcessing() { MshCommandRuntime mshRuntime = this.CommandRuntime as MshCommandRuntime; - if (mshRuntime != null) + if (mshRuntime is not null) { if (mshRuntime.UseTransaction && (!this.Context.TransactionManager.HasTransaction)) @@ -342,7 +342,7 @@ public void WriteError(ErrorRecord errorRecord) { using (PSTransactionManager.GetEngineProtectionScope()) { - if (commandRuntime != null) + if (commandRuntime is not null) commandRuntime.WriteError(errorRecord); else throw new System.NotImplementedException("WriteError"); @@ -373,7 +373,7 @@ public void WriteObject(object sendToPipeline) { using (PSTransactionManager.GetEngineProtectionScope()) { - if (commandRuntime != null) + if (commandRuntime is not null) commandRuntime.WriteObject(sendToPipeline); else throw new System.NotImplementedException("WriteObject"); @@ -409,7 +409,7 @@ public void WriteObject(object sendToPipeline, bool enumerateCollection) { using (PSTransactionManager.GetEngineProtectionScope()) { - if (commandRuntime != null) + if (commandRuntime is not null) commandRuntime.WriteObject(sendToPipeline, enumerateCollection); else throw new System.NotImplementedException("WriteObject"); @@ -446,7 +446,7 @@ public void WriteVerbose(string text) { using (PSTransactionManager.GetEngineProtectionScope()) { - if (commandRuntime != null) + if (commandRuntime is not null) commandRuntime.WriteVerbose(text); else throw new System.NotImplementedException("WriteVerbose"); @@ -483,7 +483,7 @@ public void WriteWarning(string text) { using (PSTransactionManager.GetEngineProtectionScope()) { - if (commandRuntime != null) + if (commandRuntime is not null) commandRuntime.WriteWarning(text); else throw new System.NotImplementedException("WriteWarning"); @@ -520,7 +520,7 @@ public void WriteCommandDetail(string text) { using (PSTransactionManager.GetEngineProtectionScope()) { - if (commandRuntime != null) + if (commandRuntime is not null) commandRuntime.WriteCommandDetail(text); else throw new System.NotImplementedException("WriteCommandDetail"); @@ -559,7 +559,7 @@ public void WriteProgress(ProgressRecord progressRecord) { using (PSTransactionManager.GetEngineProtectionScope()) { - if (commandRuntime != null) + if (commandRuntime is not null) commandRuntime.WriteProgress(progressRecord); else throw new System.NotImplementedException("WriteProgress"); @@ -592,7 +592,7 @@ internal void WriteProgress( Int64 sourceId, ProgressRecord progressRecord) { - if (commandRuntime != null) + if (commandRuntime is not null) commandRuntime.WriteProgress(sourceId, progressRecord); else throw new System.NotImplementedException("WriteProgress"); @@ -634,7 +634,7 @@ public void WriteDebug(string text) { using (PSTransactionManager.GetEngineProtectionScope()) { - if (commandRuntime != null) + if (commandRuntime is not null) commandRuntime.WriteDebug(text); else throw new System.NotImplementedException("WriteDebug"); @@ -679,7 +679,7 @@ public void WriteInformation(object messageData, string[] tags) using (PSTransactionManager.GetEngineProtectionScope()) { ICommandRuntime2 commandRuntime2 = commandRuntime as ICommandRuntime2; - if (commandRuntime2 != null) + if (commandRuntime2 is not null) { string source = this.MyInvocation.PSCommandPath; if (string.IsNullOrEmpty(source)) @@ -689,7 +689,7 @@ public void WriteInformation(object messageData, string[] tags) InformationRecord informationRecord = new InformationRecord(messageData, source); - if (tags != null) + if (tags is not null) { informationRecord.Tags.AddRange(tags); } @@ -737,7 +737,7 @@ public void WriteInformation(InformationRecord informationRecord) using (PSTransactionManager.GetEngineProtectionScope()) { ICommandRuntime2 commandRuntime2 = commandRuntime as ICommandRuntime2; - if (commandRuntime2 != null) + if (commandRuntime2 is not null) { commandRuntime2.WriteInformation(informationRecord); } @@ -835,7 +835,7 @@ public bool ShouldProcess(string target) { using (PSTransactionManager.GetEngineProtectionScope()) { - if (commandRuntime != null) + if (commandRuntime is not null) return commandRuntime.ShouldProcess(target); else return true; @@ -931,7 +931,7 @@ public bool ShouldProcess(string target, string action) { using (PSTransactionManager.GetEngineProtectionScope()) { - if (commandRuntime != null) + if (commandRuntime is not null) return commandRuntime.ShouldProcess(target, action); else return true; @@ -1041,7 +1041,7 @@ public bool ShouldProcess( { using (PSTransactionManager.GetEngineProtectionScope()) { - if (commandRuntime != null) + if (commandRuntime is not null) return commandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption); else return true; @@ -1160,7 +1160,7 @@ public bool ShouldProcess( { using (PSTransactionManager.GetEngineProtectionScope()) { - if (commandRuntime != null) + if (commandRuntime is not null) return commandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption, out shouldProcessReason); else { @@ -1287,7 +1287,7 @@ public bool ShouldContinue(string query, string caption) { using (PSTransactionManager.GetEngineProtectionScope()) { - if (commandRuntime != null) + if (commandRuntime is not null) return commandRuntime.ShouldContinue(query, caption); else return true; @@ -1423,7 +1423,7 @@ public bool ShouldContinue( { using (PSTransactionManager.GetEngineProtectionScope()) { - if (commandRuntime != null) + if (commandRuntime is not null) return commandRuntime.ShouldContinue(query, caption, ref yesToAll, ref noToAll); else return true; @@ -1563,10 +1563,10 @@ public bool ShouldContinue( { using (PSTransactionManager.GetEngineProtectionScope()) { - if (commandRuntime != null) + if (commandRuntime is not null) { ICommandRuntime2 runtime2 = commandRuntime as ICommandRuntime2; - if (runtime2 != null) + if (runtime2 is not null) { return runtime2.ShouldContinue(query, caption, hasSecurityImpact, ref yesToAll, ref noToAll); } @@ -1649,7 +1649,7 @@ public bool TransactionAvailable() { using (PSTransactionManager.GetEngineProtectionScope()) { - if (commandRuntime != null) + if (commandRuntime is not null) return commandRuntime.TransactionAvailable(); else #pragma warning suppress 56503 @@ -1666,7 +1666,7 @@ public PSTransactionContext CurrentPSTransaction { get { - if (commandRuntime != null) + if (commandRuntime is not null) return commandRuntime.CurrentPSTransaction; else // We want to throw in this situation, and want to use a @@ -1721,11 +1721,11 @@ public void ThrowTerminatingError(ErrorRecord errorRecord) if (errorRecord is null) throw new ArgumentNullException(nameof(errorRecord)); - if (commandRuntime != null) + if (commandRuntime is not null) { commandRuntime.ThrowTerminatingError(errorRecord); } - else if (errorRecord.Exception != null) + else if (errorRecord.Exception is not null) { throw errorRecord.Exception; } diff --git a/src/System.Management.Automation/engine/debugger/Breakpoint.cs b/src/System.Management.Automation/engine/debugger/Breakpoint.cs index 4fca64dc5d6..6a513b450ab 100644 --- a/src/System.Management.Automation/engine/debugger/Breakpoint.cs +++ b/src/System.Management.Automation/engine/debugger/Breakpoint.cs @@ -47,7 +47,7 @@ internal void SetEnabled(bool value) /// internal bool IsScriptBreakpoint { - get { return Script != null; } + get { return Script is not null; } } /// @@ -227,7 +227,7 @@ private bool CommandInfoMatches(CommandInfo commandInfo) } var externalScript = commandInfo as ExternalScriptInfo; - if (externalScript != null) + if (externalScript is not null) { if (externalScript.Path.Equals(Command, StringComparison.OrdinalIgnoreCase)) return true; @@ -486,7 +486,7 @@ internal bool TrySetBreakpoint(string scriptFile, FunctionContext functionContex // A quick check to see if the breakpoint is within the scriptblock. bool couldBeInNestedScriptBlock; var scriptBlock = functionContext._scriptBlock; - if (scriptBlock != null) + if (scriptBlock is not null) { var ast = scriptBlock.Ast; if (!ast.Extent.ContainsLineAndColumn(Line, Column)) @@ -509,7 +509,7 @@ internal bool TrySetBreakpoint(string scriptFile, FunctionContext functionContex int sequencePointIndex; var sequencePoint = FindSequencePoint(functionContext, Line, Column, out sequencePointIndex); - if (sequencePoint != null) + if (sequencePoint is not null) { // If the bp could be in a nested script block, we want to be careful and get the bp in the correct script block. // If it's a simple line bp (no column specified), then the start line must match the bp line exactly, otherwise @@ -530,7 +530,7 @@ internal bool TrySetBreakpoint(string scriptFile, FunctionContext functionContex // Not found. First, we check if the line/column is before any real code. If so, we'll // move the breakpoint to the first interesting sequence point (could be a dynamicparam, // begin, process, or end block.) - if (scriptBlock != null) + if (scriptBlock is not null) { var ast = scriptBlock.Ast; var bodyAst = ((IParameterMetadataProvider)ast).Body; @@ -545,7 +545,7 @@ internal bool TrySetBreakpoint(string scriptFile, FunctionContext functionContex } // Still not found. Try fudging a bit, but only if it's a simple line breakpoint. - if (Column == 0 && FindSequencePoint(functionContext, Line + 1, 0, out sequencePointIndex) != null) + if (Column == 0 && FindSequencePoint(functionContext, Line + 1, 0, out sequencePointIndex) is not null) { SetBreakpoint(functionContext, sequencePointIndex); return true; @@ -585,12 +585,12 @@ private void SetBreakpoint(FunctionContext functionContext, int sequencePointInd internal override bool RemoveSelf(ScriptDebugger debugger) { - if (this.SequencePoints != null) + if (this.SequencePoints is not null) { // Remove ourselves from the list of bound breakpoints in this script. It's possible the breakpoint was never // bound, in which case there is nothing to do. var boundBreakPoints = debugger.GetBoundBreakpoints(this.SequencePoints); - if (boundBreakPoints != null) + if (boundBreakPoints is not null) { Diagnostics.Assert(boundBreakPoints.Contains(this), "If we set _scriptBlock, we should have also added the breakpoint to the bound breakpoint list"); diff --git a/src/System.Management.Automation/engine/debugger/debugger.cs b/src/System.Management.Automation/engine/debugger/debugger.cs index 07c5f179210..7058e041f7d 100644 --- a/src/System.Management.Automation/engine/debugger/debugger.cs +++ b/src/System.Management.Automation/engine/debugger/debugger.cs @@ -427,7 +427,7 @@ internal virtual bool IsDebuggerSteppingEnabled /// internal bool IsDebugHandlerSubscribed { - get { return (DebuggerStop != null); } + get { return (DebuggerStop is not null); } } /// @@ -498,7 +498,7 @@ protected void RaiseDebuggerStopEvent(DebuggerStopEventArgs args) /// True if event subscription exists. protected bool IsDebuggerStopEventSubscribed() { - return (DebuggerStop != null); + return (DebuggerStop is not null); } /// @@ -517,7 +517,7 @@ protected void RaiseBreakpointUpdatedEvent(BreakpointUpdatedEventArgs args) /// True if event subscription exists. protected bool IsDebuggerBreakpointUpdatedEventSubscribed() { - return (BreakpointUpdated != null); + return (BreakpointUpdated is not null); } #region Runspace Debug Processing @@ -541,7 +541,7 @@ protected void RaiseRunspaceProcessingCompletedEvent(ProcessRunspaceDebugEndEven /// protected bool IsStartRunspaceDebugProcessingEventSubscribed() { - return (StartRunspaceDebugProcessing != null); + return (StartRunspaceDebugProcessing is not null); } /// @@ -1054,7 +1054,7 @@ internal override bool IsPendingDebugStopEvent { get { - return ((_preserveDebugStopEvent != null) && !_preserveDebugStopEvent.IsSet); + return ((_preserveDebugStopEvent is not null) && !_preserveDebugStopEvent.IsSet); } } @@ -1080,7 +1080,7 @@ private bool IsLocalSession if (_isLocalSession is null) { // Remote debug sessions always have a ServerRemoteHost. Otherwise it is a local session. - _isLocalSession = !(((_context.InternalHost.ExternalHost != null) && + _isLocalSession = !(((_context.InternalHost.ExternalHost is not null) && (_context.InternalHost.ExternalHost is System.Management.Automation.Remoting.ServerRemoteHost))); } @@ -1168,7 +1168,7 @@ internal void EnterScriptFunction(FunctionContext functionContext) if (_context._debuggingMode > 0) { var scriptCommandInfo = invocationInfo.MyCommand as ExternalScriptInfo; - if (scriptCommandInfo != null) + if (scriptCommandInfo is not null) { RegisterScriptFile(scriptCommandInfo); } @@ -1284,21 +1284,21 @@ private LineBreakpoint AddLineBreakpoint(LineBreakpoint breakpoint) private void AddNewBreakpoint(Breakpoint breakpoint) { LineBreakpoint lineBreakpoint = breakpoint as LineBreakpoint; - if (lineBreakpoint != null) + if (lineBreakpoint is not null) { AddLineBreakpoint(lineBreakpoint); return; } CommandBreakpoint cmdBreakpoint = breakpoint as CommandBreakpoint; - if (cmdBreakpoint != null) + if (cmdBreakpoint is not null) { AddCommandBreakpoint(cmdBreakpoint); return; } VariableBreakpoint varBreakpoint = breakpoint as VariableBreakpoint; - if (varBreakpoint != null) + if (varBreakpoint is not null) { AddVariableBreakpoint(varBreakpoint); } @@ -1392,7 +1392,7 @@ internal bool RemoveLineBreakpoint(LineBreakpoint breakpoint) internal bool CheckCommand(InvocationInfo invocationInfo) { var functionContext = _callStack.LastFunctionContext(); - if (functionContext != null && functionContext._debuggerHidden) + if (functionContext is not null && functionContext._debuggerHidden) { // Never stop in DebuggerHidden scripts, don't even call the actions on breakpoints. return false; @@ -1408,7 +1408,7 @@ internal bool CheckCommand(InvocationInfo invocationInfo) if (breakpoints.Count > 0) { var breakInvocationInfo = - functionContext != null + functionContext is not null ? new InvocationInfo(invocationInfo.MyCommand, functionContext.CurrentPosition) : null; OnDebuggerStop(breakInvocationInfo, breakpoints); @@ -1422,7 +1422,7 @@ internal bool CheckCommand(InvocationInfo invocationInfo) internal void CheckVariableRead(string variableName) { var breakpointsToTrigger = GetVariableBreakpointsToTrigger(variableName, read: true); - if (breakpointsToTrigger != null && breakpointsToTrigger.Count > 0) + if (breakpointsToTrigger is not null && breakpointsToTrigger.Count > 0) { TriggerVariableBreakpoints(breakpointsToTrigger); } @@ -1431,7 +1431,7 @@ internal void CheckVariableRead(string variableName) internal void CheckVariableWrite(string variableName) { var breakpointsToTrigger = GetVariableBreakpointsToTrigger(variableName, read: false); - if (breakpointsToTrigger != null && breakpointsToTrigger.Count > 0) + if (breakpointsToTrigger is not null && breakpointsToTrigger.Count > 0) { TriggerVariableBreakpoints(breakpointsToTrigger); } @@ -1442,7 +1442,7 @@ private List GetVariableBreakpointsToTrigger(string variable Diagnostics.Assert(_context._debuggingMode == 1, "breakpoints only hit when debugging mode is 1"); var functionContext = _callStack.LastFunctionContext(); - if (functionContext != null && functionContext._debuggerHidden) + if (functionContext is not null && functionContext._debuggerHidden) { // Never stop in DebuggerHidden scripts, don't even call the action on any breakpoint. return null; @@ -1467,7 +1467,7 @@ private List GetVariableBreakpointsToTrigger(string variable return null; var callStackInfo = _callStack.Last(); - var currentScriptFile = (callStackInfo != null) ? callStackInfo.File : null; + var currentScriptFile = (callStackInfo is not null) ? callStackInfo.File : null; return breakpoints.Values.Where(bp => bp.Trigger(currentScriptFile, read: read)).ToList(); } finally @@ -1479,7 +1479,7 @@ private List GetVariableBreakpointsToTrigger(string variable internal void TriggerVariableBreakpoints(List breakpoints) { var functionContext = _callStack.LastFunctionContext(); - var invocationInfo = functionContext != null ? new InvocationInfo(null, functionContext.CurrentPosition, _context) : null; + var invocationInfo = functionContext is not null ? new InvocationInfo(null, functionContext.CurrentPosition, _context) : null; OnDebuggerStop(invocationInfo, breakpoints.ToList()); } @@ -1653,7 +1653,7 @@ internal CallStackInfo Last() internal FunctionContext LastFunctionContext() { var last = Last(); - return last != null ? last.FunctionContext : null; + return last is not null ? last.FunctionContext : null; } internal bool Any() @@ -1750,13 +1750,13 @@ internal void Clear() /// private void OnDebuggerStop(InvocationInfo invocationInfo, List breakpoints) { - Diagnostics.Assert(breakpoints != null, "The list of breakpoints should not be null"); + Diagnostics.Assert(breakpoints is not null, "The list of breakpoints should not be null"); LocalRunspace localRunspace = _context.CurrentRunspace as LocalRunspace; - Diagnostics.Assert(localRunspace != null, "Debugging is only supported on local runspaces"); + Diagnostics.Assert(localRunspace is not null, "Debugging is only supported on local runspaces"); - if (localRunspace.PulsePipeline != null && localRunspace.PulsePipeline == localRunspace.GetCurrentlyRunningPipeline()) + if (localRunspace.PulsePipeline is not null && localRunspace.PulsePipeline == localRunspace.GetCurrentlyRunningPipeline()) { _context.EngineHostInterface.UI.WriteWarningLine( breakpoints.Count > 0 @@ -1789,7 +1789,7 @@ private void OnDebuggerStop(InvocationInfo invocationInfo, List brea try { Collection items = _context.SessionState.InvokeProvider.Item.Get("function:\\prompt"); - if ((items != null) && (items.Count > 0)) + if ((items is not null) && (items.Count > 0)) { defaultPromptInfo = items[0].BaseObject as FunctionInfo; originalPromptString = defaultPromptInfo.Definition as string; @@ -1837,7 +1837,7 @@ private void OnDebuggerStop(InvocationInfo invocationInfo, List brea RunspaceAvailability previousAvailability = _context.CurrentRunspace.RunspaceAvailability; _context.CurrentRunspace.UpdateRunspaceAvailability( - _context.CurrentRunspace.GetCurrentlyRunningPipeline() != null + _context.CurrentRunspace.GetCurrentlyRunningPipeline() is not null ? RunspaceAvailability.AvailableForNestedCommand : RunspaceAvailability.Available, true); @@ -2081,7 +2081,7 @@ private void StopOnSequencePoint(FunctionContext functionContext, List 0, "Caller to verify line is greater than 0."); CheckForBreakpointSupport(); @@ -2817,7 +2817,7 @@ public override bool RemoveBreakpoint(Breakpoint breakpoint, int? runspaceId) return GetRunspaceDebugger(runspaceId.Value).RemoveBreakpoint(breakpoint); } - Diagnostics.Assert(breakpoint != null, "Caller to verify the breakpoint is not null."); + Diagnostics.Assert(breakpoint is not null, "Caller to verify the breakpoint is not null."); if (_idToBreakpoint.Remove(breakpoint.Id, out _)) { @@ -2848,7 +2848,7 @@ public override Breakpoint EnableBreakpoint(Breakpoint breakpoint, int? runspace return GetRunspaceDebugger(runspaceId.Value).EnableBreakpoint(breakpoint); } - Diagnostics.Assert(breakpoint != null, "Caller to verify the breakpoint is not null."); + Diagnostics.Assert(breakpoint is not null, "Caller to verify the breakpoint is not null."); if (_idToBreakpoint.TryGetValue(breakpoint.Id, out _)) { @@ -2873,7 +2873,7 @@ public override Breakpoint DisableBreakpoint(Breakpoint breakpoint, int? runspac return GetRunspaceDebugger(runspaceId.Value).DisableBreakpoint(breakpoint); } - Diagnostics.Assert(breakpoint != null, "Caller to verify the breakpoint is not null."); + Diagnostics.Assert(breakpoint is not null, "Caller to verify the breakpoint is not null."); if (_idToBreakpoint.TryGetValue(breakpoint.Id, out _)) { @@ -2952,7 +2952,7 @@ internal override void DebugJob(Job job, bool breakAll) private bool TryAddDebugJob(Job job, bool breakAll) { IJobDebugger debuggableJob = job as IJobDebugger; - if ((debuggableJob != null) && (debuggableJob.Debugger != null) && + if ((debuggableJob is not null) && (debuggableJob.Debugger is not null) && ((job.JobStateInfo.State == JobState.Running) || (job.JobStateInfo.State == JobState.AtBreakpoint))) { // Check to see if job is already stopped in debugger. @@ -2968,7 +2968,7 @@ private bool TryAddDebugJob(Job job, bool breakAll) if (jobDebugAlreadyStopped) { RemotingJobDebugger remoteJobDebugger = debuggableJob.Debugger as RemotingJobDebugger; - if (remoteJobDebugger != null) + if (remoteJobDebugger is not null) { remoteJobDebugger.CheckStateAndRaiseStopEvent(); } @@ -3015,7 +3015,7 @@ internal override void StopDebugJob(Job job) /// Boolean. internal static void SetDebugJobAsync(IJobDebugger debuggableJob, bool isAsync) { - if (debuggableJob != null) + if (debuggableJob is not null) { debuggableJob.IsAsync = isAsync; } @@ -3129,7 +3129,7 @@ public override void CancelDebuggerProcessing() private void ReleaseInternalRunspaceDebugProcessing(object sender, bool emptyQueue = false) { Runspace runspace = sender as Runspace; - if (runspace != null) + if (runspace is not null) { runspace.StateChanged -= RunspaceStateChangedHandler; runspace.AvailabilityChanged -= RunspaceAvailabilityChangedHandler; @@ -3150,7 +3150,7 @@ private void ReleaseInternalRunspaceDebugProcessing(object sender, bool emptyQue } } - if (_runspaceDebugCompleteEvent != null) + if (_runspaceDebugCompleteEvent is not null) { try { @@ -3267,7 +3267,7 @@ private void SetRunspaceListToStep(bool enableStepping) { Debugger nestedDebugger = item.NestedDebugger; - if (nestedDebugger != null) + if (nestedDebugger is not null) { nestedDebugger.SetDebuggerStepMode(enableStepping); } @@ -3291,7 +3291,7 @@ private void RemoveFromRunningJobList(Job job) } } - if (jobArgs != null) + if (jobArgs is not null) { // Pop from active debugger stack. lock (_syncActiveDebuggerStopObject) @@ -3320,7 +3320,7 @@ private void ClearRunningJobList() } } - if (runningJobs != null) + if (runningJobs is not null) { foreach (var item in runningJobs) { @@ -3403,7 +3403,7 @@ private void HandleActiveJobDebuggerStop(object sender, DebuggerStopEventArgs ar if (_runningRunspaces.Count > 0) { return; } // Forward active debugger event. - if (args != null) + if (args is not null) { // Save copy of arguments. DebuggerStopEventArgs copyArgs = new DebuggerStopEventArgs( @@ -3452,7 +3452,7 @@ private CallStackInfo FixUpCallStack() private void RestoreCallStack(CallStackInfo item) { - if (item != null) + if (item is not null) { _callStack.Add(item); } @@ -3585,8 +3585,8 @@ private DebuggerCommandResults ProcessCommandForActiveDebugger(PSCommand command // Check to see if this is a resume command that we handle here. DebuggerCommand dbgCommand = _commandProcessor.ProcessBasicCommand(commandText); - if (dbgCommand != null && - dbgCommand.ResumeAction != null) + if (dbgCommand is not null && + dbgCommand.ResumeAction is not null) { _lastActiveDebuggerAction = dbgCommand.ResumeAction.Value; return new DebuggerCommandResults(dbgCommand.ResumeAction, true); @@ -3625,7 +3625,7 @@ internal override void StartMonitoringRunspace(PSMonitorRunspaceInfo runspaceInf { if (runspaceInfo is null || runspaceInfo.Runspace is null) { return; } - if ((runspaceInfo.Runspace.Debugger != null) && + if ((runspaceInfo.Runspace.Debugger is not null) && runspaceInfo.Runspace.Debugger.Equals(this)) { Debug.Fail("Nested debugger cannot be the root debugger."); @@ -3698,8 +3698,8 @@ private void RemoveFromRunningRunspaceList(Runspace runspace) } // Clean up nested debugger. - NestedRunspaceDebugger nestedDebugger = (runspaceInfo != null) ? runspaceInfo.NestedDebugger : null; - if (nestedDebugger != null) + NestedRunspaceDebugger nestedDebugger = (runspaceInfo is not null) ? runspaceInfo.NestedDebugger : null; + if (nestedDebugger is not null) { nestedDebugger.DebuggerStop -= HandleMonitorRunningRSDebuggerStop; nestedDebugger.Dispose(); @@ -3731,7 +3731,7 @@ private void ClearRunningRunspaceList() } } - if (runningRunspaces != null) + if (runningRunspaces is not null) { foreach (var item in runningRunspaces) { @@ -3860,8 +3860,8 @@ private bool SetUpDebuggerOnRunspace(Runspace runspace) // Create nested debugger wrapper if it is not already created and if // the runspace debugger is available. - if ((runspace.Debugger != null) && - (runspaceInfo != null) && + if ((runspace.Debugger is not null) && + (runspaceInfo is not null) && (runspaceInfo.NestedDebugger is null)) { try @@ -4031,7 +4031,7 @@ public void Dispose() foreach (var item in runningJobs) { Job job = item.Job; - if (job != null) + if (job is not null) { job.StateChanged -= HandleJobStateChanged; job.OutputProcessingStateChanged -= HandleOutputProcessingStateChanged; @@ -4041,13 +4041,13 @@ public void Dispose() _processingOutputCompleteEvent.Dispose(); _processingOutputCompleteEvent = null; - if (_preserveDebugStopEvent != null) + if (_preserveDebugStopEvent is not null) { _preserveDebugStopEvent.Dispose(); _preserveDebugStopEvent = null; } - if (_runspaceDebugCompleteEvent != null) + if (_runspaceDebugCompleteEvent is not null) { _runspaceDebugCompleteEvent.Dispose(); _runspaceDebugCompleteEvent = null; @@ -4071,7 +4071,7 @@ internal void EnableTracing(int traceLevel, bool? step) _context.IgnoreScriptDebug = false; _context.PSDebugTraceLevel = traceLevel; - if (step != null) + if (step is not null) { _context.PSDebugTraceStep = (bool)step; } @@ -4441,7 +4441,7 @@ public virtual void Dispose() { _isDisposed = true; - if (_wrappedDebugger != null) + if (_wrappedDebugger is not null) { _wrappedDebugger.BreakpointUpdated -= HandleBreakpointUpdated; _wrappedDebugger.DebuggerStop -= HandleDebuggerStop; @@ -4473,7 +4473,7 @@ protected virtual DebuggerCommandResults HandlePromptCommand(PSDataCollection]: [RunspaceName]: PS C:\> - string computerName = (_runspace.ConnectionInfo != null) ? _runspace.ConnectionInfo.ComputerName : null; + string computerName = (_runspace.ConnectionInfo is not null) ? _runspace.ConnectionInfo.ComputerName : null; string processPartPattern = "{0}[{1}:{2}]:{3}"; string processPart = StringUtil.Format(processPartPattern, @"""", @@ -4552,7 +4552,7 @@ internal bool IsSameDebugger(Debugger testDebugger) internal void CheckStateAndRaiseStopEvent() { RemoteDebugger remoteDebugger = _wrappedDebugger as RemoteDebugger; - if (remoteDebugger != null) + if (remoteDebugger is not null) { // Have remote debugger raise existing debugger stop event. remoteDebugger.CheckStateAndRaiseStopEvent(); @@ -4567,7 +4567,7 @@ internal void CheckStateAndRaiseStopEvent() // If this is a remote server debugger then we want to convert the pending remote // debugger stop to a local debugger stop event for this Debug-Runspace to handle. ServerRemoteDebugger serverRemoteDebugger = this._wrappedDebugger as ServerRemoteDebugger; - if (serverRemoteDebugger != null) + if (serverRemoteDebugger is not null) { serverRemoteDebugger.ReleaseAndRaiseDebugStopLocal(); } @@ -4654,7 +4654,7 @@ private object DrainAndBlockRemoteOutput() if (remoteRunspace is null) { return null; } var runningPowerShell = remoteRunspace.GetCurrentBasePowerShell(); - if (runningPowerShell != null) + if (runningPowerShell is not null) { runningPowerShell.WaitForServicingComplete(); runningPowerShell.SuspendIncomingData(); @@ -4663,7 +4663,7 @@ private object DrainAndBlockRemoteOutput() else { var runningPipe = remoteRunspace.GetCurrentlyRunningPipeline(); - if (runningPipe != null) + if (runningPipe is not null) { runningPipe.DrainIncomingData(); runningPipe.SuspendIncomingData(); @@ -4679,7 +4679,7 @@ private void RestoreRemoteOutput(object runningCmd) if (runningCmd is null) { return; } var runningPowerShell = runningCmd as PowerShell; - if (runningPowerShell != null) + if (runningPowerShell is not null) { runningPowerShell.ResumeIncomingData(); } @@ -4792,7 +4792,7 @@ protected override DebuggerCommandResults HandleCallStack(PSDataCollection output) { - if ((_sendDebuggerArgs != null) && (_sendDebuggerArgs.InvocationInfo != null)) + if ((_sendDebuggerArgs is not null) && (_sendDebuggerArgs.InvocationInfo is not null)) { return _rootDebugger.InternalProcessListCommand(_sendDebuggerArgs.InvocationInfo.ScriptLineNumber, output); } @@ -4817,14 +4817,14 @@ internal override InvocationInfo FixupInvocationInfo(InvocationInfo debugStopInv int dbStopLineNumber = debugStopInvocationInfo.ScriptLineNumber; CallStackFrame topItem = null; var parentActiveStack = _rootDebugger.GetActiveDebuggerCallStack(); - if ((parentActiveStack != null) && (parentActiveStack.Length > 0)) + if ((parentActiveStack is not null) && (parentActiveStack.Length > 0)) { topItem = parentActiveStack[0]; } else { var parentStack = _rootDebugger.GetCallStack().ToArray(); - if ((parentStack != null) && (parentStack.Length > 0)) + if ((parentStack is not null) && (parentStack.Length > 0)) { topItem = parentStack[0]; dbStopLineNumber--; @@ -4882,7 +4882,7 @@ private InvocationInfo CreateInvocationInfoFromParent( out tokens, out errors); } - if (_parentScriptBlockAst != null) + if (_parentScriptBlockAst is not null) { int callingLineNumber = parentStackFrame.ScriptLineNumber; @@ -4893,18 +4893,18 @@ private InvocationInfo CreateInvocationInfoFromParent( , true) as StatementAst; - if (callingStatement != null) + if (callingStatement is not null) { // Find first statement in calling statement. StatementAst firstStatement = callingStatement.Find(ast => { return ((ast is StatementAst) && ast.Extent.StartLineNumber > callingLineNumber); }, true) as StatementAst; - if (firstStatement != null) + if (firstStatement is not null) { int adjustedLineNumber = firstStatement.Extent.StartLineNumber + debugLineNumber - 1; debugStatement = callingStatement.Find(ast => { return ((ast is StatementAst) && ast.Extent.StartLineNumber == adjustedLineNumber); }, true) as StatementAst; } } - if (debugStatement != null) + if (debugStatement is not null) { int endColNum = debugStartColNumber + (debugEndColNumber - debugStartColNumber) - 2; string statementExtentText = FixUpStatementExtent(debugStatement.Extent.StartColumnNumber - 1, debugStatement.Extent.Text); @@ -4949,7 +4949,7 @@ private object DrainAndBlockRemoteOutput() try { - if (_command != null) + if (_command is not null) { _command.WaitForServicingComplete(); _command.SuspendIncomingData(); @@ -4958,7 +4958,7 @@ private object DrainAndBlockRemoteOutput() } Pipeline runningCmd = _runspace.GetCurrentlyRunningPipeline(); - if (runningCmd != null) + if (runningCmd is not null) { runningCmd.DrainIncomingData(); runningCmd.SuspendIncomingData(); @@ -4977,14 +4977,14 @@ private void RestoreRemoteOutput(object runningCmd) if (runningCmd is null) { return; } PowerShell command = runningCmd as PowerShell; - if (command != null) + if (command is not null) { command.ResumeIncomingData(); } else { Pipeline pipelineCommand = runningCmd as Pipeline; - if (pipelineCommand != null) + if (pipelineCommand is not null) { pipelineCommand.ResumeIncomingData(); } @@ -5144,7 +5144,7 @@ public DebuggerCommand ProcessCommand(PSHost host, string command, InvocationInf public DebuggerCommand ProcessCommand(PSHost host, string command, InvocationInfo invocationInfo, IList output) { DebuggerCommand dbgCommand = DoProcessCommand(host, command, invocationInfo, output); - if (dbgCommand.ExecutedByDebugger || (dbgCommand.ResumeAction != null)) { _lastCommand = dbgCommand; } + if (dbgCommand.ExecutedByDebugger || (dbgCommand.ResumeAction is not null)) { _lastCommand = dbgCommand; } return dbgCommand; } @@ -5167,7 +5167,7 @@ public void ProcessListCommand(InvocationInfo invocationInfo, IList ou /// DebuggerCommand or null. public DebuggerCommand ProcessBasicCommand(string command) { - if (command.Length == 0 && _lastCommand != null && _lastCommand.RepeatOnEnter) + if (command.Length == 0 && _lastCommand is not null && _lastCommand.RepeatOnEnter) { return _lastCommand; } @@ -5175,7 +5175,7 @@ public DebuggerCommand ProcessBasicCommand(string command) DebuggerCommand debuggerCommand; if (_commandTable.TryGetValue(command, out debuggerCommand)) { - if (debuggerCommand.ExecutedByDebugger || (debuggerCommand.ResumeAction != null)) { _lastCommand = debuggerCommand; } + if (debuggerCommand.ExecutedByDebugger || (debuggerCommand.ResumeAction is not null)) { _lastCommand = debuggerCommand; } return debuggerCommand; } @@ -5189,11 +5189,11 @@ public DebuggerCommand ProcessBasicCommand(string command) private DebuggerCommand DoProcessCommand(PSHost host, string command, InvocationInfo invocationInfo, IList output) { // check for - if (command.Length == 0 && _lastCommand != null && _lastCommand.RepeatOnEnter) + if (command.Length == 0 && _lastCommand is not null && _lastCommand.RepeatOnEnter) { if (_lastCommand == _listCommand) { - if (_lines != null && _lastLineDisplayed < _lines.Length) + if (_lines is not null && _lastLineDisplayed < _lines.Length) { DisplayScript(host, output, invocationInfo, _lastLineDisplayed + 1, DefaultListLineCount); } @@ -5366,12 +5366,12 @@ private void DisplayScript(PSHost host, IList output, InvocationInfo i private void WriteLine(string line, PSHost host, IList output) { - if (host != null) + if (host is not null) { host.UI.WriteLine(line); } - if (output != null) + if (output is not null) { output.Add(new PSObject(line)); } @@ -5379,12 +5379,12 @@ private void WriteLine(string line, PSHost host, IList output) private void WriteCR(PSHost host, IList output) { - if (host != null) + if (host is not null) { host.UI.WriteLine(); } - if (output != null) + if (output is not null) { output.Add(new PSObject(Crlf)); } @@ -5392,12 +5392,12 @@ private void WriteCR(PSHost host, IList output) private void WriteErrorLine(string error, PSHost host, IList output) { - if (host != null) + if (host is not null) { host.UI.WriteErrorLine(error); } - if (output != null) + if (output is not null) { output.Add( new PSObject( @@ -5532,7 +5532,7 @@ internal CallStackFrame(FunctionContext functionContext, InvocationInfo invocati throw new PSArgumentNullException(nameof(invocationInfo)); } - if (functionContext != null) + if (functionContext is not null) { this.InvocationInfo = invocationInfo; FunctionContext = functionContext; @@ -5607,7 +5607,7 @@ public Dictionary GetFrameVariables() if (FunctionContext._executionContext is null) { return result; } var scope = FunctionContext._executionContext.EngineSessionState.CurrentScope; - while (scope != null) + while (scope is not null) { if (scope.LocalsTuple == FunctionContext._localsTuple) { @@ -5615,7 +5615,7 @@ public Dictionary GetFrameVariables() break; } - if (scope.DottedScopes != null && scope.DottedScopes.Any(s => s == FunctionContext._localsTuple)) + if (scope.DottedScopes is not null && scope.DottedScopes.Any(s => s == FunctionContext._localsTuple)) { var dottedScopes = scope.DottedScopes.ToArray(); diff --git a/src/System.Management.Automation/engine/hostifaces/AsyncResult.cs b/src/System.Management.Automation/engine/hostifaces/AsyncResult.cs index 745556b78bd..30da9f74238 100644 --- a/src/System.Management.Automation/engine/hostifaces/AsyncResult.cs +++ b/src/System.Management.Automation/engine/hostifaces/AsyncResult.cs @@ -152,7 +152,7 @@ internal void SetAsCompleted(Exception exception) } // call the user supplied callback - if (Callback != null) + if (Callback is not null) { Callback(this); } @@ -181,7 +181,7 @@ internal void SignalWaitHandle() { lock (SyncObject) { - if (_completedWaitHandle != null) + if (_completedWaitHandle is not null) { _completedWaitHandle.Set(); } @@ -226,7 +226,7 @@ internal void EndInvoke() _invokeOnThreadEvent = null; // Allow early GC // Operation is done: if an exception occured, throw it - if (Exception != null) + if (Exception is not null) { throw Exception; } @@ -248,7 +248,7 @@ internal bool InvokeCallbackOnThread(WaitCallback callback, object state) _invokeCallbackState = state; // Signal thread to run callback. - if (_invokeOnThreadEvent != null) + if (_invokeOnThreadEvent is not null) { _invokeOnThreadEvent.Set(); return true; diff --git a/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs b/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs index a94fffe5946..8a47590ca43 100644 --- a/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs +++ b/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs @@ -99,7 +99,7 @@ class ChoiceDescription { get { - Dbg.Assert(this.label != null, "label should not be null"); + Dbg.Assert(this.label is not null, "label should not be null"); return this.label; } @@ -122,7 +122,7 @@ class ChoiceDescription { get { - Dbg.Assert(this.helpMessage != null, "helpMessage should not be null"); + Dbg.Assert(this.helpMessage is not null, "helpMessage should not be null"); return this.helpMessage; } diff --git a/src/System.Management.Automation/engine/hostifaces/Command.cs b/src/System.Management.Automation/engine/hostifaces/Command.cs index 325eb0f7ba0..f58730a2dd9 100644 --- a/src/System.Management.Automation/engine/hostifaces/Command.cs +++ b/src/System.Management.Automation/engine/hostifaces/Command.cs @@ -373,14 +373,14 @@ public void MergeMyResults(PipelineResultTypes myResult, PipelineResultTypes toR void SetMergeSettingsOnCommandProcessor(CommandProcessorBase commandProcessor) { - Dbg.Assert(commandProcessor != null, "caller should validate the parameter"); + Dbg.Assert(commandProcessor is not null, "caller should validate the parameter"); MshCommandRuntime mcr = commandProcessor.Command.commandRuntime as MshCommandRuntime; if (_mergeUnclaimedPreviousCommandResults != PipelineResultTypes.None) { // Currently only merging previous unclaimed error and output is supported. - if (mcr != null) + if (mcr is not null) { mcr.MergeUnclaimedPreviousErrorResults = true; } @@ -454,7 +454,7 @@ private Pipe GetRedirectionPipe( CommandOrigin origin ) { - Dbg.Assert(executionContext != null, "Caller should verify the parameters"); + Dbg.Assert(executionContext is not null, "Caller should verify the parameters"); CommandProcessorBase commandProcessorBase; @@ -532,7 +532,7 @@ CommandOrigin origin CommandParameterCollection parameters = Parameters; - if (parameters != null) + if (parameters is not null) { bool isNativeCommand = commandProcessorBase is NativeCommandProcessor; foreach (CommandParameter publicParameter in parameters) @@ -608,27 +608,27 @@ internal static Command FromPSObjectForRemoting(PSObject commandAsPSObject) command.MergeUnclaimedPreviousCommandResults = RemotingDecoder.GetPropertyValue(commandAsPSObject, RemoteDataNameStrings.MergeUnclaimedPreviousCommandResults); // V3 merge instructions will not be returned by V2 server and this is expected. - if (commandAsPSObject.Properties[RemoteDataNameStrings.MergeError] != null) + if (commandAsPSObject.Properties[RemoteDataNameStrings.MergeError] is not null) { command.MergeInstructions[(int)MergeType.Error] = RemotingDecoder.GetPropertyValue(commandAsPSObject, RemoteDataNameStrings.MergeError); } - if (commandAsPSObject.Properties[RemoteDataNameStrings.MergeWarning] != null) + if (commandAsPSObject.Properties[RemoteDataNameStrings.MergeWarning] is not null) { command.MergeInstructions[(int)MergeType.Warning] = RemotingDecoder.GetPropertyValue(commandAsPSObject, RemoteDataNameStrings.MergeWarning); } - if (commandAsPSObject.Properties[RemoteDataNameStrings.MergeVerbose] != null) + if (commandAsPSObject.Properties[RemoteDataNameStrings.MergeVerbose] is not null) { command.MergeInstructions[(int)MergeType.Verbose] = RemotingDecoder.GetPropertyValue(commandAsPSObject, RemoteDataNameStrings.MergeVerbose); } - if (commandAsPSObject.Properties[RemoteDataNameStrings.MergeDebug] != null) + if (commandAsPSObject.Properties[RemoteDataNameStrings.MergeDebug] is not null) { command.MergeInstructions[(int)MergeType.Debug] = RemotingDecoder.GetPropertyValue(commandAsPSObject, RemoteDataNameStrings.MergeDebug); } - if (commandAsPSObject.Properties[RemoteDataNameStrings.MergeInformation] != null) + if (commandAsPSObject.Properties[RemoteDataNameStrings.MergeInformation] is not null) { command.MergeInstructions[(int)MergeType.Information] = RemotingDecoder.GetPropertyValue(commandAsPSObject, RemoteDataNameStrings.MergeInformation); } @@ -661,7 +661,7 @@ internal PSObject ToPSObjectForRemoting(Version psRPVersion) commandAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MergeUnclaimedPreviousCommandResults, this.MergeUnclaimedPreviousCommandResults)); - if (psRPVersion != null && + if (psRPVersion is not null && psRPVersion >= RemotingConstants.ProtocolVersionWin10RTM) { // V5 merge instructions @@ -671,7 +671,7 @@ internal PSObject ToPSObjectForRemoting(Version psRPVersion) commandAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MergeDebug, MergeInstructions[(int)MergeType.Debug])); commandAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MergeInformation, MergeInstructions[(int)MergeType.Information])); } - else if (psRPVersion != null && + else if (psRPVersion is not null && psRPVersion >= RemotingConstants.ProtocolVersionWin8RTM) { // V3 merge instructions. @@ -749,7 +749,7 @@ internal CimInstance ToCimInstance() Microsoft.Management.Infrastructure.CimType.Boolean); c.CimInstanceProperties.Add(isScriptProperty); - if (this.Parameters != null && this.Parameters.Count > 0) + if (this.Parameters is not null && this.Parameters.Count > 0) { List parameterInstances = new List(); foreach (var p in this.Parameters) diff --git a/src/System.Management.Automation/engine/hostifaces/Connection.cs b/src/System.Management.Automation/engine/hostifaces/Connection.cs index 1ffd5fea9f8..46a4653a610 100644 --- a/src/System.Management.Automation/engine/hostifaces/Connection.cs +++ b/src/System.Management.Automation/engine/hostifaces/Connection.cs @@ -536,7 +536,7 @@ internal static Runspace PrimaryRunspace set { var result = Interlocked.CompareExchange(ref s_primaryRunspace, value, null); - if (result != null) + if (result is not null) { throw new PSInvalidOperationException(RunspaceStrings.PrimaryRunspaceAlreadySet); } @@ -566,11 +566,11 @@ public static bool CanUseDefaultRunspace get { RunspaceBase runspace = Runspace.DefaultRunspace as RunspaceBase; - if (runspace != null) + if (runspace is not null) { Pipeline currentPipeline = runspace.GetCurrentlyRunningPipeline(); LocalPipeline localPipeline = currentPipeline as LocalPipeline; - if ((localPipeline != null) && (localPipeline.NestedPipelineExecutionThread != null)) + if ((localPipeline is not null) && (localPipeline.NestedPipelineExecutionThread is not null)) { return (localPipeline.NestedPipelineExecutionThread.ManagedThreadId @@ -954,11 +954,11 @@ internal void UpdateRunspaceAvailability(PipelineState pipelineState, bool raise else { RemoteRunspace remoteRunspace = this as RemoteRunspace; - RemoteDebugger remoteDebugger = (remoteRunspace != null) ? remoteRunspace.Debugger as RemoteDebugger : null; - Internal.ConnectCommandInfo remoteCommand = (remoteRunspace != null) ? remoteRunspace.RemoteCommand : null; + RemoteDebugger remoteDebugger = (remoteRunspace is not null) ? remoteRunspace.Debugger as RemoteDebugger : null; + Internal.ConnectCommandInfo remoteCommand = (remoteRunspace is not null) ? remoteRunspace.RemoteCommand : null; if (((pipelineState == PipelineState.Completed) || (pipelineState == PipelineState.Failed) || ((pipelineState == PipelineState.Stopped) && (this.RunspaceStateInfo.State == RunspaceState.Opened))) - && (remoteCommand != null) && (cmdInstanceId != null) && (remoteCommand.CommandId == cmdInstanceId)) + && (remoteCommand is not null) && (cmdInstanceId is not null) && (remoteCommand.CommandId == cmdInstanceId)) { // Completed, Failed, and Stopped with Runspace.Opened states are command finish states and we know // that the command is finished on the server. @@ -967,7 +967,7 @@ internal void UpdateRunspaceAvailability(PipelineState pipelineState, bool raise remoteRunspace.RunspacePool.RemoteRunspacePoolInternal.ConnectCommands = null; remoteCommand = null; - if ((remoteDebugger != null) && (pipelineState == PipelineState.Stopped)) + if ((remoteDebugger is not null) && (pipelineState == PipelineState.Stopped)) { // Notify remote debugger of a stop in case the stop occurred while command was in debug stop. remoteDebugger.OnCommandStopped(); @@ -976,7 +976,7 @@ 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; + Guid? pipeLineCmdInstance = (remotePipeline is not null && remotePipeline.PowerShell is not null) ? remotePipeline.PowerShell.InstanceId : (Guid?)null; if (currentPipeline is null) { // A runspace is available: @@ -986,9 +986,9 @@ internal void UpdateRunspaceAvailability(PipelineState pipelineState, bool raise // - if the remote runspace pool is marked as available for connection. if (remoteCommand is null) { - if (remoteRunspace != null) + if (remoteRunspace is not null) { - if ((remoteDebugger != null) && (pipelineState == PipelineState.Stopped)) + if ((remoteDebugger is not null) && (pipelineState == PipelineState.Stopped)) { // Notify remote debugger of a stop in case the stop occurred while command was in debug stop. remoteDebugger.OnCommandStopped(); @@ -1004,9 +1004,9 @@ internal void UpdateRunspaceAvailability(PipelineState pipelineState, bool raise } } } - else if ((cmdInstanceId != null) && (pipeLineCmdInstance != null) && (cmdInstanceId == pipeLineCmdInstance)) + else if ((cmdInstanceId is not null) && (pipeLineCmdInstance is not null) && (cmdInstanceId == pipeLineCmdInstance)) { - if ((remoteDebugger != null) && (pipelineState == PipelineState.Stopped)) + if ((remoteDebugger is not null) && (pipelineState == PipelineState.Stopped)) { // Notify remote debugger of a stop in case the stop occurred while command was in debug stop. remoteDebugger.OnCommandStopped(); @@ -1123,11 +1123,11 @@ protected void UpdateRunspaceAvailability(RunspaceState runspaceState, bool rais Internal.ConnectCommandInfo remoteCommand = null; bool remoteDebug = false; - if (remoteRunspace != null) + if (remoteRunspace is not null) { remoteCommand = remoteRunspace.RemoteCommand; RemoteDebugger remoteDebugger = remoteRunspace.Debugger as RemoteDebugger; - remoteDebug = (remoteDebugger != null) && remoteDebugger.IsRemoteDebug; + remoteDebug = (remoteDebugger is not null) && remoteDebugger.IsRemoteDebug; } switch (oldAvailability) @@ -1486,7 +1486,7 @@ public static Runspace GetRunspace(RunspaceConnectionInfo connectionInfo, Guid s /// PowerShell. internal void PushRunningPowerShell(PowerShell ps) { - Dbg.Assert(ps != null, "Caller should not pass in null reference."); + Dbg.Assert(ps is not null, "Caller should not pass in null reference."); lock (_syncObject) { @@ -1593,7 +1593,7 @@ public virtual Debugger Debugger get { var context = GetExecutionContext; - return (context != null) ? context.Debugger : null; + return (context is not null) ? context.Debugger : null; } } @@ -1675,7 +1675,7 @@ internal SessionStateProxy() internal SessionStateProxy(RunspaceBase runspace) { - Dbg.Assert(runspace != null, "Caller should validate the parameter"); + Dbg.Assert(runspace is not null, "Caller should validate the parameter"); _runspace = runspace; } diff --git a/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs b/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs index 8f958943a37..2cbd302acdd 100644 --- a/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs +++ b/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs @@ -626,7 +626,7 @@ public override Pipeline CreateNestedPipeline(string command, bool addToHistory) /// internal override bool HasAvailabilityChangedSubscribers { - get { return this.AvailabilityChanged != null; } + get { return this.AvailabilityChanged is not null; } } /// @@ -636,7 +636,7 @@ protected override void OnAvailabilityChanged(RunspaceAvailabilityEventArgs e) { EventHandler eh = this.AvailabilityChanged; - if (eh != null) + if (eh is not null) { try { @@ -749,7 +749,7 @@ protected void RaiseRunspaceStateEvents() stateChanged = this.StateChanged; hasAvailabilityChangedSubscribers = this.HasAvailabilityChangedSubscribers; - if (stateChanged != null || hasAvailabilityChangedSubscribers) + if (stateChanged is not null || hasAvailabilityChangedSubscribers) { tempEventQueue = _runspaceEventQueue; _runspaceEventQueue = new Queue(); @@ -763,7 +763,7 @@ protected void RaiseRunspaceStateEvents() } } - if (tempEventQueue != null) + if (tempEventQueue is not null) { while (tempEventQueue.Count > 0) { @@ -777,7 +777,7 @@ protected void RaiseRunspaceStateEvents() #pragma warning disable 56500 // Exception raised by events are not error condition for runspace // object. - if (stateChanged != null) + if (stateChanged is not null) { try { @@ -825,7 +825,7 @@ protected void RaiseRunspaceStateEvents() /// internal void AddToRunningPipelineList(PipelineBase pipeline) { - Dbg.Assert(pipeline != null, "caller should validate the parameter"); + Dbg.Assert(pipeline is not null, "caller should validate the parameter"); lock (_pipelineListLock) { @@ -859,7 +859,7 @@ internal void AddToRunningPipelineList(PipelineBase pipeline) /// internal void RemoveFromRunningPipelineList(PipelineBase pipeline) { - Dbg.Assert(pipeline != null, "caller should validate the parameter"); + Dbg.Assert(pipeline is not null, "caller should validate the parameter"); lock (_pipelineListLock) { @@ -1157,12 +1157,12 @@ private void DoConcurrentCheckAndMarkSessionStateProxyCallInProgress() } Pipeline runningPipeline = GetCurrentlyRunningPipeline(); - if (runningPipeline != null) + if (runningPipeline is not null) { // Detect if we're running an engine pulse, or we're running a nested pipeline // from an engine pulse if (runningPipeline == PulsePipeline || - (runningPipeline.IsNested && PulsePipeline != null)) + (runningPipeline.IsNested && PulsePipeline is not null)) { // If so, wait and try again // Release the lock before we wait for the pulse pipelines diff --git a/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs b/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs index 50438950c9a..789441c91f8 100644 --- a/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs +++ b/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs @@ -196,7 +196,7 @@ public string Name { get { - Dbg.Assert(label != null, "label should not be null"); + Dbg.Assert(label is not null, "label should not be null"); return label; } @@ -229,7 +229,7 @@ public string Name { get { - Dbg.Assert(helpMessage != null, "helpMessage should not be null"); + Dbg.Assert(helpMessage is not null, "helpMessage should not be null"); return helpMessage; } diff --git a/src/System.Management.Automation/engine/hostifaces/History.cs b/src/System.Management.Automation/engine/hostifaces/History.cs index 245f5a48052..b52b40f3263 100644 --- a/src/System.Management.Automation/engine/hostifaces/History.cs +++ b/src/System.Management.Automation/engine/hostifaces/History.cs @@ -31,7 +31,7 @@ public class HistoryInfo /// EndTime of execution. internal HistoryInfo(long pipelineId, string cmdline, PipelineState status, DateTime startTime, DateTime endTime) { - Dbg.Assert(cmdline != null, "caller should validate the parameter"); + Dbg.Assert(cmdline is not null, "caller should validate the parameter"); _pipelineId = pipelineId; CommandLine = cmdline; ExecutionStatus = status; @@ -237,7 +237,7 @@ internal void UpdateEntry(long id, PipelineState status, DateTime endTime, bool try { HistoryInfo entry = CoreGetEntry(id); - if (entry != null) + if (entry is not null) { entry.SetStatus(status); entry.SetEndTime(endTime); @@ -263,7 +263,7 @@ internal HistoryInfo GetEntry(long id) ReallocateBufferIfNeeded(); HistoryInfo entry = CoreGetEntry(id); - if (entry != null) + if (entry is not null) if (entry.Cleared == false) return entry.Clone(); @@ -572,7 +572,7 @@ internal void ClearEntry(long id) } HistoryInfo entry = CoreGetEntry(id); - if (entry != null) + if (entry is not null) { entry.Cleared = true; _countEntriesInBuffer--; @@ -663,7 +663,7 @@ private long SmallestIDinBuffer() for (int i = 0; i < _buffer.Length; i++) { // assign the first entry in the buffer as min. - if (_buffer[i] != null && _buffer[i].Cleared == false) + if (_buffer[i] is not null && _buffer[i].Cleared == false) { minID = _buffer[i].Id; break; @@ -672,7 +672,7 @@ private long SmallestIDinBuffer() // check for the minimum id that is not cleared for (int i = 0; i < _buffer.Length; i++) { - if (_buffer[i] != null && _buffer[i].Cleared == false) + if (_buffer[i] is not null && _buffer[i].Cleared == false) if (minID > _buffer[i].Id) minID = _buffer[i].Id; } @@ -762,8 +762,8 @@ private int GetHistorySize() { int historySize = 0; var executionContext = LocalPipeline.GetExecutionContextFromTLS(); - object obj = (executionContext != null) ? executionContext.GetVariableValue(SpecialVariables.HistorySizeVarPath) : null; - if (obj != null) + object obj = (executionContext is not null) ? executionContext.GetVariableValue(SpecialVariables.HistorySizeVarPath) : null; + if (obj is not null) { try { @@ -911,7 +911,7 @@ protected override void ProcessRecord() { History history = ((LocalRunspace)Context.CurrentRunspace).History; - if (_id != null) + if (_id is not null) { if (!_countParameterSpecified) { @@ -923,7 +923,7 @@ protected override void ProcessRecord() HistoryInfo entry = history.GetEntry(id); - if (entry != null && entry.Id == id) + if (entry is not null && entry.Id == id) { WriteObject(entry); } @@ -1024,7 +1024,7 @@ public string Id set { - if (_id != null) + if (_id is not null) { // Id has been set already. _multipleIdProvided = true; @@ -1055,7 +1055,7 @@ protected override void EndProcessing() var ctxRunspace = (LocalRunspace)Context.CurrentRunspace; History history = ctxRunspace.History; - Dbg.Assert(history != null, "History should be non null"); + Dbg.Assert(history is not null, "History should be non null"); // Get the history entry to invoke HistoryInfo entry = GetHistoryEntryToInvoke(history); @@ -1123,7 +1123,7 @@ protected override void EndProcessing() // This ensures that the command being run as nested runs in the correct language mode, because CreatePipelineProcessor() // always forces CommandOrigin to Internal for nested running commands, and Command.CreateCommandProcessor() forces Internal // commands to always run in FullLanguage mode unless in a nested prompt. - if (localRunspace != null) + if (localRunspace is not null) { localRunspace.InInternalNestedPrompt = ps.IsNested; } @@ -1138,7 +1138,7 @@ protected override void EndProcessing() { history.RemoveFromInvokeHistoryEntrySet(entry); - if (localRunspace != null) + if (localRunspace is not null) { localRunspace.InInternalNestedPrompt = false; } @@ -1197,7 +1197,7 @@ private HistoryInfo GetHistoryEntryToInvoke(History history) PopulateIdAndCommandLine(); // User specified a commandline. Get list of all history entries // and find latest match - if (_commandLine != null) + if (_commandLine is not null) { HistoryInfo[] entries = history.GetEntries(0, -1, false); @@ -1384,16 +1384,16 @@ void BeginProcessing() void ProcessRecord() { History history = ((LocalRunspace)Context.CurrentRunspace).History; - Dbg.Assert(history != null, "History should be non null"); + Dbg.Assert(history is not null, "History should be non null"); - if (InputObject != null) + if (InputObject is not null) { foreach (PSObject input in InputObject) { // Wrap the inputobject in PSObject and convert it to // HistoryInfo object. HistoryInfo infoToAdd = GetHistoryInfoObject(input); - if (infoToAdd != null) + if (infoToAdd is not null) { long id = history.AddEntry ( @@ -1761,7 +1761,7 @@ private void ClearHistoryByID() ); } // if id parameter is not present - if (_id != null) + if (_id is not null) { // if count parameter is not present if (!_countParameterSpecified) @@ -1771,7 +1771,7 @@ private void ClearHistoryByID() { Dbg.Assert(id > 0, "ValidateRangeAttribute should not allow this"); HistoryInfo entry = _history.GetEntry(id); - if (entry != null && entry.Id == id) + if (entry is not null && entry.Id == id) { _history.ClearEntry(entry.Id); } @@ -1871,7 +1871,7 @@ private void ClearHistoryByCmdLine() ); } // if command line is not present - if (_commandline != null) + if (_commandline is not null) { // if count parameter is not present if (!_countParameterSpecified) @@ -1968,7 +1968,7 @@ private void ClearHistoryEntries(long id, int count, string cmdline, SwitchParam // Clear the History value. foreach (HistoryInfo entry in _entries) { - if (entry != null && entry.Cleared == false) + if (entry is not null && entry.Cleared == false) _history.ClearEntry(entry.Id); } diff --git a/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs b/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs index 8881491c973..b978edb55a1 100644 --- a/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs +++ b/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs @@ -345,7 +345,7 @@ internal static List GetSuggestion(Runspace runspace) // If we got information about the error invocation, // we can be more careful with the errors we pass along - if ((lastErrorRecord != null) && (lastErrorRecord.InvocationInfo != null)) + if ((lastErrorRecord is not null) && (lastErrorRecord.InvocationInfo is not null)) { if (lastErrorRecord.InvocationInfo.HistoryId == lastHistory.Id) lastError = lastErrorRecord; @@ -462,10 +462,10 @@ internal static List GetSuggestion(HistoryInfo lastHistory, object lastE } else if (matchType == SuggestionMatchType.Error) { - if (lastError != null) + if (lastError is not null) { Exception lastException = lastError as Exception; - if (lastException != null) + if (lastException is not null) { matchText = lastException.Message; } @@ -477,7 +477,7 @@ internal static List GetSuggestion(HistoryInfo lastHistory, object lastE } else if (matchType == SuggestionMatchType.ErrorId) { - if (lastError != null && lastError is ErrorRecord errorRecord) + if (lastError is not null && lastError is ErrorRecord errorRecord) { matchText = errorRecord.FullyQualifiedErrorId; } @@ -693,7 +693,7 @@ runspace.ConnectionInfo is VMConnectionInfo || SSHConnectionInfo sshConnectionInfo = runspace.ConnectionInfo as SSHConnectionInfo; // Usernames are case-sensitive on Unix systems - if (sshConnectionInfo != null && + if (sshConnectionInfo is not null && !string.IsNullOrEmpty(sshConnectionInfo.UserName) && !System.Environment.UserName.Equals(sshConnectionInfo.UserName, StringComparison.Ordinal)) { @@ -808,7 +808,7 @@ public static Collection InvokeOnRunspace(PSCommand command, Runspace throw new PSArgumentNullException(nameof(runspace)); } - if ((runspace.Debugger != null) && runspace.Debugger.InBreakpoint) + if ((runspace.Debugger is not null) && runspace.Debugger.InBreakpoint) { // Use the Debugger API to run the command when a runspace is stopped in the debugger. PSDataCollection output = new PSDataCollection(); @@ -826,7 +826,7 @@ public static Collection InvokeOnRunspace(PSCommand command, Runspace if (runspace.ConnectionInfo is null) { // Local runspace. Make a nested PowerShell object as needed. - ps.SetIsNested(runspace.GetCurrentlyRunningPipeline() != null); + ps.SetIsNested(runspace.GetCurrentlyRunningPipeline() is not null); } using (ps) diff --git a/src/System.Management.Automation/engine/hostifaces/InformationalRecord.cs b/src/System.Management.Automation/engine/hostifaces/InformationalRecord.cs index 55fd16d7d12..a7fced331c8 100644 --- a/src/System.Management.Automation/engine/hostifaces/InformationalRecord.cs +++ b/src/System.Management.Automation/engine/hostifaces/InformationalRecord.cs @@ -100,7 +100,7 @@ internal void SetInvocationInfo(InvocationInfo invocationInfo) // // Copy a snapshot of the PipelineIterationInfo from the InvocationInfo to this InformationalRecord // - if (invocationInfo.PipelineIterationInfo != null) + if (invocationInfo.PipelineIterationInfo is not null) { int[] snapshot = (int[])invocationInfo.PipelineIterationInfo.Clone(); diff --git a/src/System.Management.Automation/engine/hostifaces/InternalHost.cs b/src/System.Management.Automation/engine/hostifaces/InternalHost.cs index edbb2c754bf..f386f3ee768 100644 --- a/src/System.Management.Automation/engine/hostifaces/InternalHost.cs +++ b/src/System.Management.Automation/engine/hostifaces/InternalHost.cs @@ -38,10 +38,10 @@ internal class InternalHost : PSHost, IHostSupportsInteractiveSession /// internal InternalHost(PSHost externalHost, ExecutionContext executionContext) { - Dbg.Assert(externalHost != null, "must supply an PSHost"); + Dbg.Assert(externalHost is not null, "must supply an PSHost"); Dbg.Assert(!(externalHost is InternalHost), "try to create an InternalHost from another InternalHost"); - Dbg.Assert(executionContext != null, "must supply an ExecutionContext"); + Dbg.Assert(executionContext is not null, "must supply an ExecutionContext"); _externalHostRef = new ObjectRef(externalHost); Context = executionContext; @@ -238,11 +238,11 @@ internal void EnterNestedPrompt(InternalCommand callingCommand) try { localRunspace = this.Runspace as LocalRunspace; } catch (PSNotImplementedException) { } - if (localRunspace != null) + if (localRunspace is not null) { Pipeline currentlyRunningPipeline = this.Runspace.GetCurrentlyRunningPipeline(); - if ((currentlyRunningPipeline != null) && + if ((currentlyRunningPipeline is not null) && (currentlyRunningPipeline == localRunspace.PulsePipeline)) throw new InvalidOperationException(); } @@ -278,7 +278,7 @@ internal void EnterNestedPrompt(InternalCommand callingCommand) PSPropertyInfo stackTraceProperty = null; object oldCommandInfo = null; object oldStackTrace = null; - if (callingCommand != null) + if (callingCommand is not null) { Dbg.Assert(callingCommand.Context == Context, "I expect that the contexts should match"); @@ -346,12 +346,12 @@ internal void EnterNestedPrompt(InternalCommand callingCommand) } finally { - if (commandInfoProperty != null) + if (commandInfoProperty is not null) { commandInfoProperty.Value = oldCommandInfo; } - if (stackTraceProperty != null) + if (stackTraceProperty is not null) { stackTraceProperty.Value = oldStackTrace; } diff --git a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs index 9a33f119069..8b515c875cd 100644 --- a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs @@ -24,7 +24,7 @@ class InternalHostUserInterface : PSHostUserInterface, IHostUISupportsMultipleCh // parent may not be null, however - Dbg.Assert(parentHost != null, "parent may not be null"); + Dbg.Assert(parentHost is not null, "parent may not be null"); if (parentHost is null) { throw PSTraceSource.NewArgumentNullException(nameof(parentHost)); @@ -34,7 +34,7 @@ class InternalHostUserInterface : PSHostUserInterface, IHostUISupportsMultipleCh PSHostRawUserInterface rawui = null; - if (externalUI != null) + if (externalUI is not null) { rawui = externalUI.RawUI; } @@ -80,7 +80,7 @@ public override public override bool SupportsVirtualTerminal { - get { return (_externalUI != null) ? _externalUI.SupportsVirtualTerminal : false; } + get { return (_externalUI is not null) ? _externalUI.SupportsVirtualTerminal : false; } } /// @@ -390,7 +390,7 @@ internal void WriteDebugRecord(DebugRecord record) /// DebugRecord. internal void WriteDebugInfoBuffers(DebugRecord record) { - if (_informationalBuffers != null) + if (_informationalBuffers is not null) { _informationalBuffers.AddDebug(record); } @@ -591,7 +591,7 @@ public override } // Write to Information Buffers - if (_informationalBuffers != null) + if (_informationalBuffers is not null) { _informationalBuffers.AddProgress(record); } @@ -644,7 +644,7 @@ internal void WriteVerboseRecord(VerboseRecord record) /// VerboseRecord. internal void WriteVerboseInfoBuffers(VerboseRecord record) { - if (_informationalBuffers != null) + if (_informationalBuffers is not null) { _informationalBuffers.AddVerbose(record); } @@ -688,7 +688,7 @@ internal void WriteWarningRecord(WarningRecord record) /// WarningRecord. internal void WriteWarningInfoBuffers(WarningRecord record) { - if (_informationalBuffers != null) + if (_informationalBuffers is not null) { _informationalBuffers.AddWarning(record); } @@ -714,7 +714,7 @@ internal void WriteInformationRecord(InformationRecord record) /// WarningRecord. internal void WriteInformationInfoBuffers(InformationRecord record) { - if (_informationalBuffers != null) + if (_informationalBuffers is not null) { _informationalBuffers.AddInformation(record); } @@ -935,7 +935,7 @@ private Collection EmulatePromptForMultipleChoice(string caption, Collection choices, IEnumerable defaultChoices) { - Dbg.Assert(_externalUI != null, "externalUI cannot be null."); + Dbg.Assert(_externalUI is not null, "externalUI cannot be null."); if (choices is null) { @@ -949,7 +949,7 @@ private Collection EmulatePromptForMultipleChoice(string caption, } Dictionary defaultChoiceKeys = new Dictionary(); - if (defaultChoices != null) + if (defaultChoices is not null) { foreach (int defaultChoice in defaultChoices) { diff --git a/src/System.Management.Automation/engine/hostifaces/ListModifier.cs b/src/System.Management.Automation/engine/hostifaces/ListModifier.cs index 96120d97770..d8a5f839244 100644 --- a/src/System.Management.Automation/engine/hostifaces/ListModifier.cs +++ b/src/System.Management.Automation/engine/hostifaces/ListModifier.cs @@ -124,7 +124,7 @@ public PSListModifier(Hashtable hash) } IEnumerable enumerable = LanguagePrimitives.GetEnumerable(entry.Value); - if (enumerable != null) + if (enumerable is not null) { foreach (object obj in enumerable) { diff --git a/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs b/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs index a09e1a0f4f5..69833cb7ed6 100644 --- a/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs +++ b/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs @@ -198,7 +198,7 @@ public override void ResetRunspaceState() RunspaceStrings.ConcurrentInvokeNotAllowed); } - if (invalidOperation != null) + if (invalidOperation is not null) { invalidOperation.Source = "ResetRunspaceState"; throw invalidOperation; @@ -401,7 +401,7 @@ internal static void SetDebugPreference(string processName, List appDoma Hashtable debugPreferenceCache = null; string[] appDomainNames = null; - if (appDomainName != null) + if (appDomainName is not null) { appDomainNames = appDomainName.ToArray(); } @@ -419,7 +419,7 @@ internal static void SetDebugPreference(string processName, List appDoma else { debugPreferenceCache = GetDebugPreferenceCache(null); - if (debugPreferenceCache != null) + if (debugPreferenceCache is not null) { if (enable) { @@ -440,10 +440,10 @@ internal static void SetDebugPreference(string processName, List appDoma // processDebugPreference would point to null if debug preference is enabled for all app domains. // If processDebugPreference is not null then it means that user has selected specific // appdomins for which the debug preference has to be enabled. - if (processDebugPreference != null) + if (processDebugPreference is not null) { List cachedAppDomainNames = null; - if (processDebugPreference.AppDomainNames != null && processDebugPreference.AppDomainNames.Length > 0) + if (processDebugPreference.AppDomainNames is not null && processDebugPreference.AppDomainNames.Length > 0) { cachedAppDomainNames = new List(processDebugPreference.AppDomainNames); @@ -482,10 +482,10 @@ internal static void SetDebugPreference(string processName, List appDoma // processDebugPreference would point to null if debug preference is enabled for all app domains. // If processDebugPreference is not null then it means that user has selected specific // appdomins for which the debug preference has to be enabled. - if (processDebugPreference != null) + if (processDebugPreference is not null) { List cachedAppDomainNames = null; - if (processDebugPreference.AppDomainNames != null && processDebugPreference.AppDomainNames.Length > 0) + if (processDebugPreference.AppDomainNames is not null && processDebugPreference.AppDomainNames.Length > 0) { cachedAppDomainNames = new List(processDebugPreference.AppDomainNames); @@ -546,7 +546,7 @@ private static Hashtable GetDebugPreferenceCache(Runspace runspace) Hashtable debugPreferenceCache = null; using (PowerShell ps = PowerShell.Create()) { - if (runspace != null) + if (runspace is not null) { ps.Runspace = runspace; } @@ -554,7 +554,7 @@ private static Hashtable GetDebugPreferenceCache(Runspace runspace) ps.AddCommand("Import-Clixml").AddParameter("Path", LocalRunspace.s_debugPreferenceCachePath); Collection psObjects = ps.Invoke(); - if (psObjects != null && psObjects.Count == 1) + if (psObjects is not null && psObjects.Count == 1) { debugPreferenceCache = psObjects[0].BaseObject as Hashtable; } @@ -571,10 +571,10 @@ private static Hashtable GetDebugPreferenceCache(Runspace runspace) private static DebugPreference GetProcessSpecificDebugPreference(object debugPreference) { DebugPreference processDebugPreference = null; - if (debugPreference != null) + if (debugPreference is not null) { PSObject debugPreferencePsObject = debugPreference as PSObject; - if (debugPreferencePsObject != null) + if (debugPreferencePsObject is not null) { processDebugPreference = LanguagePrimitives.ConvertTo(debugPreferencePsObject); } @@ -630,7 +630,7 @@ private void OpenThreadProc() /// private void DoOpenHelper() { - Dbg.Assert(InitialSessionState != null, "InitialSessionState should not be null"); + Dbg.Assert(InitialSessionState is not null, "InitialSessionState should not be null"); // NTRAID#Windows Out Of Band Releases-915851-2005/09/13 if (_disposed) { @@ -671,7 +671,7 @@ private void DoOpenHelper() // Log engine for end of engine life if (startLifeCycleEventWritten) { - Dbg.Assert(_engine.Context != null, "if startLifeCycleEventWritten is true, ExecutionContext must be present"); + Dbg.Assert(_engine.Context is not null, "if startLifeCycleEventWritten is true, ExecutionContext must be present"); MshLog.LogEngineLifecycleEvent(_engine.Context, EngineState.Stopped); } @@ -696,13 +696,13 @@ private void DoOpenHelper() // Now do initial state configuration that requires an active runspace Exception initError = InitialSessionState.BindRunspace(this, s_runspaceInitTracer); - if (initError != null) + if (initError is not null) { // Log engine health event LogEngineHealthEvent(initError); // Log engine for end of engine life - Debug.Assert(_engine.Context != null, + Debug.Assert(_engine.Context is not null, "if startLifeCycleEventWritten is true, ExecutionContext must be present"); MshLog.LogEngineLifecycleEvent(_engine.Context, EngineState.Stopped); @@ -743,7 +743,7 @@ internal void LogEngineHealthEvent(Exception exception, int id, Dictionary additionalInfo) { - Dbg.Assert(exception != null, "Caller should validate the parameter"); + Dbg.Assert(exception is not null, "Caller should validate the parameter"); LogContext logContext = new LogContext(); logContext.EngineVersion = Version.ToString(); @@ -837,10 +837,10 @@ private void DoCloseHelper() if (!haveOpenRunspaces) { ExecutionContext executionContext = this.GetExecutionContext; - if (executionContext != null) + if (executionContext is not null) { PSHostUserInterface hostUI = executionContext.EngineHostInterface.UI; - if (hostUI != null) + if (hostUI is not null) { hostUI.StopAllTranscribing(); } @@ -850,7 +850,7 @@ private void DoCloseHelper() } // Generate the shutdown event - if (Events != null) + if (Events is not null) Events.GenerateEvent(PSEngineEvent.Exiting, null, new object[] { }, null, true, false); // Stop all running pipelines @@ -922,7 +922,7 @@ private void DoCloseHelper() } var localRunspace = r as LocalRunspace; - if (localRunspace != null && localRunspace.Host is IHostProvidesTelemetryData) + if (localRunspace is not null && localRunspace.Host is IHostProvidesTelemetryData) { hostProvidesExitTelemetry = true; break; @@ -1003,7 +1003,7 @@ private void StopOrDisconnectAllJobs() // Otherwise add disconnectable runspaces to list so that // they can be disconnected. IEnumerable jobRunspaces = job.GetRunspaces(); - if (jobRunspaces != null) + if (jobRunspaces is not null) { disconnectRunspaces.AddRange(jobRunspaces); } @@ -1025,7 +1025,7 @@ private void StopOrDisconnectAllJobs() internal void ReleaseDebugger() { Debugger debugger = Debugger; - if (debugger != null) + if (debugger is not null) { try { @@ -1245,7 +1245,7 @@ protected override void Dispose(bool disposing) _jobManager = null; _jobRepository = null; _runspaceRepository = null; - if (RunspaceOpening != null) + if (RunspaceOpening is not null) { RunspaceOpening.Dispose(); RunspaceOpening = null; @@ -1254,7 +1254,7 @@ protected override void Dispose(bool disposing) Platform.RemoveTemporaryDirectory(); // Dispose the event manager - if (this.ExecutionContext != null && this.ExecutionContext.Events != null) + if (this.ExecutionContext is not null && this.ExecutionContext.Events is not null) { try { @@ -1283,7 +1283,7 @@ public override void Close() base.Close(); // call base.Close() first to make it stop the pipeline - if (_pipelineThread != null) + if (_pipelineThread is not null) { _pipelineThread.Close(); } @@ -1465,7 +1465,7 @@ internal override void StartOperation() // If the runspace supports disconnect semantics and is running a command, // then disconnect it rather than closing it. if (_remoteRunspace.CanDisconnect && - _remoteRunspace.GetCurrentlyRunningPipeline() != null) + _remoteRunspace.GetCurrentlyRunningPipeline() is not null) { _remoteRunspace.DisconnectAsync(); } @@ -1552,7 +1552,7 @@ internal RunspaceOpenModuleLoadException( string moduleName, PSDataCollection errors) : base(StringUtil.Format(RunspaceStrings.ErrorLoadingModulesOnRunspaceOpen, moduleName, - (errors != null && errors.Count > 0 && errors[0] != null) ? errors[0].ToString() : string.Empty), null) + (errors is not null && errors.Count > 0 && errors[0] is not null) ? errors[0].ToString() : string.Empty), null) { _errors = errors; this.SetErrorId("ErrorLoadingModulesOnRunspaceOpen"); diff --git a/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs b/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs index 1b89ad3617c..61e96f03816 100644 --- a/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs +++ b/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs @@ -161,7 +161,7 @@ protected override void StartPipelineExecution() _identityToImpersonate = null; // If impersonation identity flow is requested, then get current thread impersonation, if any. - if ((InvocationSettings != null) && InvocationSettings.FlowImpersonationPolicy) + if ((InvocationSettings is not null) && InvocationSettings.FlowImpersonationPolicy) { Utils.TryGetWindowsImpersonatedIdentity(out _identityToImpersonate); } @@ -182,7 +182,7 @@ protected override void StartPipelineExecution() ApartmentState apartmentState; - if (InvocationSettings != null && InvocationSettings.ApartmentState != ApartmentState.Unknown) + if (InvocationSettings is not null && InvocationSettings.ApartmentState != ApartmentState.Unknown) { apartmentState = InvocationSettings.ApartmentState; // set the user-defined apartmentstate. } @@ -438,7 +438,7 @@ private FlowControlException InvokeHelper() { exitCode = (int)ee.Argument; - if ((InvocationSettings != null) && (InvocationSettings.ExposeFlowControlExceptions)) + if ((InvocationSettings is not null) && (InvocationSettings.ExposeFlowControlExceptions)) { flowControlException = ee; } @@ -454,7 +454,7 @@ private FlowControlException InvokeHelper() } catch (FlowControlException e) { - if ((InvocationSettings != null) && (InvocationSettings.ExposeFlowControlExceptions) && + if ((InvocationSettings is not null) && (InvocationSettings.ExposeFlowControlExceptions) && ((e is BreakException) || (e is ContinueException) || (e is TerminateException))) { // Save FlowControl exception for return to caller. @@ -473,7 +473,7 @@ private FlowControlException InvokeHelper() finally { // Call StopProcessing() for all the commands. - if (pipelineProcessor != null && pipelineProcessor.Commands != null) + if (pipelineProcessor is not null && pipelineProcessor.Commands is not null) { for (int i = 0; i < pipelineProcessor.Commands.Count; i++) { @@ -491,7 +491,7 @@ private FlowControlException InvokeHelper() } PSLocalEventManager eventManager = LocalRunspace.Events as PSLocalEventManager; - if (eventManager != null) + if (eventManager is not null) { eventManager.ProcessPendingActions(); } @@ -522,7 +522,7 @@ private FlowControlException InvokeHelper() finally { // 2004/02/26-JonN added IDisposable to PipelineProcessor - if (pipelineProcessor != null) + if (pipelineProcessor is not null) { pipelineProcessor.Dispose(); pipelineProcessor = null; @@ -539,7 +539,7 @@ private FlowControlException InvokeHelper() /// private void InvokeThreadProcImpersonate() { - if (_identityToImpersonate != null) + if (_identityToImpersonate is not null) { WindowsIdentity.RunImpersonated( _identityToImpersonate.AccessToken, @@ -563,11 +563,11 @@ private void InvokeThreadProc() try { // Set up pipeline internal host if it is available. - if (InvocationSettings != null && InvocationSettings.Host != null) + if (InvocationSettings is not null && InvocationSettings.Host is not null) { InternalHost internalHost = InvocationSettings.Host as InternalHost; - if (internalHost != null) // if we are given an internal host, use the external host + if (internalHost is not null) // if we are given an internal host, use the external host { LocalRunspace.ExecutionContext.InternalHost.SetHostRef(internalHost.ExternalHost); } @@ -594,7 +594,7 @@ private void InvokeThreadProc() FlowControlException flowControlException = InvokeHelper(); - if (flowControlException != null) + if (flowControlException is not null) { // Let pipeline propagate the BreakException. SetPipelineState(Runspaces.PipelineState.Failed, flowControlException); @@ -637,7 +637,7 @@ private void InvokeThreadProc() // Remove pipeline specific host if it was set. // Win8:464422 Revert the host only if this pipeline invocation changed it // with 464422 a nested pipeline reverts the host, although the nested pipeline did not set it. - if ((InvocationSettings != null && InvocationSettings.Host != null) && + if ((InvocationSettings is not null && InvocationSettings.Host is not null) && (LocalRunspace.ExecutionContext.InternalHost.IsHostRefSet)) { LocalRunspace.ExecutionContext.InternalHost.RevertHostRef(); @@ -851,7 +851,7 @@ private PipelineProcessor CreatePipelineProcessor() // runs nested commands). This prevents the script debugger command line from seeing private commands. if (IsNested && !LocalRunspace.InNestedPrompt && - !((LocalRunspace.Debugger != null) && (LocalRunspace.Debugger.InBreakpoint))) + !((LocalRunspace.Debugger is not null) && (LocalRunspace.Debugger.InBreakpoint))) { commandOrigin = CommandOrigin.Internal; } @@ -887,7 +887,7 @@ private PipelineProcessor CreatePipelineProcessor() // Set the internal command origin member on the command object at this point... commandProcessorBase.Command.CommandOriginInternal = CommandOrigin.Internal; commandProcessorBase.Command.MyInvocation.InvocationName = command.CommandInfo.Name; - if (command.Parameters != null) + if (command.Parameters is not null) { foreach (CommandParameter publicParameter in command.Parameters) { @@ -939,20 +939,20 @@ private CommandProcessorBase CreateCommandProcessBase(Command command) } CmdletInfo cmdletInfo = commandInfo as CmdletInfo; - if (cmdletInfo != null) + if (cmdletInfo is not null) { return new CommandProcessor(cmdletInfo, LocalRunspace.ExecutionContext); } IScriptCommandInfo functionInfo = commandInfo as IScriptCommandInfo; - if (functionInfo != null) + if (functionInfo is not null) { return new CommandProcessor(functionInfo, LocalRunspace.ExecutionContext, useLocalScope: false, fromScriptFile: false, sessionState: LocalRunspace.ExecutionContext.EngineSessionState); } ApplicationInfo applicationInfo = commandInfo as ApplicationInfo; - if (applicationInfo != null) + if (applicationInfo is not null) { return new NativeCommandProcessor(applicationInfo, LocalRunspace.ExecutionContext); } @@ -966,7 +966,7 @@ private CommandProcessorBase CreateCommandProcessBase(Command command) /// private void InitStreams() { - if (LocalRunspace.ExecutionContext != null) + if (LocalRunspace.ExecutionContext is not null) { _oldExternalErrorOutput = LocalRunspace.ExecutionContext.ExternalErrorOutput; _oldExternalSuccessOutput = LocalRunspace.ExecutionContext.ExternalSuccessOutput; @@ -981,7 +981,7 @@ private void InitStreams() /// private void ClearStreams() { - if (LocalRunspace.ExecutionContext != null) + if (LocalRunspace.ExecutionContext is not null) { LocalRunspace.ExecutionContext.ExternalErrorOutput = _oldExternalErrorOutput; LocalRunspace.ExecutionContext.ExternalSuccessOutput = _oldExternalSuccessOutput; @@ -1357,7 +1357,7 @@ internal void Pop(bool fromSteppablePipeline) _stack.Peek().ExecutionFailed = true; } // If this is the last pipeline processor on the stack, then propagate it's execution status - if (_stack.Count == 1 && _localPipeline != null) + if (_stack.Count == 1 && _localPipeline is not null) { _localPipeline.SetHadErrors(oldPipe.ExecutionFailed); } @@ -1384,7 +1384,7 @@ internal void Stop() if (copyStack.Length > 0) { PipelineProcessor topLevel = copyStack[copyStack.Length - 1]; - if (topLevel != null && _localPipeline != null) + if (topLevel is not null && _localPipeline is not null) { _localPipeline.SetHadErrors(topLevel.ExecutionFailed); } diff --git a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs index 1560de4f230..e5b56107119 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs @@ -184,7 +184,7 @@ public virtual void WriteLine(ConsoleColor foregroundColor, ConsoleColor backgro // expressly not checking for value is null so that attempts to write a null cause an exception - if ((value != null) && (value.Length != 0)) + if ((value is not null) && (value.Length != 0)) { Write(foregroundColor, backgroundColor, value); } @@ -273,10 +273,10 @@ private TranscriptionData TranscriptionData // If we have access to a runspace, use the transcription data for that runspace. // This is important when you have multiple runspaces within a host. LocalRunspace localRunspace = Runspace.DefaultRunspace as LocalRunspace; - if (localRunspace != null) + if (localRunspace is not null) { _volatileTranscriptionData = localRunspace.TranscriptionData; - if (_volatileTranscriptionData != null) + if (_volatileTranscriptionData is not null) { return _volatileTranscriptionData; } @@ -284,7 +284,7 @@ private TranscriptionData TranscriptionData // Otherwise, use the last stored transcription data. This will let us transcribe // errors where the runspace has gone away. - if (_volatileTranscriptionData != null) + if (_volatileTranscriptionData is not null) { return _volatileTranscriptionData; } @@ -317,7 +317,7 @@ internal void TranscribeCommand(string commandText, InvocationInfo invocation) // the command generates output, or when we are told to invoke ignore the next command. foreach (TranscriptionOption transcript in TranscriptionData.Transcripts.Prepend(TranscriptionData.SystemTranscript)) { - if (transcript != null) + if (transcript is not null) { lock (transcript.OutputToLog) { @@ -349,13 +349,13 @@ private bool ShouldIgnoreCommand(string logElement, InvocationInfo invocation) { string commandName = logElement; - if (invocation != null) + if (invocation is not null) { commandName = invocation.InvocationName; // Do not transcribe Out-Default CmdletInfo invocationCmdlet = invocation.MyCommand as CmdletInfo; - if (invocationCmdlet != null) + if (invocationCmdlet is not null) { if (invocationCmdlet.ImplementingType == typeof(Microsoft.PowerShell.Commands.OutDefaultCommand)) { @@ -405,7 +405,7 @@ internal void IgnoreCommand(string commandText, InvocationInfo invocation) TranscriptionData.CommandBeingIgnored = commandText; TranscriptionData.IsHelperCommand = false; - if ((invocation != null) && (invocation.MyCommand != null)) + if ((invocation is not null) && (invocation.MyCommand is not null)) { TranscriptionData.CommandBeingIgnored = invocation.MyCommand.Name; } @@ -455,7 +455,7 @@ internal bool IsTranscribing get { CheckSystemTranscript(); - return (TranscriptionData.Transcripts.Count > 0) || (TranscriptionData.SystemTranscript != null); + return (TranscriptionData.Transcripts.Count > 0) || (TranscriptionData.SystemTranscript is not null); } } @@ -466,7 +466,7 @@ private void CheckSystemTranscript() if (TranscriptionData.SystemTranscript is null) { TranscriptionData.SystemTranscript = PSHostUserInterface.GetSystemTranscriptOption(TranscriptionData.SystemTranscript); - if (TranscriptionData.SystemTranscript != null) + if (TranscriptionData.SystemTranscript is not null) { LogTranscriptHeader(null, TranscriptionData.SystemTranscript); } @@ -501,7 +501,7 @@ private void LogTranscriptHeader(System.Management.Automation.Remoting.PSSenderI string username = Environment.UserDomainName + "\\" + Environment.UserName; string runAsUser = username; - if (senderInfo != null) + if (senderInfo is not null) { username = senderInfo.UserInfo.Identity.Name; } @@ -513,16 +513,16 @@ private void LogTranscriptHeader(System.Management.Automation.Remoting.PSSenderI { object value = versionInfo[versionKey]; - if (value != null) + if (value is not null) { var arrayValue = value as object[]; - string valueString = arrayValue != null ? string.Join(", ", arrayValue) : value.ToString(); + string valueString = arrayValue is not null ? string.Join(", ", arrayValue) : value.ToString(); versionInfoFooter.AppendLine(versionKey + ": " + valueString); } } string configurationName = string.Empty; - if (senderInfo != null && !string.IsNullOrEmpty(senderInfo.ConfigurationName)) + if (senderInfo is not null && !string.IsNullOrEmpty(senderInfo.ConfigurationName)) { configurationName = senderInfo.ConfigurationName; } @@ -599,7 +599,7 @@ internal void StopAllTranscribing() lock (TranscriptionData) { - if (TranscriptionData.SystemTranscript != null) + if (TranscriptionData.SystemTranscript is not null) { LogTranscriptFooter(TranscriptionData.SystemTranscript); TranscriptionData.SystemTranscript.Dispose(); @@ -625,7 +625,7 @@ internal void TranscribeResult(Runspace sourceRunspace, string resultText) // If the runspace that this result applies to is not the current runspace, update Runspace.DefaultRunspace // so that the transcript paths / etc. will be available to the TranscriptionData accessor. Runspace originalDefaultRunspace = null; - if (sourceRunspace != null) + if (sourceRunspace is not null) { originalDefaultRunspace = Runspace.DefaultRunspace; Runspace.DefaultRunspace = sourceRunspace; @@ -634,7 +634,7 @@ internal void TranscribeResult(Runspace sourceRunspace, string resultText) try { // If we're ignoring a command, ignore its output. - if (TranscriptionData.CommandBeingIgnored != null) + if (TranscriptionData.CommandBeingIgnored is not null) { // If we're ignoring a prompt, capture the value if (string.Equals("prompt", TranscriptionData.CommandBeingIgnored, StringComparison.OrdinalIgnoreCase)) @@ -648,7 +648,7 @@ internal void TranscribeResult(Runspace sourceRunspace, string resultText) resultText = resultText.TrimEnd(); foreach (TranscriptionOption transcript in TranscriptionData.Transcripts.Prepend(TranscriptionData.SystemTranscript)) { - if (transcript != null) + if (transcript is not null) { lock (transcript.OutputToLog) { @@ -659,7 +659,7 @@ internal void TranscribeResult(Runspace sourceRunspace, string resultText) } finally { - if (originalDefaultRunspace != null) + if (originalDefaultRunspace is not null) { Runspace.DefaultRunspace = originalDefaultRunspace; } @@ -684,7 +684,7 @@ internal void TranscribeCommandComplete(InvocationInfo invocation) { FlushPendingOutput(); - if (invocation != null) + if (invocation is not null) { // If we're ignoring a command that was internal, we still want the // results of Out-Default. However, if it was a host helper command, @@ -696,8 +696,8 @@ internal void TranscribeCommandComplete(InvocationInfo invocation) } // If we're completing a command that we were ignoring, start transcribing results / etc. again. - if ((TranscriptionData.CommandBeingIgnored != null) && - (invocation != null) && (invocation.MyCommand != null) && + if ((TranscriptionData.CommandBeingIgnored is not null) && + (invocation is not null) && (invocation.MyCommand is not null) && string.Equals(commandNameToCheck, invocation.MyCommand.Name, StringComparison.OrdinalIgnoreCase)) { TranscriptionData.CommandBeingIgnored = null; @@ -718,7 +718,7 @@ private void FlushPendingOutput() { foreach (TranscriptionOption transcript in TranscriptionData.Transcripts.Prepend(TranscriptionData.SystemTranscript)) { - if (transcript != null) + if (transcript is not null) { lock (transcript.OutputToLog) { @@ -1013,7 +1013,7 @@ internal static TranscriptionOption GetSystemTranscriptOption(TranscriptionOptio ? Utils.GetPolicySetting(Utils.SystemWideThenCurrentUserConfig) : s_transcriptionSettingCache.Value; - if (transcription != null) + if (transcription is not null) { // If we have an existing system transcript for this process, use that. // Otherwise, populate the static variable with the result of the group policy setting. @@ -1044,7 +1044,7 @@ private static TranscriptionOption GetTranscriptOptionFromSettings(Transcription if (transcriptConfig.EnableTranscripting == true) { - if (currentTranscript != null) + if (currentTranscript is not null) { return currentTranscript; } @@ -1052,7 +1052,7 @@ private static TranscriptionOption GetTranscriptOptionFromSettings(Transcription transcript = new TranscriptionOption(); // Pull out the transcript path - if (transcriptConfig.OutputDirectory != null) + if (transcriptConfig.OutputDirectory is not null) { transcript.Path = GetTranscriptPath(transcriptConfig.OutputDirectory, true); } @@ -1254,7 +1254,7 @@ public void Dispose() outputWait += 100; } - if (_contentWriter != null) + if (_contentWriter is not null) { _contentWriter.Flush(); _contentWriter.Dispose(); @@ -1366,8 +1366,8 @@ internal static void BuildHotkeysAndPlainLabels(Collection ch /// internal static int DetermineChoicePicked(string response, Collection choices, string[,] hotkeysAndPlainLabels) { - Diagnostics.Assert(choices != null, "choices: expected a value"); - Diagnostics.Assert(hotkeysAndPlainLabels != null, "hotkeysAndPlainLabels: expected a value"); + Diagnostics.Assert(choices is not null, "choices: expected a value"); + Diagnostics.Assert(hotkeysAndPlainLabels is not null, "hotkeysAndPlainLabels: expected a value"); int result = -1; diff --git a/src/System.Management.Automation/engine/hostifaces/NativeCultureResolver.cs b/src/System.Management.Automation/engine/hostifaces/NativeCultureResolver.cs index 1d21fa952a0..097861a4f31 100644 --- a/src/System.Management.Automation/engine/hostifaces/NativeCultureResolver.cs +++ b/src/System.Management.Automation/engine/hostifaces/NativeCultureResolver.cs @@ -66,7 +66,7 @@ public override CultureInfo Parent // This is required because there is difference in the parent hierarchy // between CLR and Windows for Chinese. Ex: Native windows has // zh-CN->zh-Hans->neutral whereas CLR has zh-CN->zh-CHS->zh-Hans->neutral - if ((base.Parent != null) && (!string.IsNullOrEmpty(base.Parent.Name))) + if ((base.Parent is not null) && (!string.IsNullOrEmpty(base.Parent.Name))) { return ImmediateParent; } @@ -76,7 +76,7 @@ public override CultureInfo Parent // returns fallback cultures (specified by the user) // and also adds neutral culture where appropriate. // Ex: ja-jp ja en-us en - while ((_fallbacks != null) && (_fallbacks.Length > 0)) + while ((_fallbacks is not null) && (_fallbacks.Length > 0)) { string fallback = _fallbacks[0]; string[] fallbacksForParent = null; @@ -122,7 +122,7 @@ private VistaCultureInfo ImmediateParent // remove the parentCulture from the m_fallbacks list. // ie., remove duplicates from the parent hierarchy. string[] fallbacksForTheParent = null; - if (_fallbacks != null) + if (_fallbacks is not null) { fallbacksForTheParent = new string[_fallbacks.Length]; int currentIndex = 0; diff --git a/src/System.Management.Automation/engine/hostifaces/PSCommand.cs b/src/System.Management.Automation/engine/hostifaces/PSCommand.cs index 65308f354f9..c1d9a5a6260 100644 --- a/src/System.Management.Automation/engine/hostifaces/PSCommand.cs +++ b/src/System.Management.Automation/engine/hostifaces/PSCommand.cs @@ -92,7 +92,7 @@ public PSCommand AddCommand(string command) throw PSTraceSource.NewArgumentNullException("cmdlet"); } - if (_owner != null) + if (_owner is not null) { _owner.AssertChangesAreAccepted(); } @@ -136,7 +136,7 @@ public PSCommand AddCommand(string cmdlet, bool useLocalScope) throw PSTraceSource.NewArgumentNullException(nameof(cmdlet)); } - if (_owner != null) + if (_owner is not null) { _owner.AssertChangesAreAccepted(); } @@ -178,7 +178,7 @@ public PSCommand AddScript(string script) throw PSTraceSource.NewArgumentNullException(nameof(script)); } - if (_owner != null) + if (_owner is not null) { _owner.AssertChangesAreAccepted(); } @@ -223,7 +223,7 @@ public PSCommand AddScript(string script, bool useLocalScope) throw PSTraceSource.NewArgumentNullException(nameof(script)); } - if (_owner != null) + if (_owner is not null) { _owner.AssertChangesAreAccepted(); } @@ -261,7 +261,7 @@ public PSCommand AddCommand(Command command) throw PSTraceSource.NewArgumentNullException(nameof(command)); } - if (_owner != null) + if (_owner is not null) { _owner.AssertChangesAreAccepted(); } @@ -308,7 +308,7 @@ public PSCommand AddParameter(string parameterName, object value) new object[] { "PSCommand" }); } - if (_owner != null) + if (_owner is not null) { _owner.AssertChangesAreAccepted(); } @@ -350,7 +350,7 @@ public PSCommand AddParameter(string parameterName) new object[] { "PSCommand" }); } - if (_owner != null) + if (_owner is not null) { _owner.AssertChangesAreAccepted(); } @@ -392,7 +392,7 @@ public PSCommand AddArgument(object value) new object[] { "PSCommand" }); } - if (_owner != null) + if (_owner is not null) { _owner.AssertChangesAreAccepted(); } @@ -509,7 +509,7 @@ private void Initialize(string command, bool isScript, bool? useLocalScope) { _commands = new CommandCollection(); - if (command != null) + if (command is not null) { _currentCommand = new Command(command, isScript, useLocalScope); _commands.Add(_currentCommand); diff --git a/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs b/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs index b3ddbe0f6a3..edd869cb721 100644 --- a/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs +++ b/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs @@ -291,7 +291,7 @@ public static implicit operator PSDataCollection(T valueToConvert) public static implicit operator PSDataCollection(object[] arrayToConvert) { PSDataCollection psdc = new PSDataCollection(); - if (arrayToConvert != null) + if (arrayToConvert is not null) { foreach (var ae in arrayToConvert) { @@ -552,7 +552,7 @@ public void Complete() // raise the events outside of the lock. if (raiseEvents) { - if (_readWaitHandle != null) + if (_readWaitHandle is not null) { // unblock any readers waiting on the handle _readWaitHandle.Set(); @@ -561,7 +561,7 @@ public void Complete() // A temporary variable is used as the Completed may // reach null (because of -='s) after the null check EventHandler tempCompleted = Completed; - if (tempCompleted != null) + if (tempCompleted is not null) { tempCompleted(this, EventArgs.Empty); } @@ -801,7 +801,7 @@ public void Clear() { lock (SyncObject) { - if (_data != null) + if (_data is not null) { _data.Clear(); } @@ -1177,7 +1177,7 @@ public Collection ReadAll() /// Maximum number of elements to read. internal Collection ReadAndRemove(int readCount) { - Dbg.Assert(_data != null, "Collection cannot be null"); + Dbg.Assert(_data is not null, "Collection cannot be null"); Dbg.Assert(readCount >= 0, "ReadCount cannot be negative"); @@ -1202,7 +1202,7 @@ internal Collection ReadAndRemove(int readCount) } } - if (_readWaitHandle != null) + if (_readWaitHandle is not null) { if (_data.Count > 0 || !_isOpen) { @@ -1227,7 +1227,7 @@ internal T ReadAndRemoveAt0() lock (SyncObject) { - if (_data != null && _data.Count > 0) + if (_data is not null && _data.Count > 0) { value = _data[0]; _data.RemoveAt(0); @@ -1355,7 +1355,7 @@ private void RaiseEvents(Guid psInstanceId, int index) bool raiseDataAdded = false; lock (SyncObject) { - if (_readWaitHandle != null) + if (_readWaitHandle is not null) { // TODO: Should ObjectDisposedException be caught. @@ -1406,7 +1406,7 @@ private void RaiseDataAddingEvent(Guid psInstanceId, object itemAdded) // A temporary variable is used as the DataAdding may // reach null (because of -='s) after the null check EventHandler tempDataAdding = DataAdding; - if (tempDataAdding != null) + if (tempDataAdding is not null) { tempDataAdding(this, new DataAddingEventArgs(psInstanceId, itemAdded)); } @@ -1417,7 +1417,7 @@ private void RaiseDataAddedEvent(Guid psInstanceId, int index) // A temporary variable is used as the DataAdded may // reach null (because of -='s) after the null check EventHandler tempDataAdded = DataAdded; - if (tempDataAdded != null) + if (tempDataAdded is not null) { tempDataAdded(this, new DataAddedEventArgs(psInstanceId, index)); } @@ -1571,7 +1571,7 @@ internal void DecrementRef() if (_refCount != 0 && (!_blockingEnumerator || _refCount != 1)) return; // release threads blocked on waithandle - if (_readWaitHandle != null) + if (_readWaitHandle is not null) { _readWaitHandle.Set(); } @@ -1735,7 +1735,7 @@ internal int RefCount /// internal bool PulseIdleEvent { - get { return (IdleEvent != null); } + get { return (IdleEvent is not null); } } internal event EventHandler IdleEvent; @@ -1800,13 +1800,13 @@ protected void Dispose(bool disposing) lock (SyncObject) { - if (_readWaitHandle != null) + if (_readWaitHandle is not null) { _readWaitHandle.Dispose(); _readWaitHandle = null; } - if (_data != null) + if (_data is not null) { _data.Clear(); } @@ -1861,7 +1861,7 @@ internal sealed class PSDataCollectionEnumerator : IBlockingEnumerator /// internal PSDataCollectionEnumerator(PSDataCollection collection, bool neverBlock) { - Dbg.Assert(collection != null, + Dbg.Assert(collection is not null, "Collection cannot be null"); Dbg.Assert(!collection.ReleaseOnEnumeration || !collection.IsEnumerated, "shouldn't enumerate more than once if ReleaseOnEnumeration is true"); @@ -2103,7 +2103,7 @@ internal PSDataCollection Debug /// internal void AddProgress(ProgressRecord item) { - if (progress != null) + if (progress is not null) { progress.InternalAdd(_psInstanceId, item); } @@ -2116,7 +2116,7 @@ internal void AddProgress(ProgressRecord item) /// internal void AddVerbose(VerboseRecord item) { - if (verbose != null) + if (verbose is not null) { verbose.InternalAdd(_psInstanceId, item); } @@ -2129,7 +2129,7 @@ internal void AddVerbose(VerboseRecord item) /// internal void AddDebug(DebugRecord item) { - if (debug != null) + if (debug is not null) { debug.InternalAdd(_psInstanceId, item); } @@ -2142,7 +2142,7 @@ internal void AddDebug(DebugRecord item) /// internal void AddWarning(WarningRecord item) { - if (Warning != null) + if (Warning is not null) { Warning.InternalAdd(_psInstanceId, item); } @@ -2155,7 +2155,7 @@ internal void AddWarning(WarningRecord item) /// internal void AddInformation(InformationRecord item) { - if (Information != null) + if (Information is not null) { Information.InternalAdd(_psInstanceId, item); } diff --git a/src/System.Management.Automation/engine/hostifaces/PSTask.cs b/src/System.Management.Automation/engine/hostifaces/PSTask.cs index b54a1ac8093..f41bc046b5b 100644 --- a/src/System.Management.Automation/engine/hostifaces/PSTask.cs +++ b/src/System.Management.Automation/engine/hostifaces/PSTask.cs @@ -138,11 +138,11 @@ private void HandleInformationData() private void HandleStateChanged(PSInvocationStateChangedEventArgs stateChangeInfo) { - if (_dataStreamWriter != null) + if (_dataStreamWriter is not null) { // Treat any terminating exception as a non-terminating error record var newStateInfo = stateChangeInfo.InvocationStateInfo; - if (newStateInfo.Reason != null) + if (newStateInfo.Reason is not null) { var errorRecord = new ErrorRecord( newStateInfo.Reason, @@ -351,7 +351,7 @@ public PSInvocationState State get { PowerShell ps = _powershell; - if (ps != null) + if (ps is not null) { return ps.InvocationStateInfo.State; } @@ -430,18 +430,18 @@ public void Dispose() /// Runspace used to run task. public void Start(Runspace runspace) { - if (_powershell != null) + if (_powershell is not null) { Dbg.Assert(false, "A PSTask can be started only once."); return; } - Dbg.Assert(runspace != null, "Task runspace cannot be null."); + Dbg.Assert(runspace is not null, "Task runspace cannot be null."); _runspace = runspace; // If available, set current working directory on the runspace. // Temporarily set the newly created runspace as the thread default runspace for any needed module loading. - if (_currentLocationPath != null) + if (_currentLocationPath is not null) { var oldDefaultRunspace = Runspace.DefaultRunspace; try @@ -475,7 +475,7 @@ public void Start(Runspace runspace) // Start the script running in a new thread _powershell.AddScript(_scriptBlockToRun.ToString()); _powershell.Commands.Commands[0].DollarUnderbar = _dollarUnderbar; - if (_usingValuesMap != null && _usingValuesMap.Count > 0) + if (_usingValuesMap is not null && _usingValuesMap.Count > 0) { _powershell.AddParameter(Parser.VERBATIM_ARGUMENT, _usingValuesMap); } @@ -488,7 +488,7 @@ public void Start(Runspace runspace) /// public void SignalStop() { - if (_powershell != null) + if (_powershell is not null) { _powershell.BeginStop(null, null); } @@ -853,7 +853,7 @@ public void Close() private void HandleTaskStateChanged(object sender, PSInvocationStateChangedEventArgs args) { var task = sender as PSTaskBase; - Dbg.Assert(task != null, "State changed sender must always be PSTaskBase"); + Dbg.Assert(task is not null, "State changed sender must always be PSTaskBase"); var stateInfo = args.InvocationStateInfo; switch (stateInfo.State) { @@ -946,7 +946,7 @@ private Runspace GetRunspace(int taskId) private void ReturnRunspace(PSTaskBase task) { var runspace = task.Runspace; - Dbg.Assert(runspace != null, "Task runspace cannot be null."); + Dbg.Assert(runspace is not null, "Task runspace cannot be null."); if (_useRunspacePool && runspace.RunspaceStateInfo.State == RunspaceState.Opened && runspace.RunspaceAvailability == RunspaceAvailability.Available) diff --git a/src/System.Management.Automation/engine/hostifaces/Parameter.cs b/src/System.Management.Automation/engine/hostifaces/Parameter.cs index 94da3f2a0e2..7b5e197a1c5 100644 --- a/src/System.Management.Automation/engine/hostifaces/Parameter.cs +++ b/src/System.Management.Automation/engine/hostifaces/Parameter.cs @@ -47,7 +47,7 @@ public CommandParameter(string name) /// public CommandParameter(string name, object value) { - if (name != null) + if (name is not null) { if (string.IsNullOrWhiteSpace(name)) { @@ -103,7 +103,7 @@ internal static CommandParameter FromCommandParameterInternal(CommandParameterIn name = name + " "; } - Diagnostics.Assert(name != null, "'name' variable should be initialized at this point"); + Diagnostics.Assert(name is not null, "'name' variable should be initialized at this point"); Diagnostics.Assert(name[0].IsDash(), "first character in parameter name must be a dash"); Diagnostics.Assert(name.Trim().Length != 1, "Parameter name has to have some non-whitespace characters in it"); } @@ -113,7 +113,7 @@ internal static CommandParameter FromCommandParameterInternal(CommandParameterIn return new CommandParameter(name, internalParameter.ArgumentValue); } - if (name != null) // either a switch parameter or first part of parameter+argument + if (name is not null) // either a switch parameter or first part of parameter+argument { return new CommandParameter(name); } diff --git a/src/System.Management.Automation/engine/hostifaces/Pipeline.cs b/src/System.Management.Automation/engine/hostifaces/Pipeline.cs index 29532a803fe..8bb76956a06 100644 --- a/src/System.Management.Automation/engine/hostifaces/Pipeline.cs +++ b/src/System.Management.Automation/engine/hostifaces/Pipeline.cs @@ -200,7 +200,7 @@ internal PipelineStateInfo(PipelineState state, Exception reason) /// internal PipelineStateInfo(PipelineStateInfo pipelineStateInfo) { - Dbg.Assert(pipelineStateInfo != null, "caller should validate the parameter"); + Dbg.Assert(pipelineStateInfo is not null, "caller should validate the parameter"); State = pipelineStateInfo.State; Reason = pipelineStateInfo.Reason; @@ -258,7 +258,7 @@ public sealed class PipelineStateEventArgs : EventArgs /// internal PipelineStateEventArgs(PipelineStateInfo pipelineStateInfo) { - Dbg.Assert(pipelineStateInfo != null, "caller should validate the parameter"); + Dbg.Assert(pipelineStateInfo is not null, "caller should validate the parameter"); PipelineStateInfo = pipelineStateInfo; } @@ -309,7 +309,7 @@ internal Pipeline(Runspace runspace, CommandCollection command) } // This constructor is used only internally. // Caller should make sure the input is valid - Dbg.Assert(command != null, "Command cannot be null"); + Dbg.Assert(command is not null, "Command cannot be null"); InstanceId = runspace.GeneratePipelineId(); Commands = command; diff --git a/src/System.Management.Automation/engine/hostifaces/PowerShell.cs b/src/System.Management.Automation/engine/hostifaces/PowerShell.cs index da58d172288..bc16df8925e 100644 --- a/src/System.Management.Automation/engine/hostifaces/PowerShell.cs +++ b/src/System.Management.Automation/engine/hostifaces/PowerShell.cs @@ -289,7 +289,7 @@ public sealed class PSInvocationStateChangedEventArgs : EventArgs /// internal PSInvocationStateChangedEventArgs(PSInvocationStateInfo psStateInfo) { - Dbg.Assert(psStateInfo != null, "caller should validate the parameter"); + Dbg.Assert(psStateInfo is not null, "caller should validate the parameter"); InvocationStateInfo = psStateInfo; } @@ -623,13 +623,13 @@ public sealed class PowerShell : IDisposable /// private PowerShell(PSCommand command, Collection extraCommands, object rsConnection) { - Dbg.Assert(command != null, "command must not be null"); + Dbg.Assert(command is not null, "command must not be null"); ExtraCommands = extraCommands ?? new Collection(); RunningExtraCommands = false; _psCommand = command; _psCommand.Owner = this; RemoteRunspace remoteRunspace = rsConnection as RemoteRunspace; - _rsConnection = remoteRunspace != null ? remoteRunspace.RunspacePool : rsConnection; + _rsConnection = remoteRunspace is not null ? remoteRunspace.RunspacePool : rsConnection; InstanceId = Guid.NewGuid(); InvocationStateInfo = new PSInvocationStateInfo(PSInvocationState.NotStarted, null); OutputBuffer = null; @@ -672,7 +672,7 @@ internal PowerShell(ConnectCommandInfo connectCmdInfo, object rsConnection) _runspacePool = (RunspacePool)rsConnection; } - Dbg.Assert(_runspacePool != null, "Invalid rsConnection parameter>"); + Dbg.Assert(_runspacePool is not null, "Invalid rsConnection parameter>"); RemotePowerShell = new ClientRemotePowerShell(this, _runspacePool.RemoteRunspacePoolInternal); } @@ -699,7 +699,7 @@ internal PowerShell(ObjectStreamBase inputstream, PSDataCollectionStream errordatastream = (PSDataCollectionStream)errorstream; _errorBuffer = errordatastream.ObjectStore; - if (runspacePool != null && runspacePool.RemoteRunspacePoolInternal != null) + if (runspacePool is not null && runspacePool.RemoteRunspacePoolInternal is not null) { RemotePowerShell = new ClientRemotePowerShell(this, runspacePool.RemoteRunspacePoolInternal); } @@ -748,7 +748,7 @@ internal PowerShell(ConnectCommandInfo connectCmdInfo, ObjectStreamBase inputstr internal void InitForRemotePipeline(CommandCollection command, ObjectStreamBase inputstream, ObjectStreamBase outputstream, ObjectStreamBase errorstream, PSInvocationSettings settings, bool redirectShellErrorOutputPipe) { - Dbg.Assert(command != null, "A command collection need to be specified"); + Dbg.Assert(command is not null, "A command collection need to be specified"); _psCommand = new PSCommand(command[0]); _psCommand.Owner = this; @@ -922,7 +922,7 @@ public static PowerShell Create(Runspace runspace) [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "ps", Justification = "ps represents PowerShell and is used at many places.")] public PowerShell CreateNestedPowerShell() { - if ((_worker != null) && (_worker.CurrentlyRunningPipeline != null)) + if ((_worker is not null) && (_worker.CurrentlyRunningPipeline is not null)) { PowerShell result = new PowerShell(new PSCommand(), null, _worker.CurrentlyRunningPipeline.Runspace); @@ -1816,7 +1816,7 @@ public Runspace Runspace { AssertChangesAreAccepted(); - if (_runspace != null && IsRunspaceOwner) + if (_runspace is not null && IsRunspaceOwner) { _runspace.Dispose(); _runspace = null; @@ -1843,7 +1843,7 @@ private void SetRunspace(Runspace runspace, bool owner) { _rsConnection = remoteRunspace.RunspacePool; - if (RemotePowerShell != null) + if (RemotePowerShell is not null) { RemotePowerShell.Clear(); RemotePowerShell.Dispose(); @@ -1887,13 +1887,13 @@ public RunspacePool RunspacePool set { - if (value != null) + if (value is not null) { lock (_syncObject) { AssertChangesAreAccepted(); - if (_runspace != null && IsRunspaceOwner) + if (_runspace is not null && IsRunspaceOwner) { _runspace.Dispose(); _runspace = null; @@ -1905,7 +1905,7 @@ public RunspacePool RunspacePool if (_runspacePool.IsRemote) { - if (RemotePowerShell != null) + if (RemotePowerShell is not null) { RemotePowerShell.Clear(); RemotePowerShell.Dispose(); @@ -1958,7 +1958,7 @@ public Collection Connect() EndInvokeAsyncResult = null; Collection results = null; - if (psAsyncResult.Output != null) + if (psAsyncResult.Output is not null) { results = psAsyncResult.Output.ReadAll(); } @@ -2005,7 +2005,7 @@ public IAsyncResult ConnectAsync( // runspace if it is currently disconnected. CheckRunspacePoolAndConnect(); - if (_connectCmdInfo != null) + if (_connectCmdInfo is not null) { // // This is a reconstruct/connect scenario and we create new state. @@ -2021,7 +2021,7 @@ public IAsyncResult ConnectAsync( inputStream.Close(); // Output stream. - if (output != null) + if (output is not null) { // Use the supplied output buffer. OutputBuffer = output; @@ -2049,16 +2049,16 @@ public IAsyncResult ConnectAsync( { // If this is not a reconstruct scenario then this must be a PowerShell object that was // previously disconnected, and all state should be valid. - Dbg.Assert((_invokeAsyncResult != null && RemotePowerShell.Initialized), + Dbg.Assert((_invokeAsyncResult is not null && RemotePowerShell.Initialized), "AsyncResult and RemotePowerShell objects must be valid here."); - if (output != null || - invocationCallback != null || + if (output is not null || + invocationCallback is not null || _invokeAsyncResult.IsCompleted) { // A new async object is needed. PSDataCollection streamToUse; - if (output != null) + if (output is not null) { streamToUse = output; OutputBuffer = output; @@ -2081,7 +2081,7 @@ public IAsyncResult ConnectAsync( _invokeAsyncResult = new PowerShellAsyncResult( InstanceId, invocationCallback ?? _invokeAsyncResult.Callback, - (invocationCallback != null) ? state : _invokeAsyncResult.AsyncState, + (invocationCallback is not null) ? state : _invokeAsyncResult.AsyncState, streamToUse, true); } @@ -2102,7 +2102,7 @@ public IAsyncResult ConnectAsync( // re-throw the exception InvalidRunspacePoolStateException poolException = exception as InvalidRunspacePoolStateException; - if (poolException != null && _runspace != null) // the pool exception was actually thrown by a runspace + if (poolException is not null && _runspace is not null) // the pool exception was actually thrown by a runspace { throw poolException.ToInvalidRunspaceStateException(); } @@ -2175,7 +2175,7 @@ internal void InvokeWithDebugger( Debugger debugger = _runspace.Debugger; bool addToHistory = true; - if (debugger != null && + if (debugger is not null && Commands.Commands.Count > 0) { Command cmd = this.Commands.Commands[0]; @@ -2183,7 +2183,7 @@ internal void InvokeWithDebugger( DebuggerCommand dbgCommandResult = debugger.InternalProcessCommand( cmd.CommandText, output); - if (dbgCommandResult.ResumeAction != null || + if (dbgCommandResult.ResumeAction is not null || dbgCommandResult.ExecutedByDebugger) { output.Add(new PSObject(dbgCommandResult)); @@ -2910,7 +2910,7 @@ public IAsyncResult BeginInvoke(PSDataCollection input, PSInvocationSettin { DetermineIsBatching(); - if (OutputBuffer != null) + if (OutputBuffer is not null) { if (_isBatching || ExtraCommands.Count != 0) { @@ -3320,7 +3320,7 @@ private IAsyncResult BeginBatchInvoke(PSDataCollection } RunspacePool pool = _rsConnection as RunspacePool; - if ((pool != null) && (pool.IsRemote)) + if ((pool is not null) && (pool.IsRemote)) { // Server supports batch invocation, in this case, we just send everything to the server and return immediately if (ServerSupportsBatchInvocation()) @@ -3362,7 +3362,7 @@ private void BatchInvocationWorkItem(object state) BatchInvocationContext context = state as BatchInvocationContext; - Debug.Assert(context != null, "Context should never be null"); + Debug.Assert(context is not null, "Context should never be null"); PSCommand backupCommand = _psCommand; try @@ -3394,7 +3394,7 @@ private void BatchInvocationWorkItem(object state) SetHadErrors(true); // Stop if necessarily - if ((_batchInvocationSettings != null) && _batchInvocationSettings.ErrorActionPreference == ActionPreference.Stop) + if ((_batchInvocationSettings is not null) && _batchInvocationSettings.ErrorActionPreference == ActionPreference.Stop) { _stopBatchExecution = true; AppendExceptionToErrorStream(e); @@ -3477,7 +3477,7 @@ private void BatchInvocationCallback(IAsyncResult result) SetHadErrors(true); ActionPreference preference; - if (_batchInvocationSettings != null) + if (_batchInvocationSettings is not null) { preference = (_batchInvocationSettings.ErrorActionPreference.HasValue) ? _batchInvocationSettings.ErrorActionPreference.Value @@ -3485,7 +3485,7 @@ private void BatchInvocationCallback(IAsyncResult result) } else { - preference = (Runspace != null) ? + preference = (Runspace is not null) ? (ActionPreference)Runspace.SessionStateProxy.GetVariable("ErrorActionPreference") : ActionPreference.Continue; } @@ -3614,7 +3614,7 @@ private void AppendExceptionToErrorStream(Exception e) { IContainsErrorRecord er = e as IContainsErrorRecord; - if (er != null && er.ErrorRecord != null) + if (er is not null && er.ErrorRecord is not null) { this.Streams.Error.Add(er.ErrorRecord); } @@ -3673,7 +3673,7 @@ public PSDataCollection EndInvoke(IAsyncResult asyncResult) catch (InvalidRunspacePoolStateException exception) { SetHadErrors(true); - if (_runspace != null) // the pool exception was actually thrown by a runspace + if (_runspace is not null) // the pool exception was actually thrown by a runspace { throw exception.ToInvalidRunspaceStateException(); } @@ -3894,7 +3894,7 @@ internal ExecutionContext GetContextFromTLS() string scriptText = this.Commands.Commands.Count > 0 ? this.Commands.Commands[0].CommandText : null; PSInvalidOperationException e = null; - if (scriptText != null) + if (scriptText is not null) { scriptText = ErrorCategoryInfo.Ellipsize(System.Globalization.CultureInfo.CurrentUICulture, scriptText); e = PSTraceSource.NewInvalidOperationException( @@ -4098,12 +4098,12 @@ private void Dispose(bool disposing) _isDisposed = true; } - if (OutputBuffer != null && OutputBufferOwner) + if (OutputBuffer is not null && OutputBufferOwner) { OutputBuffer.Dispose(); } - if (_errorBuffer != null && ErrorBufferOwner) + if (_errorBuffer is not null && ErrorBufferOwner) { _errorBuffer.Dispose(); } @@ -4113,7 +4113,7 @@ private void Dispose(bool disposing) _runspace.Dispose(); } - if (RemotePowerShell != null) + if (RemotePowerShell is not null) { RemotePowerShell.Dispose(); } @@ -4130,7 +4130,7 @@ private void InternalClearSuppressExceptions() { lock (_syncObject) { - if (_worker != null) + if (_worker is not null) { _worker.InternalClearSuppressExceptions(); } @@ -4150,7 +4150,7 @@ private void RaiseStateChangeEvent(PSInvocationStateInfo stateInfo) // Don't update for RemoteRunspace and nested PowerShell since this is used // only internally by the remote debugger. RemoteRunspace remoteRunspace = _runspace as RemoteRunspace; - if (remoteRunspace != null && !this.IsNested) + if (remoteRunspace is not null && !this.IsNested) { _runspace.UpdateRunspaceAvailability(InvocationStateInfo.State, true, InstanceId); } @@ -4178,7 +4178,7 @@ internal void SetStateChanged(PSInvocationStateInfo stateInfo) PSInvocationState previousState; // copy pipeline HasdErrors property to PowerShell instance... - if (_worker != null && _worker.CurrentlyRunningPipeline != null) + if (_worker is not null && _worker.CurrentlyRunningPipeline is not null) { SetHadErrors(_worker.CurrentlyRunningPipeline.HadErrors); } @@ -4250,7 +4250,7 @@ internal void SetStateChanged(PSInvocationStateInfo stateInfo) InternalClearSuppressExceptions(); // Ensure remote receive queue is not blocked. - if (RemotePowerShell != null) + if (RemotePowerShell is not null) { ResumeIncomingData(); } @@ -4259,7 +4259,7 @@ internal void SetStateChanged(PSInvocationStateInfo stateInfo) { if (RunningExtraCommands) { - if (tempInvokeAsyncResult != null) + if (tempInvokeAsyncResult is not null) { tempInvokeAsyncResult.SetAsCompleted(InvocationStateInfo.Reason); } @@ -4270,13 +4270,13 @@ internal void SetStateChanged(PSInvocationStateInfo stateInfo) { RaiseStateChangeEvent(InvocationStateInfo.Clone()); - if (tempInvokeAsyncResult != null) + if (tempInvokeAsyncResult is not null) { tempInvokeAsyncResult.SetAsCompleted(InvocationStateInfo.Reason); } } - if (tempStopAsyncResult != null) + if (tempStopAsyncResult is not null) { tempStopAsyncResult.SetAsCompleted(null); } @@ -4292,7 +4292,7 @@ internal void SetStateChanged(PSInvocationStateInfo stateInfo) finally { // takes care exception occured with invokeAsyncResult - if (isExceptionOccured && (tempStopAsyncResult != null)) + if (isExceptionOccured && (tempStopAsyncResult is not null)) { tempStopAsyncResult.Release(); } @@ -4303,14 +4303,14 @@ internal void SetStateChanged(PSInvocationStateInfo stateInfo) try { // Ensure remote receive queue is not blocked. - if (RemotePowerShell != null) + if (RemotePowerShell is not null) { ResumeIncomingData(); } // If this command was disconnected and was also invoked synchronously then // we throw an exception on the calling thread. - if (_commandInvokedSynchronously && (tempInvokeAsyncResult != null)) + if (_commandInvokedSynchronously && (tempInvokeAsyncResult is not null)) { tempInvokeAsyncResult.SetAsCompleted(new RuntimeException(PowerShellStrings.DiscOnSyncCommand)); } @@ -4318,7 +4318,7 @@ internal void SetStateChanged(PSInvocationStateInfo stateInfo) // This object can be disconnected even if "BeginStop" was called if it is a remote object // and robust connections is retrying a failed network connection. // In this case release the stop wait handle to prevent not responding. - if (tempStopAsyncResult != null) + if (tempStopAsyncResult is not null) { tempStopAsyncResult.SetAsCompleted(null); } @@ -4343,7 +4343,7 @@ internal void SetStateChanged(PSInvocationStateInfo stateInfo) finally { // takes care exception occured with invokeAsyncResult - if (isExceptionOccured && (tempStopAsyncResult != null)) + if (isExceptionOccured && (tempStopAsyncResult is not null)) { tempStopAsyncResult.Release(); } @@ -4372,7 +4372,7 @@ private void CloseInputBufferOnReconnection(PSInvocationState previousState) // synchronous Connect() method will wait indefinitely for the command to complete. if (previousState == PSInvocationState.Disconnected && _commandInvokedSynchronously && - RemotePowerShell.InputStream != null && + RemotePowerShell.InputStream is not null && RemotePowerShell.InputStream.IsOpen && RemotePowerShell.InputStream.Count > 0) { @@ -4387,7 +4387,7 @@ internal void ClearRemotePowerShell() { lock (_syncObject) { - if (RemotePowerShell != null) + if (RemotePowerShell is not null) { RemotePowerShell.Clear(); } @@ -4462,7 +4462,7 @@ internal void SetIsNested(bool isNested) private void CoreInvoke(IEnumerable input, PSDataCollection output, PSInvocationSettings settings) { PSDataCollection inputBuffer = null; - if (input != null) + if (input is not null) { inputBuffer = new PSDataCollection(); foreach (object o in input) @@ -4497,7 +4497,7 @@ private void CoreInvokeHelper(PSDataCollection input, P Runspace rsToUse = null; if (!IsNested) { - if (pool != null) + if (pool is not null) { #if !UNIX VerifyThreadSettings(settings, pool.ApartmentState, pool.ThreadOptions, false); @@ -4512,7 +4512,7 @@ private void CoreInvokeHelper(PSDataCollection input, P else { rsToUse = _rsConnection as Runspace; - if (rsToUse != null) + if (rsToUse is not null) { #if !UNIX VerifyThreadSettings(settings, rsToUse.ApartmentState, rsToUse.ThreadOptions, false); @@ -4538,7 +4538,7 @@ private void CoreInvokeHelper(PSDataCollection input, P else { rsToUse = _rsConnection as Runspace; - Dbg.Assert(rsToUse != null, + Dbg.Assert(rsToUse is not null, "Nested PowerShell can only work on a Runspace"); // Perform work on the current thread. Nested Pipeline @@ -4554,7 +4554,7 @@ private void CoreInvokeHelper(PSDataCollection input, P // re-throw the exception InvalidRunspacePoolStateException poolException = exception as InvalidRunspacePoolStateException; - if (poolException != null && _runspace != null) // the pool exception was actually thrown by a runspace + if (poolException is not null && _runspace is not null) // the pool exception was actually thrown by a runspace { throw poolException.ToInvalidRunspaceStateException(); } @@ -4589,7 +4589,7 @@ private void CoreInvokeRemoteHelper(PSDataCollection in EndInvokeAsyncResult = null; if ((PSInvocationState.Failed == InvocationStateInfo.State) && - (InvocationStateInfo.Reason != null)) + (InvocationStateInfo.Reason is not null)) { throw InvocationStateInfo.Reason; } @@ -4618,7 +4618,7 @@ private void CoreInvoke(PSDataCollection input, PSDataC SetHadErrors(false); RunspacePool pool = _rsConnection as RunspacePool; - if ((pool != null) && (pool.IsRemote)) + if ((pool is not null) && (pool.IsRemote)) { if (ServerSupportsBatchInvocation()) { @@ -4679,13 +4679,13 @@ private void CoreInvoke(PSDataCollection input, PSDataC SetHadErrors(true); // Stop if necessarily - if ((settings != null) && settings.ErrorActionPreference == ActionPreference.Stop) + if ((settings is not null) && settings.ErrorActionPreference == ActionPreference.Stop) { throw; } // Ignore the exception if necessary. - if ((settings != null) && settings.ErrorActionPreference == ActionPreference.Ignore) + if ((settings is not null) && settings.ErrorActionPreference == ActionPreference.Ignore) { continue; } @@ -4695,7 +4695,7 @@ private void CoreInvoke(PSDataCollection input, PSDataC IContainsErrorRecord er = e as IContainsErrorRecord; - if (er != null && er.ErrorRecord != null) + if (er is not null && er.ErrorRecord is not null) { this.Streams.Error.Add(er.ErrorRecord); } @@ -4777,9 +4777,9 @@ private IAsyncResult CoreInvokeAsync(PSDataCollection i try { // IsNested is true for the icm | % { icm } scenario - if (!IsNested || (pool != null && pool.IsRemote)) + if (!IsNested || (pool is not null && pool.IsRemote)) { - if (pool != null) + if (pool is not null) { #if !UNIX VerifyThreadSettings(settings, pool.ApartmentState, pool.ThreadOptions, pool.IsRemote); @@ -4812,7 +4812,7 @@ private IAsyncResult CoreInvokeAsync(PSDataCollection i ObjectStreamBase inputStream = null; - if (input != null) + if (input is not null) { inputStream = new PSDataCollectionStream(InstanceId, input); } @@ -4832,12 +4832,12 @@ private IAsyncResult CoreInvokeAsync(PSDataCollection i } else { - if (inputStream != null) + if (inputStream is not null) { RemotePowerShell.InputStream = inputStream; } - if (output != null) + if (output is not null) { RemotePowerShell.OutputStream = new PSDataCollectionStream(InstanceId, output); @@ -4858,7 +4858,7 @@ private IAsyncResult CoreInvokeAsync(PSDataCollection i else { LocalRunspace rs = _rsConnection as LocalRunspace; - if (rs != null) + if (rs is not null) { #if !UNIX VerifyThreadSettings(settings, rs.ApartmentState, rs.ThreadOptions, false); @@ -4901,7 +4901,7 @@ private IAsyncResult CoreInvokeAsync(PSDataCollection i // re-throw the exception InvalidRunspacePoolStateException poolException = exception as InvalidRunspacePoolStateException; - if (poolException != null && _runspace != null) // the pool exception was actually thrown by a runspace + if (poolException is not null && _runspace is not null) // the pool exception was actually thrown by a runspace { throw poolException.ToInvalidRunspaceStateException(); } @@ -4921,7 +4921,7 @@ private void VerifyThreadSettings(PSInvocationSettings settings, ApartmentState { ApartmentState apartmentState; - if (settings != null && settings.ApartmentState != ApartmentState.Unknown) + if (settings is not null && settings.ApartmentState != ApartmentState.Unknown) { apartmentState = settings.ApartmentState; } @@ -4967,7 +4967,7 @@ private void VerifyThreadSettings(PSInvocationSettings settings, ApartmentState /// private void Prepare(PSDataCollection input, PSDataCollection output, PSInvocationSettings settings, bool shouldCreateWorker) { - Dbg.Assert(output != null, "Output cannot be null"); + Dbg.Assert(output is not null, "Output cannot be null"); lock (_syncObject) { @@ -4986,7 +4986,7 @@ private void Prepare(PSDataCollection input, PSDataColl InvocationStateInfo = new PSInvocationStateInfo(PSInvocationState.Running, null); // update settings for impersonation policy - if ((settings != null) && (settings.FlowImpersonationPolicy)) + if ((settings is not null) && (settings.FlowImpersonationPolicy)) { // get the identity of the thread. // false behavior: If the thread is impersonating the WindowsIdentity for the @@ -5000,7 +5000,7 @@ private void Prepare(PSDataCollection input, PSDataColl // this way pipeline will not waste resources creating // the same. ObjectStreamBase inputStream; - if (input != null) + if (input is not null) { inputStream = new PSDataCollectionStream(InstanceId, input); } @@ -5104,7 +5104,7 @@ private IAsyncResult CoreStop(bool isSyncCall, AsyncCallback callback, object st // cannot complete with this object. if (isDisconnected) { - if (_invokeAsyncResult != null) + if (_invokeAsyncResult is not null) { // Since object is stopped, allow result wait to end. _invokeAsyncResult.SetAsCompleted(null); @@ -5126,9 +5126,9 @@ private IAsyncResult CoreStop(bool isSyncCall, AsyncCallback callback, object st bool shouldRunStopHelper = false; RunspacePool pool = _rsConnection as RunspacePool; - if (pool != null && pool.IsRemote) + if (pool is not null && pool.IsRemote) { - if ((RemotePowerShell != null) && RemotePowerShell.Initialized) + if ((RemotePowerShell is not null) && RemotePowerShell.Initialized) { RemotePowerShell.StopAsync(); @@ -5169,7 +5169,7 @@ private IAsyncResult CoreStop(bool isSyncCall, AsyncCallback callback, object st private void ReleaseDebugger() { LocalRunspace localRunspace = _runspace as LocalRunspace; - if (localRunspace != null) + if (localRunspace is not null) { localRunspace.ReleaseDebugger(); } @@ -5184,7 +5184,7 @@ private void ReleaseDebugger() private void StopHelper(object state) { Queue events = state as Queue; - Dbg.Assert(events != null, + Dbg.Assert(events is not null, "StopImplementation expects a Queue as parameter"); // Raise the events outside of the lock..this way 3rd party callback @@ -5241,7 +5241,7 @@ private void StopThreadProc(object state) private bool ServerSupportsBatchInvocation() { - if (_runspace != null) + if (_runspace is not null) { return _runspace.RunspaceStateInfo.State != RunspaceState.BeforeOpen && _runspace.GetRemoteProtocolVersion() >= RemotingConstants.ProtocolVersionWin8RTM; @@ -5257,7 +5257,7 @@ private bool ServerSupportsBatchInvocation() remoteRunspacePoolInternal = (_rsConnection as RunspacePool).RemoteRunspacePoolInternal; } - return remoteRunspacePoolInternal != null && + return remoteRunspacePoolInternal is not null && remoteRunspacePoolInternal.PSRemotingProtocolVersion >= RemotingConstants.ProtocolVersionWin8RTM; } @@ -5266,14 +5266,14 @@ private bool ServerSupportsBatchInvocation() /// private void AddToRemoteRunspaceRunningList() { - if (_runspace != null) + if (_runspace is not null) { _runspace.PushRunningPowerShell(this); } else { RemoteRunspacePoolInternal remoteRunspacePoolInternal = GetRemoteRunspacePoolInternal(); - if (remoteRunspacePoolInternal != null) + if (remoteRunspacePoolInternal is not null) { remoteRunspacePoolInternal.PushRunningPowerShell(this); } @@ -5285,14 +5285,14 @@ private void AddToRemoteRunspaceRunningList() /// private void RemoveFromRemoteRunspaceRunningList() { - if (_runspace != null) + if (_runspace is not null) { _runspace.PopRunningPowerShell(); } else { RemoteRunspacePoolInternal remoteRunspacePoolInternal = GetRemoteRunspacePoolInternal(); - if (remoteRunspacePoolInternal != null) + if (remoteRunspacePoolInternal is not null) { remoteRunspacePoolInternal.PopRunningPowerShell(); } @@ -5302,7 +5302,7 @@ private void RemoveFromRemoteRunspaceRunningList() private RemoteRunspacePoolInternal GetRemoteRunspacePoolInternal() { RunspacePool runspacePool = _rsConnection as RunspacePool; - return (runspacePool != null) ? (runspacePool.RemoteRunspacePoolInternal) : null; + return (runspacePool is not null) ? (runspacePool.RemoteRunspacePoolInternal) : null; } #endregion @@ -5389,7 +5389,7 @@ internal void CreateRunspaceIfNeededAndDoWork(Runspace rsToUse, bool isSync) { lock (_shell._syncObject) { - if (_shell._runspace != null) + if (_shell._runspace is not null) { rsToUse = _shell._runspace; } @@ -5397,7 +5397,7 @@ internal void CreateRunspaceIfNeededAndDoWork(Runspace rsToUse, bool isSync) { Runspace runspace = null; - if ((_settings != null) && (_settings.Host != null)) + if ((_settings is not null) && (_settings.Host is not null)) { runspace = RunspaceFactory.CreateRunspace(_settings.Host); } @@ -5459,7 +5459,7 @@ internal void RunspaceAvailableCallback(IAsyncResult asyncResult) try { RunspacePool pool = _shell._rsConnection as RunspacePool; - Dbg.Assert(pool != null, "RunspaceConnection must be a runspace pool"); + Dbg.Assert(pool is not null, "RunspaceConnection must be a runspace pool"); // get the runspace..this will throw if there is an exception // occurred while getting the runspace. @@ -5513,7 +5513,7 @@ internal void RunspaceAvailableCallback(IAsyncResult asyncResult) /// internal bool ConstructPipelineAndDoWork(Runspace rs, bool performSyncInvoke) { - Dbg.Assert(rs != null, "Runspace cannot be null in ConstructPipelineAndDoWork"); + Dbg.Assert(rs is not null, "Runspace cannot be null in ConstructPipelineAndDoWork"); _shell.RunspaceAssigned.SafeInvoke(this, new PSEventArgs(rs)); // lock is needed until a pipeline is created to @@ -5527,12 +5527,12 @@ internal bool ConstructPipelineAndDoWork(Runspace rs, bool performSyncInvoke) return false; } - if (lrs != null) + if (lrs is not null) { LocalPipeline localPipeline = new LocalPipeline( lrs, _shell.Commands.Commands, - ((_settings != null) && (_settings.AddToHistory)) ? true : false, + ((_settings is not null) && (_settings.AddToHistory)) ? true : false, _shell.IsNested, _inputStream, _outputStream, @@ -5563,7 +5563,7 @@ internal bool ConstructPipelineAndDoWork(Runspace rs, bool performSyncInvoke) // Set pipeline specific settings CurrentlyRunningPipeline.InvocationSettings = _settings; - Dbg.Assert(lrs != null, "LocalRunspace cannot be null here"); + Dbg.Assert(lrs is not null, "LocalRunspace cannot be null here"); if (performSyncInvoke) { @@ -5591,7 +5591,7 @@ internal void Stop(bool isSyncCall) } _isNotActive = true; - if (CurrentlyRunningPipeline != null) + if (CurrentlyRunningPipeline is not null) { if (isSyncCall) { @@ -5605,10 +5605,10 @@ internal void Stop(bool isSyncCall) return; } - if (GetRunspaceAsyncResult != null) + if (GetRunspaceAsyncResult is not null) { RunspacePool pool = _shell._rsConnection as RunspacePool; - Dbg.Assert(pool != null, "RunspaceConnection must be a runspace pool"); + Dbg.Assert(pool is not null, "RunspaceConnection must be a runspace pool"); pool.CancelGetRunspace(GetRunspaceAsyncResult); } } @@ -5636,7 +5636,7 @@ internal void InternalClearSuppressExceptions() { try { - if ((_settings != null) && (_settings.WindowsIdentityToImpersonate != null)) + if ((_settings is not null) && (_settings.WindowsIdentityToImpersonate is not null)) { _settings.WindowsIdentityToImpersonate.Dispose(); _settings.WindowsIdentityToImpersonate = null; @@ -5664,7 +5664,7 @@ internal void InternalClearSuppressExceptions() else { RunspacePool pool = _shell._rsConnection as RunspacePool; - if (pool != null) + if (pool is not null) { pool.ReleaseRunspace(CurrentlyRunningPipeline.Runspace); } @@ -5838,7 +5838,7 @@ internal void SuspendIncomingData() throw new PSNotSupportedException(); } - if (RemotePowerShell.DataStructureHandler != null) + if (RemotePowerShell.DataStructureHandler is not null) { RemotePowerShell.DataStructureHandler.TransportManager.SuspendQueue(true); } @@ -5854,7 +5854,7 @@ internal void ResumeIncomingData() throw new PSNotSupportedException(); } - if (RemotePowerShell.DataStructureHandler != null) + if (RemotePowerShell.DataStructureHandler is not null) { RemotePowerShell.DataStructureHandler.TransportManager.ResumeQueue(); } @@ -5872,7 +5872,7 @@ internal void WaitForServicingComplete() throw new PSNotSupportedException(); } - if (RemotePowerShell.DataStructureHandler != null) + if (RemotePowerShell.DataStructureHandler is not null) { int count = 0; while (++count < 2 && @@ -5903,7 +5903,7 @@ internal CimInstance AsPSPowerShellPipeline() bool addToHistoryValue = false, noInputValue = false; uint apartmentStateValue = 0; - if (_worker != null) + if (_worker is not null) { _worker.GetSettings(out addToHistoryValue, out noInputValue, out apartmentStateValue); } @@ -6163,10 +6163,10 @@ internal PowerShellStopper(ExecutionContext context, PowerShell powerShell) _powerShell = powerShell; - if ((context.CurrentCommandProcessor != null) && - (context.CurrentCommandProcessor.CommandRuntime != null) && - (context.CurrentCommandProcessor.CommandRuntime.PipelineProcessor != null) && - (context.CurrentCommandProcessor.CommandRuntime.PipelineProcessor.LocalPipeline != null)) + if ((context.CurrentCommandProcessor is not null) && + (context.CurrentCommandProcessor.CommandRuntime is not null) && + (context.CurrentCommandProcessor.CommandRuntime.PipelineProcessor is not null) && + (context.CurrentCommandProcessor.CommandRuntime.PipelineProcessor.LocalPipeline is not null)) { _eventHandler = new EventHandler(LocalPipeline_StateChanged); _pipeline = context.CurrentCommandProcessor.CommandRuntime.PipelineProcessor.LocalPipeline; @@ -6189,7 +6189,7 @@ public void Dispose() { if (!_isDisposed) { - if (_eventHandler != null) + if (_eventHandler is not null) { _pipeline.StateChanged -= _eventHandler; _eventHandler = null; diff --git a/src/System.Management.Automation/engine/hostifaces/PowerShellProcessInstance.cs b/src/System.Management.Automation/engine/hostifaces/PowerShellProcessInstance.cs index d245d56f9d9..c37b2ee9ef8 100644 --- a/src/System.Management.Automation/engine/hostifaces/PowerShellProcessInstance.cs +++ b/src/System.Management.Automation/engine/hostifaces/PowerShellProcessInstance.cs @@ -57,7 +57,7 @@ public PowerShellProcessInstance(Version powerShellVersion, PSCredential credent bool startingWindowsPowerShell51 = false; #if !UNIX // if requested PS version was "5.1" then we start Windows PS instead of PS Core - startingWindowsPowerShell51 = (powerShellVersion != null) && (powerShellVersion.Major == 5) && (powerShellVersion.Minor == 1); + startingWindowsPowerShell51 = (powerShellVersion is not null) && (powerShellVersion.Major == 5) && (powerShellVersion.Minor == 1); if (startingWindowsPowerShell51) { if (WinPwshExePath is null) @@ -119,7 +119,7 @@ public PowerShellProcessInstance(Version powerShellVersion, PSCredential credent _startInfo.ArgumentList.Add(workingDirectory); } - if (initializationScript != null) + if (initializationScript is not null) { var scriptBlockString = initializationScript.ToString(); if (!string.IsNullOrEmpty(scriptBlockString)) @@ -130,7 +130,7 @@ public PowerShellProcessInstance(Version powerShellVersion, PSCredential credent } } - if (credential != null) + if (credential is not null) { Net.NetworkCredential netCredential = credential.GetNetworkCredential(); @@ -171,7 +171,7 @@ public bool HasExited // When process is exited, there is some delay in receiving ProcessExited event and HasExited property on process object. // Using HasExited property on started process object to determine if powershell process has exited. // - return _processExited || (_started && Process != null && Process.HasExited); + return _processExited || (_started && Process is not null && Process.HasExited); } } @@ -201,7 +201,7 @@ private void Dispose(bool disposing) { try { - if (Process != null && !Process.HasExited) + if (Process is not null && !Process.HasExited) Process.Kill(); } catch (InvalidOperationException) diff --git a/src/System.Management.Automation/engine/hostifaces/RunspaceInit.cs b/src/System.Management.Automation/engine/hostifaces/RunspaceInit.cs index 04dc65baac2..ae00f5abf50 100644 --- a/src/System.Management.Automation/engine/hostifaces/RunspaceInit.cs +++ b/src/System.Management.Automation/engine/hostifaces/RunspaceInit.cs @@ -20,7 +20,7 @@ class LocalRunspace : RunspaceBase private void InitializeDefaults() { SessionStateInternal ss = _engine.Context.EngineSessionState; - Dbg.Assert(ss != null, "SessionState should not be null"); + Dbg.Assert(ss is not null, "SessionState should not be null"); // Add the variables that must always be there... ss.InitializeFixedVariables(); diff --git a/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs b/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs index 245c3c9741d..d94cbac03d9 100644 --- a/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs +++ b/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs @@ -776,7 +776,7 @@ private void OnStateChanged(object source, RunspacePoolStateChangedEventArgs arg if (ConnectionInfo is NewProcessConnectionInfo) { NewProcessConnectionInfo connectionInfo = ConnectionInfo as NewProcessConnectionInfo; - if (connectionInfo.Process != null && + if (connectionInfo.Process is not null && (args.RunspacePoolStateInfo.State == RunspacePoolState.Opened || args.RunspacePoolStateInfo.State == RunspacePoolState.Broken)) { @@ -839,7 +839,7 @@ private void OnEventForwarded(PSEventArgs e) { EventHandler eh = InternalForwardEvent; - if (eh != null) + if (eh is not null) { eh(this, e); } diff --git a/src/System.Management.Automation/engine/hostifaces/RunspacePoolInternal.cs b/src/System.Management.Automation/engine/hostifaces/RunspacePoolInternal.cs index ebb1c133b69..81684784fb2 100644 --- a/src/System.Management.Automation/engine/hostifaces/RunspacePoolInternal.cs +++ b/src/System.Management.Automation/engine/hostifaces/RunspacePoolInternal.cs @@ -725,7 +725,7 @@ public Runspace GetRunspace() // throw the exception that occurred while // processing the async operation - if (asyncResult.Exception != null) + if (asyncResult.Exception is not null) { throw asyncResult.Exception; } @@ -1246,7 +1246,7 @@ internal void AssertPoolIsOpen() /// protected Runspace CreateRunspace() { - Dbg.Assert(_initialSessionState != null, "_initialSessionState should not be null"); + Dbg.Assert(_initialSessionState is not null, "_initialSessionState should not be null"); // TODO: exceptions thrown here need to be documented // runspace.Open() did not document all the exceptions. Runspace result = RunspaceFactory.CreateRunspaceFromSessionStateNoClone(host, _initialSessionState); @@ -1289,7 +1289,7 @@ protected Runspace CreateRunspace() /// protected void DestroyRunspace(Runspace runspace) { - Dbg.Assert(runspace != null, "Runspace cannot be null"); + Dbg.Assert(runspace is not null, "Runspace cannot be null"); runspace.Events.ForwardEvent -= OnRunspaceForwardEvent; // this must be done after open since open initializes the ExecutionContext runspace.Close(); runspace.Dispose(); @@ -1440,7 +1440,7 @@ protected void EnqueueCheckAndStartRequestServicingThread(GetRunspaceAsyncResult bool shouldStartServicingInSameThread = false; lock (runspaceRequestQueue) { - if (requestToEnqueue != null) + if (requestToEnqueue is not null) { runspaceRequestQueue.Enqueue(requestToEnqueue); } @@ -1604,7 +1604,7 @@ protected void ServicePendingRequests(object useCallingThreadState) } } - if ((useCallingThread) && (runspaceRequester != null)) + if ((useCallingThread) && (runspaceRequester is not null)) { // call DoComplete outside of the lock and finally..as the // DoComplete handler may handle the runspace in the same @@ -1642,7 +1642,7 @@ protected virtual void OnForwardEvent(PSEventArgs e) { EventHandler eh = this.ForwardEvent; - if (eh != null) + if (eh is not null) { eh(this, e); } diff --git a/src/System.Management.Automation/engine/hostifaces/pipelinebase.cs b/src/System.Management.Automation/engine/hostifaces/pipelinebase.cs index c54f5ca235e..020f904b94d 100644 --- a/src/System.Management.Automation/engine/hostifaces/pipelinebase.cs +++ b/src/System.Management.Automation/engine/hostifaces/pipelinebase.cs @@ -87,11 +87,11 @@ protected PipelineBase(Runspace runspace, PSInformationalBuffers infoBuffers) : base(runspace, command) { - Dbg.Assert(inputStream != null, "Caller Should validate inputstream parameter"); - Dbg.Assert(outputStream != null, "Caller Should validate outputStream parameter"); - Dbg.Assert(errorStream != null, "Caller Should validate errorStream parameter"); - Dbg.Assert(infoBuffers != null, "Caller Should validate informationalBuffers parameter"); - Dbg.Assert(command != null, "Command cannot be null"); + Dbg.Assert(inputStream is not null, "Caller Should validate inputstream parameter"); + Dbg.Assert(outputStream is not null, "Caller Should validate outputStream parameter"); + Dbg.Assert(errorStream is not null, "Caller Should validate errorStream parameter"); + Dbg.Assert(infoBuffers is not null, "Caller Should validate informationalBuffers parameter"); + Dbg.Assert(command is not null, "Command cannot be null"); // Since we are constructing this pipeline using a commandcollection we dont need // to add cmd to CommandCollection again (Initialize does this).. because of this @@ -399,7 +399,7 @@ public override Collection Invoke(IEnumerable input) { return new Collection(); } - else if (PipelineStateInfo.State == PipelineState.Failed && PipelineStateInfo.Reason != null) + else if (PipelineStateInfo.State == PipelineState.Failed && PipelineStateInfo.Reason is not null) { // If this is an error pipe for a hosting applicationand we are logging, // then log the error. @@ -494,7 +494,7 @@ private void CoreInvoke(IEnumerable input, bool syncCall) if (syncCall && !(InputStream is PSDataCollectionStream || InputStream is PSDataCollectionStream)) { // Method is called from synchronous invoke. - if (input != null) + if (input is not null) { // TO-DO-Add a test make sure that ObjectDisposed // exception is thrown @@ -627,7 +627,7 @@ internal void DoConcurrentCheck(bool syncCall, object syncObject, bool isInLock) // Detect if we're running a pulse pipeline, or we're running a nested pipeline // in a pulse pipeline if (currentPipeline == RunspaceBase.PulsePipeline || - (currentPipeline.IsNested && RunspaceBase.PulsePipeline != null)) + (currentPipeline.IsNested && RunspaceBase.PulsePipeline is not null)) { // If so, wait and try again if (isInLock) @@ -685,7 +685,7 @@ internal void DoConcurrentCheck(bool syncCall, object syncObject, bool isInLock) RunspaceStrings.NestedPipelineNoParentPipeline); } - Dbg.Assert(currentPipeline.NestedPipelineExecutionThread != null, "Current pipeline should always have NestedPipelineExecutionThread set"); + Dbg.Assert(currentPipeline.NestedPipelineExecutionThread is not null, "Current pipeline should always have NestedPipelineExecutionThread set"); Thread th = Thread.CurrentThread; if (currentPipeline.NestedPipelineExecutionThread.Equals(th) == false) @@ -843,7 +843,7 @@ protected void RaisePipelineStateEvents() stateChanged = this.StateChanged; runspaceHasAvailabilityChangedSubscribers = _runspace.HasAvailabilityChangedSubscribers; - if (stateChanged != null || runspaceHasAvailabilityChangedSubscribers) + if (stateChanged is not null || runspaceHasAvailabilityChangedSubscribers) { tempEventQueue = _executionEventQueue; _executionEventQueue = new Queue(); @@ -857,7 +857,7 @@ protected void RaisePipelineStateEvents() } } - if (tempEventQueue != null) + if (tempEventQueue is not null) { while (tempEventQueue.Count > 0) { @@ -872,7 +872,7 @@ protected void RaisePipelineStateEvents() #pragma warning disable 56500 // Exception raised in the eventhandler are not error in pipeline. // silently ignore them. - if (stateChanged != null) + if (stateChanged is not null) { try { @@ -919,7 +919,7 @@ protected ObjectStreamBase ErrorStream private set { - Dbg.Assert(value != null, "ErrorStream cannot be null"); + Dbg.Assert(value is not null, "ErrorStream cannot be null"); _errorStream = value; _errorStream.DataReady += OnErrorStreamDataReady; } @@ -990,7 +990,7 @@ private void OnErrorStreamDataReady(object sender, EventArgs e) /// private void Initialize(Runspace runspace, string command, bool addToHistory, bool isNested) { - Dbg.Assert(runspace != null, "caller should validate the parameter"); + Dbg.Assert(runspace is not null, "caller should validate the parameter"); _runspace = runspace; _isNested = isNested; @@ -1000,7 +1000,7 @@ private void Initialize(Runspace runspace, string command, bool addToHistory, bo throw PSTraceSource.NewArgumentNullException(nameof(command)); } - if (command != null) + if (command is not null) { Commands.Add(new Command(command, true, false)); } diff --git a/src/System.Management.Automation/engine/interpreter/BranchLabel.cs b/src/System.Management.Automation/engine/interpreter/BranchLabel.cs index 65aa79c7a28..b8c76ca2dfa 100644 --- a/src/System.Management.Automation/engine/interpreter/BranchLabel.cs +++ b/src/System.Management.Automation/engine/interpreter/BranchLabel.cs @@ -92,7 +92,7 @@ internal void Mark(InstructionList instructions) _continuationStackDepth = instructions.CurrentContinuationsDepth; _targetIndex = instructions.Count; - if (_forwardBranchFixups != null) + if (_forwardBranchFixups is not null) { foreach (var branchIndex in _forwardBranchFixups) { diff --git a/src/System.Management.Automation/engine/interpreter/CallInstruction.Generated.cs b/src/System.Management.Automation/engine/interpreter/CallInstruction.Generated.cs index 5645f6673b1..b0cdf597358 100644 --- a/src/System.Management.Automation/engine/interpreter/CallInstruction.Generated.cs +++ b/src/System.Management.Automation/engine/interpreter/CallInstruction.Generated.cs @@ -470,7 +470,7 @@ public ActionCallInstruction(MethodInfo target) { } public override object Invoke(object arg0) { - _target(arg0 != null ? (T0)arg0 : default(T0)); + _target(arg0 is not null ? (T0)arg0 : default(T0)); return null; } @@ -496,7 +496,7 @@ public ActionCallInstruction(MethodInfo target) { } public override object Invoke(object arg0, object arg1) { - _target(arg0 != null ? (T0)arg0 : default(T0), arg1 != null ? (T1)arg1 : default(T1)); + _target(arg0 is not null ? (T0)arg0 : default(T0), arg1 is not null ? (T1)arg1 : default(T1)); return null; } @@ -522,7 +522,7 @@ public ActionCallInstruction(MethodInfo target) { } public override object Invoke(object arg0, object arg1, object arg2) { - _target(arg0 != null ? (T0)arg0 : default(T0), arg1 != null ? (T1)arg1 : default(T1), arg2 != null ? (T2)arg2 : default(T2)); + _target(arg0 is not null ? (T0)arg0 : default(T0), arg1 is not null ? (T1)arg1 : default(T1), arg2 is not null ? (T2)arg2 : default(T2)); return null; } @@ -548,7 +548,7 @@ public ActionCallInstruction(MethodInfo target) { } public override object Invoke(object arg0, object arg1, object arg2, object arg3) { - _target(arg0 != null ? (T0)arg0 : default(T0), arg1 != null ? (T1)arg1 : default(T1), arg2 != null ? (T2)arg2 : default(T2), arg3 != null ? (T3)arg3 : default(T3)); + _target(arg0 is not null ? (T0)arg0 : default(T0), arg1 is not null ? (T1)arg1 : default(T1), arg2 is not null ? (T2)arg2 : default(T2), arg3 is not null ? (T3)arg3 : default(T3)); return null; } @@ -574,7 +574,7 @@ public ActionCallInstruction(MethodInfo target) { } public override object Invoke(object arg0, object arg1, object arg2, object arg3, object arg4) { - _target(arg0 != null ? (T0)arg0 : default(T0), arg1 != null ? (T1)arg1 : default(T1), arg2 != null ? (T2)arg2 : default(T2), arg3 != null ? (T3)arg3 : default(T3), arg4 != null ? (T4)arg4 : default(T4)); + _target(arg0 is not null ? (T0)arg0 : default(T0), arg1 is not null ? (T1)arg1 : default(T1), arg2 is not null ? (T2)arg2 : default(T2), arg3 is not null ? (T3)arg3 : default(T3), arg4 is not null ? (T4)arg4 : default(T4)); return null; } @@ -600,7 +600,7 @@ public ActionCallInstruction(MethodInfo target) { } public override object Invoke(object arg0, object arg1, object arg2, object arg3, object arg4, object arg5) { - _target(arg0 != null ? (T0)arg0 : default(T0), arg1 != null ? (T1)arg1 : default(T1), arg2 != null ? (T2)arg2 : default(T2), arg3 != null ? (T3)arg3 : default(T3), arg4 != null ? (T4)arg4 : default(T4), arg5 != null ? (T5)arg5 : default(T5)); + _target(arg0 is not null ? (T0)arg0 : default(T0), arg1 is not null ? (T1)arg1 : default(T1), arg2 is not null ? (T2)arg2 : default(T2), arg3 is not null ? (T3)arg3 : default(T3), arg4 is not null ? (T4)arg4 : default(T4), arg5 is not null ? (T5)arg5 : default(T5)); return null; } @@ -626,7 +626,7 @@ public ActionCallInstruction(MethodInfo target) { } public override object Invoke(object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6) { - _target(arg0 != null ? (T0)arg0 : default(T0), arg1 != null ? (T1)arg1 : default(T1), arg2 != null ? (T2)arg2 : default(T2), arg3 != null ? (T3)arg3 : default(T3), arg4 != null ? (T4)arg4 : default(T4), arg5 != null ? (T5)arg5 : default(T5), arg6 != null ? (T6)arg6 : default(T6)); + _target(arg0 is not null ? (T0)arg0 : default(T0), arg1 is not null ? (T1)arg1 : default(T1), arg2 is not null ? (T2)arg2 : default(T2), arg3 is not null ? (T3)arg3 : default(T3), arg4 is not null ? (T4)arg4 : default(T4), arg5 is not null ? (T5)arg5 : default(T5), arg6 is not null ? (T6)arg6 : default(T6)); return null; } @@ -652,7 +652,7 @@ public ActionCallInstruction(MethodInfo target) { } public override object Invoke(object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7) { - _target(arg0 != null ? (T0)arg0 : default(T0), arg1 != null ? (T1)arg1 : default(T1), arg2 != null ? (T2)arg2 : default(T2), arg3 != null ? (T3)arg3 : default(T3), arg4 != null ? (T4)arg4 : default(T4), arg5 != null ? (T5)arg5 : default(T5), arg6 != null ? (T6)arg6 : default(T6), arg7 != null ? (T7)arg7 : default(T7)); + _target(arg0 is not null ? (T0)arg0 : default(T0), arg1 is not null ? (T1)arg1 : default(T1), arg2 is not null ? (T2)arg2 : default(T2), arg3 is not null ? (T3)arg3 : default(T3), arg4 is not null ? (T4)arg4 : default(T4), arg5 is not null ? (T5)arg5 : default(T5), arg6 is not null ? (T6)arg6 : default(T6), arg7 is not null ? (T7)arg7 : default(T7)); return null; } @@ -678,7 +678,7 @@ public ActionCallInstruction(MethodInfo target) { } public override object Invoke(object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8) { - _target(arg0 != null ? (T0)arg0 : default(T0), arg1 != null ? (T1)arg1 : default(T1), arg2 != null ? (T2)arg2 : default(T2), arg3 != null ? (T3)arg3 : default(T3), arg4 != null ? (T4)arg4 : default(T4), arg5 != null ? (T5)arg5 : default(T5), arg6 != null ? (T6)arg6 : default(T6), arg7 != null ? (T7)arg7 : default(T7), arg8 != null ? (T8)arg8 : default(T8)); + _target(arg0 is not null ? (T0)arg0 : default(T0), arg1 is not null ? (T1)arg1 : default(T1), arg2 is not null ? (T2)arg2 : default(T2), arg3 is not null ? (T3)arg3 : default(T3), arg4 is not null ? (T4)arg4 : default(T4), arg5 is not null ? (T5)arg5 : default(T5), arg6 is not null ? (T6)arg6 : default(T6), arg7 is not null ? (T7)arg7 : default(T7), arg8 is not null ? (T8)arg8 : default(T8)); return null; } @@ -729,7 +729,7 @@ public FuncCallInstruction(MethodInfo target) { } public override object Invoke(object arg0) { - return _target(arg0 != null ? (T0)arg0 : default(T0)); + return _target(arg0 is not null ? (T0)arg0 : default(T0)); } public override int Run(InterpretedFrame frame) { @@ -754,7 +754,7 @@ public FuncCallInstruction(MethodInfo target) { } public override object Invoke(object arg0, object arg1) { - return _target(arg0 != null ? (T0)arg0 : default(T0), arg1 != null ? (T1)arg1 : default(T1)); + return _target(arg0 is not null ? (T0)arg0 : default(T0), arg1 is not null ? (T1)arg1 : default(T1)); } public override int Run(InterpretedFrame frame) { @@ -779,7 +779,7 @@ public FuncCallInstruction(MethodInfo target) { } public override object Invoke(object arg0, object arg1, object arg2) { - return _target(arg0 != null ? (T0)arg0 : default(T0), arg1 != null ? (T1)arg1 : default(T1), arg2 != null ? (T2)arg2 : default(T2)); + return _target(arg0 is not null ? (T0)arg0 : default(T0), arg1 is not null ? (T1)arg1 : default(T1), arg2 is not null ? (T2)arg2 : default(T2)); } public override int Run(InterpretedFrame frame) { @@ -804,7 +804,7 @@ public FuncCallInstruction(MethodInfo target) { } public override object Invoke(object arg0, object arg1, object arg2, object arg3) { - return _target(arg0 != null ? (T0)arg0 : default(T0), arg1 != null ? (T1)arg1 : default(T1), arg2 != null ? (T2)arg2 : default(T2), arg3 != null ? (T3)arg3 : default(T3)); + return _target(arg0 is not null ? (T0)arg0 : default(T0), arg1 is not null ? (T1)arg1 : default(T1), arg2 is not null ? (T2)arg2 : default(T2), arg3 is not null ? (T3)arg3 : default(T3)); } public override int Run(InterpretedFrame frame) { @@ -829,7 +829,7 @@ public FuncCallInstruction(MethodInfo target) { } public override object Invoke(object arg0, object arg1, object arg2, object arg3, object arg4) { - return _target(arg0 != null ? (T0)arg0 : default(T0), arg1 != null ? (T1)arg1 : default(T1), arg2 != null ? (T2)arg2 : default(T2), arg3 != null ? (T3)arg3 : default(T3), arg4 != null ? (T4)arg4 : default(T4)); + return _target(arg0 is not null ? (T0)arg0 : default(T0), arg1 is not null ? (T1)arg1 : default(T1), arg2 is not null ? (T2)arg2 : default(T2), arg3 is not null ? (T3)arg3 : default(T3), arg4 is not null ? (T4)arg4 : default(T4)); } public override int Run(InterpretedFrame frame) { @@ -854,7 +854,7 @@ public FuncCallInstruction(MethodInfo target) { } public override object Invoke(object arg0, object arg1, object arg2, object arg3, object arg4, object arg5) { - return _target(arg0 != null ? (T0)arg0 : default(T0), arg1 != null ? (T1)arg1 : default(T1), arg2 != null ? (T2)arg2 : default(T2), arg3 != null ? (T3)arg3 : default(T3), arg4 != null ? (T4)arg4 : default(T4), arg5 != null ? (T5)arg5 : default(T5)); + return _target(arg0 is not null ? (T0)arg0 : default(T0), arg1 is not null ? (T1)arg1 : default(T1), arg2 is not null ? (T2)arg2 : default(T2), arg3 is not null ? (T3)arg3 : default(T3), arg4 is not null ? (T4)arg4 : default(T4), arg5 is not null ? (T5)arg5 : default(T5)); } public override int Run(InterpretedFrame frame) { @@ -879,7 +879,7 @@ public FuncCallInstruction(MethodInfo target) { } public override object Invoke(object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6) { - return _target(arg0 != null ? (T0)arg0 : default(T0), arg1 != null ? (T1)arg1 : default(T1), arg2 != null ? (T2)arg2 : default(T2), arg3 != null ? (T3)arg3 : default(T3), arg4 != null ? (T4)arg4 : default(T4), arg5 != null ? (T5)arg5 : default(T5), arg6 != null ? (T6)arg6 : default(T6)); + return _target(arg0 is not null ? (T0)arg0 : default(T0), arg1 is not null ? (T1)arg1 : default(T1), arg2 is not null ? (T2)arg2 : default(T2), arg3 is not null ? (T3)arg3 : default(T3), arg4 is not null ? (T4)arg4 : default(T4), arg5 is not null ? (T5)arg5 : default(T5), arg6 is not null ? (T6)arg6 : default(T6)); } public override int Run(InterpretedFrame frame) { @@ -904,7 +904,7 @@ public FuncCallInstruction(MethodInfo target) { } public override object Invoke(object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7) { - return _target(arg0 != null ? (T0)arg0 : default(T0), arg1 != null ? (T1)arg1 : default(T1), arg2 != null ? (T2)arg2 : default(T2), arg3 != null ? (T3)arg3 : default(T3), arg4 != null ? (T4)arg4 : default(T4), arg5 != null ? (T5)arg5 : default(T5), arg6 != null ? (T6)arg6 : default(T6), arg7 != null ? (T7)arg7 : default(T7)); + return _target(arg0 is not null ? (T0)arg0 : default(T0), arg1 is not null ? (T1)arg1 : default(T1), arg2 is not null ? (T2)arg2 : default(T2), arg3 is not null ? (T3)arg3 : default(T3), arg4 is not null ? (T4)arg4 : default(T4), arg5 is not null ? (T5)arg5 : default(T5), arg6 is not null ? (T6)arg6 : default(T6), arg7 is not null ? (T7)arg7 : default(T7)); } public override int Run(InterpretedFrame frame) { @@ -929,7 +929,7 @@ public FuncCallInstruction(MethodInfo target) { } public override object Invoke(object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8) { - return _target(arg0 != null ? (T0)arg0 : default(T0), arg1 != null ? (T1)arg1 : default(T1), arg2 != null ? (T2)arg2 : default(T2), arg3 != null ? (T3)arg3 : default(T3), arg4 != null ? (T4)arg4 : default(T4), arg5 != null ? (T5)arg5 : default(T5), arg6 != null ? (T6)arg6 : default(T6), arg7 != null ? (T7)arg7 : default(T7), arg8 != null ? (T8)arg8 : default(T8)); + return _target(arg0 is not null ? (T0)arg0 : default(T0), arg1 is not null ? (T1)arg1 : default(T1), arg2 is not null ? (T2)arg2 : default(T2), arg3 is not null ? (T3)arg3 : default(T3), arg4 is not null ? (T4)arg4 : default(T4), arg5 is not null ? (T5)arg5 : default(T5), arg6 is not null ? (T6)arg6 : default(T6), arg7 is not null ? (T7)arg7 : default(T7), arg8 is not null ? (T8)arg8 : default(T8)); } public override int Run(InterpretedFrame frame) { diff --git a/src/System.Management.Automation/engine/interpreter/CallInstruction.cs b/src/System.Management.Automation/engine/interpreter/CallInstruction.cs index d351a08bfd4..2e9298e5719 100644 --- a/src/System.Management.Automation/engine/interpreter/CallInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/CallInstruction.cs @@ -52,7 +52,7 @@ public static CallInstruction Create(MethodInfo info, ParameterInfo[] parameters // A workaround for CLR bug #796414 (Unable to create delegates for Array.Get/Set): // T[]::Address - not supported by ETs due to T& return value - if (info.DeclaringType != null && info.DeclaringType.IsArray && (info.Name == "Get" || info.Name == "Set")) + if (info.DeclaringType is not null && info.DeclaringType.IsArray && (info.Name == "Get" || info.Name == "Set")) { return GetArrayAccessor(info, argumentCount); } diff --git a/src/System.Management.Automation/engine/interpreter/ControlFlowInstructions.cs b/src/System.Management.Automation/engine/interpreter/ControlFlowInstructions.cs index a590e6b06df..d9d1c726c00 100644 --- a/src/System.Management.Automation/engine/interpreter/ControlFlowInstructions.cs +++ b/src/System.Management.Automation/engine/interpreter/ControlFlowInstructions.cs @@ -44,7 +44,7 @@ public Instruction Fixup(int offset) _offset = offset; var cache = Cache; - if (cache != null && offset >= 0 && offset < cache.Length) + if (cache is not null && offset >= 0 && offset < cache.Length) { return cache[offset] ?? (cache[offset] = this); } @@ -140,7 +140,7 @@ public override int Run(InterpretedFrame frame) { Debug.Assert(_offset != Unknown); - if (frame.Peek() != null) + if (frame.Peek() is not null) { return _offset; } @@ -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 is null && tryHandler is not null, "the tryHandler can be set only once"); _tryHandler = tryHandler; } @@ -336,7 +336,7 @@ internal static EnterTryCatchFinallyInstruction CreateTryCatch() public override int Run(InterpretedFrame frame) { - Debug.Assert(_tryHandler != null, "the tryHandler must be set already"); + Debug.Assert(_tryHandler is not null, "the tryHandler must be set already"); if (_hasFinally) { diff --git a/src/System.Management.Automation/engine/interpreter/InstructionList.cs b/src/System.Management.Automation/engine/interpreter/InstructionList.cs index dd718d7bac0..7d303ce98cd 100644 --- a/src/System.Management.Automation/engine/interpreter/InstructionList.cs +++ b/src/System.Management.Automation/engine/interpreter/InstructionList.cs @@ -312,7 +312,7 @@ public InstructionArray ToArray() _maxStackDepth, _maxContinuationDepth, _instructions.ToArray(), - (_objects != null) ? _objects.ToArray() : null, + (_objects is not null) ? _objects.ToArray() : null, BuildRuntimeLabels(), _debugCookies ); @@ -421,10 +421,10 @@ internal void SwitchToBoxed(int index, int instructionIndex) { var instruction = _instructions[instructionIndex] as IBoxableInstruction; - if (instruction != null) + if (instruction is not null) { var newInstruction = instruction.BoxIfIndexMatches(index); - if (newInstruction != null) + if (newInstruction is not null) { _instructions[instructionIndex] = newInstruction; } @@ -624,7 +624,7 @@ public void EmitStoreLocalToClosure(int index) public void EmitInitializeLocal(int index, Type type) { object value = ScriptingRuntimeHelpers.GetPrimitiveDefaultValue(type); - if (value != null) + if (value is not null) { Emit(new InitializeLocalInstruction.ImmutableValue(index, value)); } diff --git a/src/System.Management.Automation/engine/interpreter/InterpretedFrame.cs b/src/System.Management.Automation/engine/interpreter/InterpretedFrame.cs index a66a0b2293f..51293819c96 100644 --- a/src/System.Management.Automation/engine/interpreter/InterpretedFrame.cs +++ b/src/System.Management.Automation/engine/interpreter/InterpretedFrame.cs @@ -175,7 +175,7 @@ public IEnumerable GetStackTraceDebugInfo() { yield return new InterpretedFrameInfo(frame.Name, frame.GetDebugInfo(frame.InstructionIndex)); frame = frame.Parent; - } while (frame != null); + } while (frame is not null); } internal void SaveTraceToException(Exception exception) @@ -202,7 +202,7 @@ internal string[] Trace { trace.Add(frame.Name); frame = frame.Parent; - } while (frame != null); + } while (frame is not null); return trace.ToArray(); } } diff --git a/src/System.Management.Automation/engine/interpreter/LabelInfo.cs b/src/System.Management.Automation/engine/interpreter/LabelInfo.cs index 375ca16d326..8e9041be156 100644 --- a/src/System.Management.Automation/engine/interpreter/LabelInfo.cs +++ b/src/System.Management.Automation/engine/interpreter/LabelInfo.cs @@ -76,7 +76,7 @@ internal void Define(LabelScopeInfo block) // Prevent the label from being shadowed, which enforces cleaner // trees. Also we depend on this for simplicity (keeping only one // active IL Label per LabelInfo) - for (LabelScopeInfo j = block; j != null; j = j.Parent) + for (LabelScopeInfo j = block; j is not null; j = j.Parent) { if (j.ContainsTarget(_node)) { @@ -114,7 +114,7 @@ internal void Define(LabelScopeInfo block) private void ValidateJump(LabelScopeInfo reference) { // look for a simple jump out - for (LabelScopeInfo j = reference; j != null; j = j.Parent) + for (LabelScopeInfo j = reference; j is not null; j = j.Parent) { if (DefinedIn(j)) { @@ -190,7 +190,7 @@ private bool DefinedIn(LabelScopeInfo scope) } HashSet definitions = _definitions as HashSet; - if (definitions != null) + if (definitions is not null) { return definitions.Contains(scope); } @@ -202,14 +202,14 @@ private bool HasDefinitions { get { - return _definitions != null; + return _definitions is not null; } } private LabelScopeInfo FirstDefinition() { LabelScopeInfo scope = _definitions as LabelScopeInfo; - if (scope != null) + if (scope is not null) { return scope; } @@ -252,12 +252,12 @@ internal static T CommonNode(T first, T second, Func parent) where T : } var set = new HashSet(cmp); - for (T t = first; t != null; t = parent(t)) + for (T t = first; t is not null; t = parent(t)) { set.Add(t); } - for (T t = second; t != null; t = parent(t)) + for (T t = second; t is not null; t = parent(t)) { if (set.Contains(t)) { diff --git a/src/System.Management.Automation/engine/interpreter/LightCompiler.cs b/src/System.Management.Automation/engine/interpreter/LightCompiler.cs index bf2ac7542b6..146e0bc52a9 100644 --- a/src/System.Management.Automation/engine/interpreter/LightCompiler.cs +++ b/src/System.Management.Automation/engine/interpreter/LightCompiler.cs @@ -86,7 +86,7 @@ internal bool IsInsideCatchBlock(int index) internal bool IsInsideFinallyBlock(int index) { - Debug.Assert(Parent != null); + Debug.Assert(Parent is not null); return Parent.IsFinallyBlockExist && index >= Parent.FinallyStartIndex && index < Parent.FinallyEndIndex; } @@ -117,7 +117,7 @@ internal bool IsFinallyBlockExist internal bool IsCatchBlockExist { - get { return (_handlers != null); } + get { return (_handlers is not null); } } /// @@ -126,7 +126,7 @@ internal bool IsCatchBlockExist internal TryCatchFinallyHandler(int tryStart, int tryEnd, int gotoEndTargetIndex, ExceptionHandler[] handlers) : this(tryStart, tryEnd, gotoEndTargetIndex, Instruction.UnknownInstrIndex, Instruction.UnknownInstrIndex, handlers) { - Debug.Assert(handlers != null, "catch blocks should exist"); + Debug.Assert(handlers is not null, "catch blocks should exist"); } /// @@ -151,7 +151,7 @@ internal TryCatchFinallyHandler(int tryStart, int tryEnd, int gotoEndLabelIndex, _handlers = handlers; - if (_handlers != null) + if (_handlers is not null) { for (int index = 0; index < _handlers.Length; index++) { @@ -166,7 +166,7 @@ internal TryCatchFinallyHandler(int tryStart, int tryEnd, int gotoEndLabelIndex, /// internal int GotoHandler(InterpretedFrame frame, object exception, out ExceptionHandler handler) { - Debug.Assert(_handlers != null, "we should have at least one handler if the method gets called"); + Debug.Assert(_handlers is not 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; } @@ -259,7 +259,7 @@ public InterpretedFrameInfo(string methodName, DebugInfo info) public override string ToString() { - return MethodName + (DebugInfo != null ? ": " + DebugInfo : null); + return MethodName + (DebugInfo is not null ? ": " + DebugInfo : null); } } @@ -386,7 +386,7 @@ private void CompileDefaultExpression(Type type) if (type.IsValueType) { object value = ScriptingRuntimeHelpers.GetPrimitiveDefaultValue(type); - if (value != null) + if (value is not null) { _instructions.EmitLoad(value); } @@ -414,7 +414,7 @@ private LocalVariable EnsureAvailableForClosure(ParameterExpression expr) return local; } - else if (_parent != null) + else if (_parent is not null) { _parent.EnsureAvailableForClosure(expr); return _locals.AddClosureVariable(expr); @@ -585,7 +585,7 @@ private void CompileIndexExpression(Expression expr) var index = (IndexExpression)expr; // instance: - if (index.Object != null) + if (index.Object is not null) { Compile(index.Object); } @@ -597,7 +597,7 @@ private void CompileIndexExpression(Expression expr) Compile(arg); } - if (index.Indexer != null) + if (index.Indexer is not null) { _instructions.EmitCall(index.Indexer.GetMethod); } @@ -621,7 +621,7 @@ private void CompileIndexAssignment(BinaryExpression node, bool asVoid) } // instance: - if (index.Object != null) + if (index.Object is not null) { Compile(index.Object); } @@ -636,7 +636,7 @@ private void CompileIndexAssignment(BinaryExpression node, bool asVoid) // value: Compile(node.Right); - if (index.Indexer != null) + if (index.Indexer is not null) { _instructions.EmitCall(index.Indexer.SetMethod); } @@ -655,10 +655,10 @@ private void CompileMemberAssignment(BinaryExpression node, bool asVoid) var member = (MemberExpression)node.Left; PropertyInfo pi = member.Member as PropertyInfo; - if (pi != null) + if (pi is not null) { var method = pi.SetMethod; - if (member.Expression != null) + if (member.Expression is not null) { Compile(member.Expression); } @@ -683,9 +683,9 @@ private void CompileMemberAssignment(BinaryExpression node, bool asVoid) } FieldInfo fi = member.Member as FieldInfo; - if (fi != null) + if (fi is not null) { - if (member.Expression != null) + if (member.Expression is not null) { Compile(member.Expression); } @@ -748,7 +748,7 @@ private void CompileBinaryExpression(Expression expr) { var node = (BinaryExpression)expr; - if (node.Method != null) + if (node.Method is not null) { Compile(node.Left); Compile(node.Right); @@ -855,7 +855,7 @@ private void CompileArithmetic(ExpressionType nodeType, Expression left, Express private void CompileConvertUnaryExpression(Expression expr) { var node = (UnaryExpression)expr; - if (node.Method != null) + if (node.Method is not null) { Compile(node.Operand); @@ -923,7 +923,7 @@ private void CompileUnaryExpression(Expression expr) { var node = (UnaryExpression)expr; - if (node.Method != null) + if (node.Method is not null) { Compile(node.Operand); _instructions.EmitCall(node.Method); @@ -957,7 +957,7 @@ private void CompileOrElseBinaryExpression(Expression expr) private void CompileLogicalBinaryExpression(Expression expr, bool andAlso) { var node = (BinaryExpression)expr; - if (node.Method != null) + if (node.Method is not null) { throw new NotImplementedException(); } @@ -1057,7 +1057,7 @@ private void CompileSwitchExpression(Expression expr) var node = (SwitchExpression)expr; // Currently only supports int test values, with no method - if (node.SwitchValue.Type != typeof(int) || node.Comparison != null) + if (node.SwitchValue.Type != typeof(int) || node.Comparison is not null) { throw new NotImplementedException(); } @@ -1076,7 +1076,7 @@ private void CompileSwitchExpression(Expression expr) int switchIndex = _instructions.Count; _instructions.EmitSwitch(caseDict); - if (node.DefaultBody != null) + if (node.DefaultBody is not null) { Compile(node.DefaultBody); } @@ -1129,7 +1129,7 @@ private void CompileLabelExpression(Expression expr) } // if we're in a switch or block, we should've found the label - Debug.Assert(label != null); + Debug.Assert(label is not null); } if (label is null) @@ -1137,7 +1137,7 @@ private void CompileLabelExpression(Expression expr) label = DefineLabel(node.Target); } - if (node.DefaultValue != null) + if (node.DefaultValue is not null) { if (node.Target.Type == typeof(void)) { @@ -1157,12 +1157,12 @@ private void CompileGotoExpression(Expression expr) var node = (GotoExpression)expr; var labelInfo = ReferenceLabel(node.Target); - if (node.Value != null) + if (node.Value is not null) { Compile(node.Value); } - _instructions.EmitGoto(labelInfo.GetLabel(this), node.Type != typeof(void), node.Value != null && node.Value.Type != typeof(void)); + _instructions.EmitGoto(labelInfo.GetLabel(this), node.Type != typeof(void), node.Value is not null && node.Value.Type != typeof(void)); } public BranchLabel GetBranchLabel(LabelTarget target) @@ -1178,7 +1178,7 @@ public void PushLabelBlock(LabelScopeKind type) [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "kind")] public void PopLabelBlock(LabelScopeKind kind) { - Debug.Assert(_labelBlock != null && _labelBlock.Kind == kind); + Debug.Assert(_labelBlock is not null && _labelBlock.Kind == kind); _labelBlock = _labelBlock.Parent; } @@ -1308,7 +1308,7 @@ private void DefineBlockLabels(Expression node) Expression e = block.Expressions[i]; var label = e as LabelExpression; - if (label != null) + if (label is not null) { DefineLabel(label.Target); } @@ -1366,7 +1366,7 @@ private bool EndsWithRethrow(Expression expr) } BlockExpression block = expr as BlockExpression; - if (block != null) + if (block is not null) { return EndsWithRethrow(block.Expressions[block.Expressions.Count - 1]); } @@ -1404,7 +1404,7 @@ private void CompileTryExpression(Expression expr) int tryStart = _instructions.Count; BranchLabel startOfFinally = null; - if (node.Finally != null) + if (node.Finally is not null) { startOfFinally = _instructions.MakeLabel(); _instructions.EmitEnterTryFinally(startOfFinally); @@ -1416,7 +1416,7 @@ private void CompileTryExpression(Expression expr) List exHandlers = null; var enterTryInstr = _instructions.GetInstruction(tryStart) as EnterTryCatchFinallyInstruction; - Debug.Assert(enterTryInstr != null); + Debug.Assert(enterTryInstr is not null); PushLabelBlock(LabelScopeKind.Try); Compile(node.Body); @@ -1471,7 +1471,7 @@ private void CompileTryExpression(Expression expr) var handler = node.Handlers[index]; PushLabelBlock(LabelScopeKind.Catch); - if (handler.Filter != null) + if (handler.Filter is not null) { // PushLabelBlock(LabelScopeKind.Filter); throw new NotImplementedException(); @@ -1513,15 +1513,15 @@ private void CompileTryExpression(Expression expr) _locals.UndefineLocal(local, _instructions.Count); } - if (node.Fault != null) + if (node.Fault is not null) { throw new NotImplementedException(); } } - if (node.Finally != null) + if (node.Finally is not null) { - Debug.Assert(startOfFinally != null); + Debug.Assert(startOfFinally is not null); PushLabelBlock(LabelScopeKind.Finally); _instructions.MarkLabel(startOfFinally); @@ -1532,12 +1532,12 @@ private void CompileTryExpression(Expression expr) enterTryInstr.SetTryHandler( new TryCatchFinallyHandler(tryStart, tryEnd, gotoEnd.TargetIndex, startOfFinally.TargetIndex, _instructions.Count, - exHandlers != null ? exHandlers.ToArray() : null)); + exHandlers is not null ? exHandlers.ToArray() : null)); PopLabelBlock(LabelScopeKind.Finally); } else { - Debug.Assert(exHandlers != null); + Debug.Assert(exHandlers is not null); enterTryInstr.SetTryHandler( new TryCatchFinallyHandler(tryStart, tryEnd, gotoEnd.TargetIndex, exHandlers.ToArray())); } @@ -1598,7 +1598,7 @@ private void CompileNewExpression(Expression expr) { var node = (NewExpression)expr; - if (node.Constructor != null) + if (node.Constructor is not null) { var parameters = node.Constructor.GetParameters(); if (!parameters.TrueForAll(p => !p.ParameterType.IsByRef)) @@ -1607,7 +1607,7 @@ private void CompileNewExpression(Expression expr) } } - if (node.Constructor != null) + if (node.Constructor is not null) { for (int index = 0; index < node.Arguments.Count; index++) { @@ -1630,7 +1630,7 @@ private void CompileMemberExpression(Expression expr) var member = node.Member; FieldInfo fi = member as FieldInfo; - if (fi != null) + if (fi is not null) { if (fi.IsLiteral) { @@ -1657,10 +1657,10 @@ private void CompileMemberExpression(Expression expr) } PropertyInfo pi = member as PropertyInfo; - if (pi != null) + if (pi is not null) { var method = pi.GetMethod; - if (node.Expression != null) + if (node.Expression is not null) { Compile(node.Expression); } @@ -1709,7 +1709,7 @@ private void CompileNewArrayExpression(Expression expr) private void CompileExtensionExpression(Expression expr) { var instructionProvider = expr as IInstructionProvider; - if (instructionProvider != null) + if (instructionProvider is not null) { instructionProvider.AddInstructions(this); return; @@ -1760,7 +1760,7 @@ private void CompileLambdaExpression(Expression expr) var compiler = new LightCompiler(this); var creator = compiler.CompileTop(node); - if (compiler._locals.ClosureVariables != null) + if (compiler._locals.ClosureVariables is not null) { foreach (ParameterExpression variable in compiler._locals.ClosureVariables.Keys) { @@ -1779,7 +1779,7 @@ private void CompileCoalesceBinaryExpression(Expression expr) { throw new NotImplementedException(); } - else if (node.Conversion != null) + else if (node.Conversion is not null) { throw new NotImplementedException(); } diff --git a/src/System.Management.Automation/engine/interpreter/LightDelegateCreator.cs b/src/System.Management.Automation/engine/interpreter/LightDelegateCreator.cs index 58bf458a683..d71d02ed370 100644 --- a/src/System.Management.Automation/engine/interpreter/LightDelegateCreator.cs +++ b/src/System.Management.Automation/engine/interpreter/LightDelegateCreator.cs @@ -58,12 +58,12 @@ internal Interpreter Interpreter private bool HasClosure { - get { return _interpreter != null && _interpreter.ClosureSize > 0; } + get { return _interpreter is not null && _interpreter.ClosureSize > 0; } } internal bool HasCompiled { - get { return _compiled != null; } + get { return _compiled is not null; } } /// @@ -82,7 +82,7 @@ public Delegate CreateDelegate() internal Delegate CreateDelegate(StrongBox[] closure) { - if (_compiled != null) + if (_compiled is not null) { // If the delegate type we want is not a Func/Action, we can't // use the compiled code directly. So instead just fall through @@ -116,7 +116,7 @@ private Type DelegateType get { LambdaExpression le = _lambda as LambdaExpression; - if (le != null) + if (le is not null) { return le.Type; } @@ -131,7 +131,7 @@ private Type DelegateType /// internal Delegate CreateCompiledDelegate(StrongBox[] closure) { - Debug.Assert(HasClosure == (closure != null)); + Debug.Assert(HasClosure == (closure is not null)); if (HasClosure) { @@ -150,7 +150,7 @@ internal Delegate CreateCompiledDelegate(StrongBox[] closure) /// internal void Compile(object state) { - if (_compiled != null) + if (_compiled is not null) { return; } @@ -158,7 +158,7 @@ internal void Compile(object state) // Compilation is expensive, we only want to do it once. lock (_compileLock) { - if (_compiled != null) + if (_compiled is not null) { return; } @@ -170,7 +170,7 @@ internal void Compile(object state) // Action<...> so it can be called from the LightLambda.Run // methods. LambdaExpression lambda = (_lambda as LambdaExpression);// ?? (LambdaExpression)((LightLambdaExpression)_lambda).Reduce(); - if (_interpreter != null) + if (_interpreter is not null) { _compiledDelegateType = GetFuncOrAction(lambda); lambda = Expression.Lambda(_compiledDelegateType, lambda.Body, lambda.Name, lambda.Parameters); diff --git a/src/System.Management.Automation/engine/interpreter/LightLambda.Generated.cs b/src/System.Management.Automation/engine/interpreter/LightLambda.Generated.cs index 7ff5de773c5..206da2f33fd 100644 --- a/src/System.Management.Automation/engine/interpreter/LightLambda.Generated.cs +++ b/src/System.Management.Automation/engine/interpreter/LightLambda.Generated.cs @@ -26,7 +26,7 @@ internal partial class LightLambda { internal const int MaxParameters = 16; internal TRet Run0() { - if (_compiled != null || TryGetCompiled()) { + if (_compiled is not null || TryGetCompiled()) { return ((Func)_compiled)(); } @@ -38,7 +38,7 @@ internal TRet Run0() { } internal void RunVoid0() { - if (_compiled != null || TryGetCompiled()) { + if (_compiled is not null || TryGetCompiled()) { ((Action)_compiled)(); return; } @@ -57,7 +57,7 @@ internal static Delegate MakeRunVoid0(LightLambda lambda) { } internal TRet Run1(T0 arg0) { - if (_compiled != null || TryGetCompiled()) { + if (_compiled is not null || TryGetCompiled()) { return ((Func)_compiled)(arg0); } @@ -70,7 +70,7 @@ internal TRet Run1(T0 arg0) { } internal void RunVoid1(T0 arg0) { - if (_compiled != null || TryGetCompiled()) { + if (_compiled is not null || TryGetCompiled()) { ((Action)_compiled)(arg0); return; } @@ -90,7 +90,7 @@ internal static Delegate MakeRunVoid1(LightLambda lambda) { } internal TRet Run2(T0 arg0,T1 arg1) { - if (_compiled != null || TryGetCompiled()) { + if (_compiled is not null || TryGetCompiled()) { return ((Func)_compiled)(arg0, arg1); } @@ -104,7 +104,7 @@ internal TRet Run2(T0 arg0,T1 arg1) { } internal void RunVoid2(T0 arg0,T1 arg1) { - if (_compiled != null || TryGetCompiled()) { + if (_compiled is not null || TryGetCompiled()) { ((Action)_compiled)(arg0, arg1); return; } @@ -125,7 +125,7 @@ internal static Delegate MakeRunVoid2(LightLambda lambda) { } internal TRet Run3(T0 arg0,T1 arg1,T2 arg2) { - if (_compiled != null || TryGetCompiled()) { + if (_compiled is not null || TryGetCompiled()) { return ((Func)_compiled)(arg0, arg1, arg2); } @@ -140,7 +140,7 @@ internal TRet Run3(T0 arg0,T1 arg1,T2 arg2) { } internal void RunVoid3(T0 arg0,T1 arg1,T2 arg2) { - if (_compiled != null || TryGetCompiled()) { + if (_compiled is not null || TryGetCompiled()) { ((Action)_compiled)(arg0, arg1, arg2); return; } @@ -162,7 +162,7 @@ internal static Delegate MakeRunVoid3(LightLambda lambda) { } internal TRet Run4(T0 arg0,T1 arg1,T2 arg2,T3 arg3) { - if (_compiled != null || TryGetCompiled()) { + if (_compiled is not null || TryGetCompiled()) { return ((Func)_compiled)(arg0, arg1, arg2, arg3); } @@ -178,7 +178,7 @@ internal TRet Run4(T0 arg0,T1 arg1,T2 arg2,T3 arg3) { } internal void RunVoid4(T0 arg0,T1 arg1,T2 arg2,T3 arg3) { - if (_compiled != null || TryGetCompiled()) { + if (_compiled is not null || TryGetCompiled()) { ((Action)_compiled)(arg0, arg1, arg2, arg3); return; } @@ -201,7 +201,7 @@ internal static Delegate MakeRunVoid4(LightLambda lambda) { } internal TRet Run5(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4) { - if (_compiled != null || TryGetCompiled()) { + if (_compiled is not null || TryGetCompiled()) { return ((Func)_compiled)(arg0, arg1, arg2, arg3, arg4); } @@ -218,7 +218,7 @@ internal TRet Run5(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4) } internal void RunVoid5(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4) { - if (_compiled != null || TryGetCompiled()) { + if (_compiled is not null || TryGetCompiled()) { ((Action)_compiled)(arg0, arg1, arg2, arg3, arg4); return; } @@ -242,7 +242,7 @@ internal static Delegate MakeRunVoid5(LightLambda lambda) { } internal TRet Run6(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5) { - if (_compiled != null || TryGetCompiled()) { + if (_compiled is not null || TryGetCompiled()) { return ((Func)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5); } @@ -260,7 +260,7 @@ internal TRet Run6(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 ar } internal void RunVoid6(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5) { - if (_compiled != null || TryGetCompiled()) { + if (_compiled is not null || TryGetCompiled()) { ((Action)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5); return; } @@ -285,7 +285,7 @@ internal static Delegate MakeRunVoid6(LightLambda lambda) { } internal TRet Run7(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6) { - if (_compiled != null || TryGetCompiled()) { + if (_compiled is not null || TryGetCompiled()) { return ((Func)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6); } @@ -304,7 +304,7 @@ internal TRet Run7(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 } internal void RunVoid7(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6) { - if (_compiled != null || TryGetCompiled()) { + if (_compiled is not null || TryGetCompiled()) { ((Action)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6); return; } @@ -330,7 +330,7 @@ internal static Delegate MakeRunVoid7(LightLambda lambda) } internal TRet Run8(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7) { - if (_compiled != null || TryGetCompiled()) { + if (_compiled is not null || TryGetCompiled()) { return ((Func)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7); } @@ -350,7 +350,7 @@ internal TRet Run8(T0 arg0,T1 arg1,T2 arg2,T3 arg3 } internal void RunVoid8(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7) { - if (_compiled != null || TryGetCompiled()) { + if (_compiled is not null || TryGetCompiled()) { ((Action)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7); return; } @@ -377,7 +377,7 @@ internal static Delegate MakeRunVoid8(LightLambda lambd } internal TRet Run9(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8) { - if (_compiled != null || TryGetCompiled()) { + if (_compiled is not null || TryGetCompiled()) { return ((Func)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); } @@ -398,7 +398,7 @@ internal TRet Run9(T0 arg0,T1 arg1,T2 arg2,T3 a } internal void RunVoid9(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8) { - if (_compiled != null || TryGetCompiled()) { + if (_compiled is not null || TryGetCompiled()) { ((Action)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); return; } @@ -426,7 +426,7 @@ internal static Delegate MakeRunVoid9(LightLambda la } internal TRet Run10(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9) { - if (_compiled != null || TryGetCompiled()) { + if (_compiled is not null || TryGetCompiled()) { return ((Func)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9); } @@ -448,7 +448,7 @@ internal TRet Run10(T0 arg0,T1 arg1,T2 arg2, } internal void RunVoid10(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9) { - if (_compiled != null || TryGetCompiled()) { + if (_compiled is not null || TryGetCompiled()) { ((Action)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9); return; } @@ -477,7 +477,7 @@ internal static Delegate MakeRunVoid10(LightLambd } internal TRet Run11(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10) { - if (_compiled != null || TryGetCompiled()) { + if (_compiled is not null || TryGetCompiled()) { return ((Func)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10); } @@ -500,7 +500,7 @@ internal TRet Run11(T0 arg0,T1 arg1,T2 a } internal void RunVoid11(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10) { - if (_compiled != null || TryGetCompiled()) { + if (_compiled is not null || TryGetCompiled()) { ((Action)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10); return; } @@ -530,7 +530,7 @@ internal static Delegate MakeRunVoid11(LightL } internal TRet Run12(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10,T11 arg11) { - if (_compiled != null || TryGetCompiled()) { + if (_compiled is not null || TryGetCompiled()) { return ((Func)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11); } @@ -554,7 +554,7 @@ internal TRet Run12(T0 arg0,T1 arg1, } internal void RunVoid12(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10,T11 arg11) { - if (_compiled != null || TryGetCompiled()) { + if (_compiled is not null || TryGetCompiled()) { ((Action)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11); return; } @@ -585,7 +585,7 @@ internal static Delegate MakeRunVoid12(Li } internal TRet Run13(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10,T11 arg11,T12 arg12) { - if (_compiled != null || TryGetCompiled()) { + if (_compiled is not null || TryGetCompiled()) { return ((Func)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12); } @@ -610,7 +610,7 @@ internal TRet Run13(T0 arg0,T1 a } internal void RunVoid13(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10,T11 arg11,T12 arg12) { - if (_compiled != null || TryGetCompiled()) { + if (_compiled is not null || TryGetCompiled()) { ((Action)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12); return; } @@ -642,7 +642,7 @@ internal static Delegate MakeRunVoid13(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10,T11 arg11,T12 arg12,T13 arg13) { - if (_compiled != null || TryGetCompiled()) { + if (_compiled is not null || TryGetCompiled()) { return ((Func)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13); } @@ -668,7 +668,7 @@ internal TRet Run14(T0 arg0, } internal void RunVoid14(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10,T11 arg11,T12 arg12,T13 arg13) { - if (_compiled != null || TryGetCompiled()) { + if (_compiled is not null || TryGetCompiled()) { ((Action)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13); return; } @@ -701,7 +701,7 @@ internal static Delegate MakeRunVoid14(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10,T11 arg11,T12 arg12,T13 arg13,T14 arg14) { - if (_compiled != null || TryGetCompiled()) { + if (_compiled is not null || TryGetCompiled()) { return ((Func)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14); } @@ -728,7 +728,7 @@ internal TRet Run15(T0 a } internal void RunVoid15(T0 arg0,T1 arg1,T2 arg2,T3 arg3,T4 arg4,T5 arg5,T6 arg6,T7 arg7,T8 arg8,T9 arg9,T10 arg10,T11 arg11,T12 arg12,T13 arg13,T14 arg14) { - if (_compiled != null || TryGetCompiled()) { + if (_compiled is not null || TryGetCompiled()) { ((Action)_compiled)(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14); return; } diff --git a/src/System.Management.Automation/engine/interpreter/LightLambda.cs b/src/System.Management.Automation/engine/interpreter/LightLambda.cs index 3bf38da35b9..481f3daebd1 100644 --- a/src/System.Management.Automation/engine/interpreter/LightLambda.cs +++ b/src/System.Management.Automation/engine/interpreter/LightLambda.cs @@ -184,7 +184,7 @@ private Delegate CreateCustomDelegate(Type delegateType) internal Delegate MakeDelegate(Type delegateType) { Func fastCtor = GetRunDelegateCtor(delegateType); - if (fastCtor != null) + if (fastCtor is not null) { return fastCtor(this); } @@ -203,7 +203,7 @@ private bool TryGetCompiled() // Send it to anyone who's interested. var compileEvent = Compile; - if (compileEvent != null && _delegateCreator.SameDelegateType) + if (compileEvent is not null && _delegateCreator.SameDelegateType) { compileEvent(this, new LightLambdaCompileEventArgs(_compiled)); } @@ -252,7 +252,7 @@ private InterpretedFrame MakeFrame() internal void RunVoidRef2(ref T0 arg0, ref T1 arg1) { - // if (_compiled != null || TryGetCompiled()) { + // if (_compiled is not null || TryGetCompiled()) { // ((ActionRef)_compiled)(ref arg0, ref arg1); // return; // } @@ -276,7 +276,7 @@ internal void RunVoidRef2(ref T0 arg0, ref T1 arg1) public object Run(params object[] arguments) { - if (_compiled != null || TryGetCompiled()) + if (_compiled is not null || TryGetCompiled()) { return _compiled.DynamicInvoke(arguments); } diff --git a/src/System.Management.Automation/engine/interpreter/LightLambdaClosureVisitor.cs b/src/System.Management.Automation/engine/interpreter/LightLambdaClosureVisitor.cs index 043b729a18b..13de63b992b 100644 --- a/src/System.Management.Automation/engine/interpreter/LightLambdaClosureVisitor.cs +++ b/src/System.Management.Automation/engine/interpreter/LightLambdaClosureVisitor.cs @@ -120,14 +120,14 @@ protected override Expression VisitBlock(BlockExpression node) protected override CatchBlock VisitCatchBlock(CatchBlock node) { - if (node.Variable != null) + if (node.Variable is not null) { _shadowedVars.Push(new HashSet(new[] { node.Variable })); } Expression b = Visit(node.Body); Expression f = Visit(node.Filter); - if (node.Variable != null) + if (node.Variable is not null) { _shadowedVars.Pop(); } @@ -202,7 +202,7 @@ protected override Expression VisitBinary(BinaryExpression node) { var variable = (ParameterExpression)node.Left; Expression closureItem = GetClosureItem(variable, true); - if (closureItem != null) + if (closureItem is not null) { // We need to convert to object to store the value in the box. return Expression.Block( diff --git a/src/System.Management.Automation/engine/interpreter/LocalVariables.cs b/src/System.Management.Automation/engine/interpreter/LocalVariables.cs index f9e28d96e26..011a6a4022c 100644 --- a/src/System.Management.Automation/engine/interpreter/LocalVariables.cs +++ b/src/System.Management.Automation/engine/interpreter/LocalVariables.cs @@ -180,7 +180,7 @@ public void UndefineLocal(LocalDefinition definition, int end) { var scope = _variables[definition.Parameter]; scope.Stop = end; - if (scope.Parent != null) + if (scope.Parent is not null) { _variables[definition.Parameter] = scope.Parent; } @@ -203,7 +203,7 @@ internal void Box(ParameterExpression variable, InstructionList instructions) int curChild = 0; for (int i = scope.Start; i < scope.Stop && i < instructions.Count; i++) { - if (scope.ChildScopes != null && scope.ChildScopes[curChild].Start == i) + if (scope.ChildScopes is not null && scope.ChildScopes[curChild].Start == i) { // skip boxing in the child scope var child = scope.ChildScopes[curChild]; @@ -248,7 +248,7 @@ public bool TryGetLocalOrClosure(ParameterExpression var, out LocalVariable loca return true; } - if (_closureVariables != null && _closureVariables.TryGetValue(var, out local)) + if (_closureVariables is not null && _closureVariables.TryGetValue(var, out local)) { return true; } diff --git a/src/System.Management.Automation/engine/interpreter/LoopCompiler.cs b/src/System.Management.Automation/engine/interpreter/LoopCompiler.cs index b7933085921..2acbea5947a 100644 --- a/src/System.Management.Automation/engine/interpreter/LoopCompiler.cs +++ b/src/System.Management.Automation/engine/interpreter/LoopCompiler.cs @@ -103,7 +103,7 @@ internal LoopFunc CreateDelegate() if (local.InClosureOrBoxed) { var box = variable.Value.BoxStorage; - Debug.Assert(box != null); + Debug.Assert(box is not null); body.Add(Expression.Assign(box, elemRef)); AddTemp(box); } @@ -135,7 +135,7 @@ internal LoopFunc CreateDelegate() body.Add(Expression.Label(_returnLabel, Expression.Constant(_loopEndInstructionIndex - _loopStartInstructionIndex))); var lambda = Expression.Lambda( - _temps != null ? Expression.Block(_temps, body) : Expression.Block(body), + _temps is not null ? Expression.Block(_temps, body) : Expression.Block(body), new[] { _frameDataVar, _frameClosureVar, _frameVar } ); return lambda.Compile(); @@ -177,7 +177,7 @@ protected override Expression VisitGoto(GotoExpression node) } return Expression.Return(_returnLabel, - (value != null && value.Type != typeof(void)) ? + (value is not null && value.Type != typeof(void)) ? Expression.Call(_frameVar, InterpretedFrame.GotoMethod, Expression.Constant(label.LabelIndex), AstUtils.Box(value)) : Expression.Call(_frameVar, InterpretedFrame.VoidGotoMethod, Expression.Constant(label.LabelIndex)), node.Type @@ -219,7 +219,7 @@ private HashSet EnterVariableScope(ICollection), node.Name) : null; @@ -352,7 +352,7 @@ private Expression VisitVariable(ParameterExpression node, ExpressionAccess acce return node; } - if (box != null) + if (box is not null) { if ((access & ExpressionAccess.Write) != 0) { diff --git a/src/System.Management.Automation/engine/interpreter/TypeOperations.cs b/src/System.Management.Automation/engine/interpreter/TypeOperations.cs index 190e89d6e0b..2ade4251a39 100644 --- a/src/System.Management.Automation/engine/interpreter/TypeOperations.cs +++ b/src/System.Management.Automation/engine/interpreter/TypeOperations.cs @@ -185,7 +185,7 @@ public override int Run(InterpretedFrame frame) { object type = frame.Pop(); object obj = frame.Pop(); - frame.Push(ScriptingRuntimeHelpers.BooleanToObject(obj != null && (object)obj.GetType() == type)); + frame.Push(ScriptingRuntimeHelpers.BooleanToObject(obj is not null && (object)obj.GetType() == type)); return +1; } diff --git a/src/System.Management.Automation/engine/interpreter/Utilities.cs b/src/System.Management.Automation/engine/interpreter/Utilities.cs index 3001068a088..6f75906c410 100644 --- a/src/System.Management.Automation/engine/interpreter/Utilities.cs +++ b/src/System.Management.Automation/engine/interpreter/Utilities.cs @@ -27,7 +27,7 @@ internal static Type GetNonNullableType(this Type type) internal static Type GetNullableType(Type type) { - Debug.Assert(type != null, "type cannot be null"); + Debug.Assert(type is not null, "type cannot be null"); if (type.IsValueType && !IsNullableType(type)) { return typeof(Nullable<>).MakeGenericType(type); @@ -143,7 +143,7 @@ internal static class DelegateHelpers [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] internal static Type MakeDelegate(Type[] types) { - Debug.Assert(types != null && types.Length > 0); + Debug.Assert(types is not null && types.Length > 0); // Can only used predefined delegates if we have no byref types and // the arity is small enough to fit in Func<...> or Action<...> @@ -363,7 +363,7 @@ private static void AssociateStackTraces(Exception e, List traces) private static bool TryGetAssociatedStackTraces(Exception e, out List traces) { traces = e.Data[prevStackTraces] as List; - return traces != null; + return traces is not null; } } @@ -396,13 +396,13 @@ public HybridReferenceDictionary(int initialCapacity) public bool TryGetValue(TKey key, out TValue value) { - Debug.Assert(key != null); + Debug.Assert(key is not null); - if (_dict != null) + if (_dict is not null) { return _dict.TryGetValue(key, out value); } - else if (_keysAndValues != null) + else if (_keysAndValues is not null) { for (int i = 0; i < _keysAndValues.Length; i++) { @@ -420,13 +420,13 @@ public bool TryGetValue(TKey key, out TValue value) public bool Remove(TKey key) { - Debug.Assert(key != null); + Debug.Assert(key is not null); - if (_dict != null) + if (_dict is not null) { return _dict.Remove(key); } - else if (_keysAndValues != null) + else if (_keysAndValues is not null) { for (int i = 0; i < _keysAndValues.Length; i++) { @@ -444,13 +444,13 @@ public bool Remove(TKey key) public bool ContainsKey(TKey key) { - Debug.Assert(key != null); + Debug.Assert(key is not null); - if (_dict != null) + if (_dict is not null) { return _dict.ContainsKey(key); } - else if (_keysAndValues != null) + else if (_keysAndValues is not null) { for (int i = 0; i < _keysAndValues.Length; i++) { @@ -468,7 +468,7 @@ public int Count { get { - if (_dict != null) + if (_dict is not null) { return _dict.Count; } @@ -479,7 +479,7 @@ public int Count public IEnumerator> GetEnumerator() { - if (_dict != null) + if (_dict is not null) { return _dict.GetEnumerator(); } @@ -489,11 +489,11 @@ public IEnumerator> GetEnumerator() private IEnumerator> GetEnumeratorWorker() { - if (_keysAndValues != null) + if (_keysAndValues is not null) { for (int i = 0; i < _keysAndValues.Length; i++) { - if (_keysAndValues[i].Key != null) + if (_keysAndValues[i].Key is not null) { yield return _keysAndValues[i]; } @@ -505,7 +505,7 @@ public TValue this[TKey key] { get { - Debug.Assert(key != null); + Debug.Assert(key is not null); TValue res; if (TryGetValue(key, out res)) @@ -518,16 +518,16 @@ public TValue this[TKey key] set { - Debug.Assert(key != null); + Debug.Assert(key is not null); - if (_dict != null) + if (_dict is not null) { _dict[key] = value; } else { int index; - if (_keysAndValues != null) + if (_keysAndValues is not null) { index = -1; for (int i = 0; i < _keysAndValues.Length; i++) @@ -602,7 +602,7 @@ public bool TryGetValue(TKey key, out TValue value) if (_dict.TryGetValue(key, out storedValue)) { LinkedListNode node = storedValue.List; - if (node.Previous != null) + if (node.Previous is not null) { // move us to the head of the list... _list.Remove(node); @@ -782,11 +782,11 @@ private StorageInfo GetStorageInfo(StorageInfo[] curStorage) int threadId = Thread.CurrentThread.ManagedThreadId; // fast path if we already have a value in the array - if (curStorage != null && curStorage.Length > threadId) + if (curStorage is not null && curStorage.Length > threadId) { StorageInfo res = curStorage[threadId]; - if (res != null && (_refCounted || res.Thread == Thread.CurrentThread)) + if (res is not null && (_refCounted || res.Thread == Thread.CurrentThread)) { return res; } @@ -851,7 +851,7 @@ private StorageInfo CreateStorageInfo() for (int i = 0; i < curStorage.Length; i++) { // leave out the threads that have exited - if (curStorage[i] != null && curStorage[i].Thread.IsAlive) + if (curStorage[i] is not null && curStorage[i].Thread.IsAlive) { newStorage[i] = curStorage[i]; } @@ -913,28 +913,28 @@ internal static Exception Unreachable [Conditional("DEBUG")] public static void NotNull(object var) { - Debug.Assert(var != null); + Debug.Assert(var is not null); } [Conditional("DEBUG")] public static void NotNull(object var1, object var2) { - Debug.Assert(var1 != null && var2 != null); + Debug.Assert(var1 is not null && var2 is not null); } [Conditional("DEBUG")] public static void NotNull(object var1, object var2, object var3) { - Debug.Assert(var1 != null && var2 != null && var3 != null); + Debug.Assert(var1 is not null && var2 is not null && var3 is not null); } [Conditional("DEBUG")] public static void NotNullItems(IEnumerable items) where T : class { - Debug.Assert(items != null); + Debug.Assert(items is not null); foreach (object item in items) { - Debug.Assert(item != null); + Debug.Assert(item is not null); } } diff --git a/src/System.Management.Automation/engine/lang/interface/PSParseError.cs b/src/System.Management.Automation/engine/lang/interface/PSParseError.cs index 5fa12cc073c..20069f6d453 100644 --- a/src/System.Management.Automation/engine/lang/interface/PSParseError.cs +++ b/src/System.Management.Automation/engine/lang/interface/PSParseError.cs @@ -21,8 +21,8 @@ public sealed class PSParseError { internal PSParseError(RuntimeException rte) { - Dbg.Assert(rte != null, "exception argument should not be null"); - Dbg.Assert(rte.ErrorToken != null, "token for exception should not be null"); + Dbg.Assert(rte is not null, "exception argument should not be null"); + Dbg.Assert(rte.ErrorToken is not null, "token for exception should not be null"); Message = rte.Message; Token = new PSToken(rte.ErrorToken); diff --git a/src/System.Management.Automation/engine/lang/interface/PSParser.cs b/src/System.Management.Automation/engine/lang/interface/PSParser.cs index 3df14dfea14..a62d442b581 100644 --- a/src/System.Management.Automation/engine/lang/interface/PSParser.cs +++ b/src/System.Management.Automation/engine/lang/interface/PSParser.cs @@ -179,7 +179,7 @@ public static Collection Tokenize(object[] script, out Collection result = new List(); IEnumerator enumerator = LanguagePrimitives.GetEnumerator(tuple); - if (enumerator != null) + if (enumerator is not null) { while (ParserOps.MoveNext(context, errorPosition, enumerator)) { @@ -544,13 +544,13 @@ private static IReadOnlyList SplitOperatorImpl(ExecutionContext context, if (args.Length >= 2) limit = FixNum(args[1], errorPosition); - if (args.Length >= 3 && args[2] != null) + if (args.Length >= 3 && args[2] is not null) { string args2asString = args[2] as string; if (args2asString is null || !string.IsNullOrEmpty(args2asString)) { options = ConvertTo(args[2], errorPosition); - if (predicate != null) + if (predicate is not null) { throw InterpreterError.NewInterpreterException(null, typeof(ParseException), errorPosition, "InvalidSplitOptionWithPredicate", ParserStrings.InvalidSplitOptionWithPredicate); @@ -810,7 +810,7 @@ internal static object JoinOperator(ExecutionContext context, IScriptExtent erro // PSObject already has join functionality; just expose it // as an operator. IEnumerable enumerable = LanguagePrimitives.GetEnumerable(lval); - if (enumerable != null) + if (enumerable is not null) { return PSObject.ToStringEnumerable(context, enumerable, separator, null, null); } @@ -921,7 +921,7 @@ internal static object ReplaceOperator(ExecutionContext context, IScriptExtent e rval = PSObject.Base(rval); IList rList = rval as IList; - if (rList != null) + if (rList is not null) { if (rList.Count > 2) { @@ -1241,7 +1241,7 @@ internal static object MatchOperator(ExecutionContext context, IScriptExtent err if (check++ > 1000) { // Check to see if we're stopping every one in a while... - if (context != null && context.CurrentPipelineStopping) + if (context is not null && context.CurrentPipelineStopping) throw new PipelineStoppedException(); check = 0; } @@ -1399,7 +1399,7 @@ internal static bool MoveNext(ExecutionContext context, IScriptExtent errorPosit try { // Check to see if we're stopping... - if (context != null && context.CurrentPipelineStopping) + if (context is not null && context.CurrentPipelineStopping) throw new PipelineStoppedException(); return enumerator.MoveNext(); @@ -1503,7 +1503,7 @@ internal static object CallMethod( bool callStatic, object valueToSet) { - Dbg.Assert(methodName != null, "methodName was null"); + Dbg.Assert(methodName is not null, "methodName was null"); PSMethodInfo targetMethod = null; object targetBase = null; @@ -1585,7 +1585,7 @@ internal static object CallMethod( else { PSMethod adaptedMethod = targetMethod as PSMethod; - if (adaptedMethod != null) + if (adaptedMethod is not null) { return adaptedMethod.Invoke(invocationConstraints, paramArray); } @@ -1907,7 +1907,7 @@ internal static RuntimeException NewInterpreterExceptionByMessage( } // Don't trash the existing InvocationInfo. - if (errorPosition != null) + if (errorPosition is not null) e.ErrorRecord.SetInvocationInfo(new InvocationInfo(null, errorPosition)); return e; } @@ -1941,7 +1941,7 @@ internal static void UpdateExceptionErrorRecordPosition(Exception exception, ISc } var icer = exception as IContainsErrorRecord; - if (icer != null) + if (icer is not null) { var errorRecord = icer.ErrorRecord; var invocationInfo = errorRecord.InvocationInfo; diff --git a/src/System.Management.Automation/engine/lang/scriptblock.cs b/src/System.Management.Automation/engine/lang/scriptblock.cs index ab1d74fc9e6..5b0a2da9d27 100644 --- a/src/System.Management.Automation/engine/lang/scriptblock.cs +++ b/src/System.Management.Automation/engine/lang/scriptblock.cs @@ -90,7 +90,7 @@ public partial class ScriptBlock internal static ScriptBlock Create(ExecutionContext context, string script) { ScriptBlock sb = Create(context.Engine.EngineParser, null, script); - if (context.EngineSessionState != null && context.EngineSessionState.Module != null) + if (context.EngineSessionState is not null && context.EngineSessionState.Module is not null) { sb.SessionStateInternal = context.EngineSessionState; } @@ -230,7 +230,7 @@ public PowerShell GetPowerShell(Dictionary variables, params obj ExecutionContext context = LocalPipeline.GetExecutionContextFromTLS(); Dictionary suppliedVariables = null; - if (variables != null) + if (variables is not null) { suppliedVariables = new Dictionary(variables, StringComparer.OrdinalIgnoreCase); context = null; @@ -324,7 +324,7 @@ public PowerShell GetPowerShell( ExecutionContext context = LocalPipeline.GetExecutionContextFromTLS(); Dictionary suppliedVariables = null; - if (variables != null) + if (variables is not null) { suppliedVariables = new Dictionary(variables, StringComparer.OrdinalIgnoreCase); context = null; @@ -415,7 +415,7 @@ public Collection InvokeWithContext( params object[] args) { Dictionary functionsToDefineDictionary = null; - if (functionsToDefine != null) + if (functionsToDefine is not null) { functionsToDefineDictionary = new Dictionary(); foreach (DictionaryEntry pair in functionsToDefine) @@ -460,12 +460,12 @@ public Collection InvokeWithContext( object dollarUnder = AutomationNull.Value; object scriptThis = AutomationNull.Value; - if (variablesToDefine != null) + if (variablesToDefine is not null) { // Extract the special variables "this", "input" and "_" PSVariable located = variablesToDefine.Find( v => string.Equals(v.Name, "this", StringComparison.OrdinalIgnoreCase)); - if (located != null) + if (located is not null) { scriptThis = located.Value; variablesToDefine.Remove(located); @@ -473,7 +473,7 @@ public Collection InvokeWithContext( located = variablesToDefine.Find( v => string.Equals(v.Name, "_", StringComparison.Ordinal)); - if (located != null) + if (located is not null) { dollarUnder = located.Value; variablesToDefine.Remove(located); @@ -481,7 +481,7 @@ public Collection InvokeWithContext( located = variablesToDefine.Find( v => string.Equals(v.Name, "input", StringComparison.OrdinalIgnoreCase)); - if (located != null) + if (located is not null) { input = located.Value; variablesToDefine.Remove(located); @@ -596,7 +596,7 @@ internal void InvokeAsMemberFunction(object instance, object[] args) /// Get the PSModuleInfo object for the module that defined this /// scriptblock. /// - public PSModuleInfo Module { get => SessionStateInternal != null ? SessionStateInternal.Module : null; } + public PSModuleInfo Module { get => SessionStateInternal is not null ? SessionStateInternal.Module : null; } /// /// Return the PSToken object for this function definition... @@ -630,7 +630,7 @@ internal ReadOnlyCollection OutputType foreach (Attribute attribute in Attributes) { OutputTypeAttribute outputType = attribute as OutputTypeAttribute; - if (outputType != null) + if (outputType is not null) { result.AddRange(outputType.Type); } @@ -669,7 +669,7 @@ internal void InvokeUsingCmdlet( object scriptThis, object[] args) { - Diagnostics.Assert(contextCmdlet != null, "caller to verify contextCmdlet parameter"); + Diagnostics.Assert(contextCmdlet is not null, "caller to verify contextCmdlet parameter"); Pipe outputPipe = ((MshCommandRuntime)contextCmdlet.CommandRuntime).OutputPipe; ExecutionContext context = GetContextFromTLS(); @@ -703,13 +703,13 @@ internal SessionState SessionState if (SessionStateInternal is null) { ExecutionContext context = LocalPipeline.GetExecutionContextFromTLS(); - if (context != null) + if (context is not null) { SessionStateInternal = context.EngineSessionState.PublicSessionState.Internal; } } - return SessionStateInternal != null ? SessionStateInternal.PublicSessionState : null; + return SessionStateInternal is not null ? SessionStateInternal.PublicSessionState : null; } set @@ -954,7 +954,7 @@ internal void InvokeWithPipe( bool oldPropagateExceptions = false; ExecutionContext context = LocalPipeline.GetExecutionContextFromTLS(); - if (SessionStateInternal != null && SessionStateInternal.ExecutionContext != context) + if (SessionStateInternal is not null && SessionStateInternal.ExecutionContext != context) { context = SessionStateInternal.ExecutionContext; shouldGenerateEvent = true; @@ -1035,7 +1035,7 @@ internal void InvokeWithPipe( processInCurrentThread: true, waitForCompletionInCurrentThread: true); - if (scriptBlockInvocationEventArgs.Exception != null) + if (scriptBlockInvocationEventArgs.Exception is not null) { scriptBlockInvocationEventArgs.Exception.Throw(); } @@ -1048,7 +1048,7 @@ internal void InvokeWithPipe( private static void OnScriptBlockInvokeEventHandler(object sender, PSEventArgs args) { var eventArgs = (object)args.SourceEventArgs as ScriptBlockInvocationEventArgs; - Diagnostics.Assert(eventArgs != null, + Diagnostics.Assert(eventArgs is not null, "Event Arguments to OnScriptBlockInvokeEventHandler should not be null"); try @@ -1170,14 +1170,14 @@ private void Begin(bool expectInput, ICommandRuntime commandRuntime) // not expecting input (as indicated by it's position in the pipeline // then neither should we. MshCommandRuntime crt = commandRuntime as MshCommandRuntime; - if (crt != null) + if (crt is not null) { - if (crt.OutputPipe != null) + if (crt.OutputPipe is not null) { _pipeline.LinkPipelineSuccessOutput(crt.OutputPipe); } - if (crt.ErrorOutputPipe != null) + if (crt.ErrorOutputPipe is not null) { _pipeline.LinkPipelineErrorOutput(crt.ErrorOutputPipe); } diff --git a/src/System.Management.Automation/engine/parser/AstVisitor.cs b/src/System.Management.Automation/engine/parser/AstVisitor.cs index 03ce04ea4ad..6a545c1caa0 100644 --- a/src/System.Management.Automation/engine/parser/AstVisitor.cs +++ b/src/System.Management.Automation/engine/parser/AstVisitor.cs @@ -194,7 +194,7 @@ internal AstVisitAction CheckParent(Ast ast) { if (ast != Root) { - Diagnostics.Assert(ast.Parent != null, "Parent not set"); + Diagnostics.Assert(ast.Parent is not null, "Parent not set"); } return AstVisitAction.Continue; @@ -333,7 +333,7 @@ internal class CheckTypeBuilder : AstVisitor2 public override AstVisitAction VisitTypeConstraint(TypeConstraintAst ast) { Type type = ast.TypeName.GetReflectionType(); - if (type != null) + if (type is not null) { Diagnostics.Assert(!(type is TypeBuilder), "ReflectionType can never be TypeBuilder"); } @@ -352,7 +352,7 @@ internal class AstSearcher : AstVisitor2 internal static IEnumerable FindAll(Ast ast, Func predicate, bool searchNestedScriptBlocks) { - Diagnostics.Assert(ast != null && predicate != null, "caller to verify arguments"); + Diagnostics.Assert(ast is not null && predicate is not null, "caller to verify arguments"); var searcher = new AstSearcher(predicate, stopOnFirst: false, searchNestedScriptBlocks: searchNestedScriptBlocks); ast.InternalVisit(searcher); @@ -361,7 +361,7 @@ internal static IEnumerable FindAll(Ast ast, Func predicate, boo internal static Ast FindFirst(Ast ast, Func predicate, bool searchNestedScriptBlocks) { - Diagnostics.Assert(ast != null && predicate != null, "caller to verify arguments"); + Diagnostics.Assert(ast is not null && predicate is not null, "caller to verify arguments"); var searcher = new AstSearcher(predicate, stopOnFirst: true, searchNestedScriptBlocks: searchNestedScriptBlocks); ast.InternalVisit(searcher); @@ -370,7 +370,7 @@ internal static Ast FindFirst(Ast ast, Func predicate, bool searchNes internal static bool Contains(Ast ast, Func predicate, bool searchNestedScriptBlocks) { - Diagnostics.Assert(ast != null && predicate != null, "caller to verify arguments"); + Diagnostics.Assert(ast is not null && predicate is not null, "caller to verify arguments"); var searcher = new AstSearcher(predicate, stopOnFirst: true, searchNestedScriptBlocks: searchNestedScriptBlocks); ast.InternalVisit(searcher); @@ -384,7 +384,7 @@ internal static bool IsUsingDollarInput(Ast ast) ast_ => { var varAst = ast_ as VariableExpressionAst; - if (varAst != null) + if (varAst is not null) { return varAst.VariablePath.IsVariable && varAst.VariablePath.UnqualifiedPath.Equals(SpecialVariables.Input, diff --git a/src/System.Management.Automation/engine/parser/Compiler.cs b/src/System.Management.Automation/engine/parser/Compiler.cs index f7e23e8fcf7..f556facfbe6 100644 --- a/src/System.Management.Automation/engine/parser/Compiler.cs +++ b/src/System.Management.Automation/engine/parser/Compiler.cs @@ -785,7 +785,7 @@ internal class FunctionContext internal IScriptExtent CurrentPosition { - get { return _sequencePoints != null ? _sequencePoints[_currentSequencePointIndex] : PositionUtilities.EmptyExtent; } + get { return _sequencePoints is not null ? _sequencePoints[_currentSequencePointIndex] : PositionUtilities.EmptyExtent; } } internal void PushTrapHandlers(Type[] type, Action[] handler, Type[] tupleType) @@ -1182,7 +1182,7 @@ internal static Expression ConvertValue(TypeConstraintAst typeConstraint, Expres { var typeName = typeConstraint.TypeName; var toType = typeName.GetReflectionType(); - if (toType != null) + if (toType is not null) { if (toType == typeof(void)) { @@ -1208,7 +1208,7 @@ internal static Expression ConvertValue(Expression expr, List for (int index = 0; index < conversions.Count; index++) { var typeConstraint = conversions[index] as TypeConstraintAst; - if (typeConstraint != null) + if (typeConstraint is not null) { expr = ConvertValue(typeConstraint, expr); } @@ -1230,7 +1230,7 @@ internal static RuntimeDefinedParameterDictionary GetParameterMetaData(ReadOnlyC { var param = parameters[index]; var rdp = GetRuntimeDefinedParameter(param, ref customParameterSet, ref usesCmdletBinding); - if (rdp != null) + if (rdp is not null) { runtimeDefinedParamList.Add(rdp); runtimeDefinedParamDict.Add(param.Name.VariablePath.UserPath, rdp); @@ -1519,7 +1519,7 @@ private static Attribute NewOutputTypeAttribute(AttributeAst ast) else if (ast.PositionalArguments.Count == 1) { var typeArg = ast.PositionalArguments[0] as TypeExpressionAst; - if (typeArg != null) + if (typeArg is not null) { var type = TypeOps.ResolveTypeName(typeArg.TypeName, typeArg.Extent); result = new OutputTypeAttribute(type); @@ -1537,7 +1537,7 @@ private static Attribute NewOutputTypeAttribute(AttributeAst ast) { var positionalArgument = ast.PositionalArguments[i]; var typeArg = positionalArgument as TypeExpressionAst; - args[i] = typeArg != null + args[i] = typeArg is not null ? TypeOps.ResolveTypeName(typeArg.TypeName, typeArg.Extent) : positionalArgument.Accept(s_cvv); } @@ -1604,7 +1604,7 @@ private static Attribute NewValidateSetAttribute(AttributeAst ast) if (ast.PositionalArguments.Count == 1 && ast.PositionalArguments[0] is TypeExpressionAst generatorTypeAst) { var generatorType = TypeResolver.ResolveITypeName(generatorTypeAst.TypeName, out Exception exception); - if (generatorType != null) + if (generatorType is not null) { result = new ValidateSetAttribute(generatorType); } @@ -1756,7 +1756,7 @@ internal static Attribute GetAttribute(TypeConstraintAst typeConstraintAst) { Type type = null; var ihct = typeConstraintAst.TypeName as ISupportsTypeCaching; - if (ihct != null) + if (ihct is not null) { type = ihct.CachedType; } @@ -1764,7 +1764,7 @@ internal static Attribute GetAttribute(TypeConstraintAst typeConstraintAst) if (type is null) { type = TypeOps.ResolveTypeName(typeConstraintAst.TypeName, typeConstraintAst.Extent); - if (ihct != null) + if (ihct is not null) { ihct.CachedType = type; } @@ -1835,7 +1835,7 @@ private static RuntimeDefinedParameter GetRuntimeDefinedParameter(ParameterAst p var result = new RuntimeDefinedParameter(parameterAst.Name.VariablePath.UserPath, parameterAst.StaticType, new Collection(attributes)); - if (parameterAst.DefaultValue != null) + if (parameterAst.DefaultValue is not null) { object constantValue; if (IsConstantValueVisitor.IsConstant(parameterAst.DefaultValue, out constantValue)) @@ -1852,7 +1852,7 @@ private static RuntimeDefinedParameter GetRuntimeDefinedParameter(ParameterAst p else { object defaultValue; - if (TryGetDefaultParameterValue(parameterAst.StaticType, out defaultValue) && defaultValue != null) + if (TryGetDefaultParameterValue(parameterAst.StaticType, out defaultValue) && defaultValue is not null) { // Skip setting the value when defaultValue is null because if we do call the setter, // we'll try converting null to the parameter, which we might not want, e.g. if the parameter is [ref]. @@ -1940,7 +1940,7 @@ internal void Compile(CompiledScriptBlockData scriptBlock, bool optimize) _compilingScriptCmdlet = scriptBlock.UsesCmdletBinding; var fileName = ast.Extent.File; - if (fileName != null) + if (fileName is not null) { _debugSymbolDocument = Expression.SymbolDocument(fileName); } @@ -1962,7 +1962,7 @@ internal void Compile(CompiledScriptBlockData scriptBlock, bool optimize) LocalVariablesParameter = Expression.Variable(LocalVariablesTupleType, "locals"); var functionMemberAst = ast as FunctionMemberAst; - if (functionMemberAst != null) + if (functionMemberAst is not null) { CompilingMemberFunction = true; MemberFunctionReturnType = functionMemberAst.GetReturnType(); @@ -1983,7 +1983,7 @@ internal void Compile(CompiledScriptBlockData scriptBlock, bool optimize) else { var generatedMemberFunctionAst = ast as CompilerGeneratedMemberFunctionAst; - if (generatedMemberFunctionAst != null) + if (generatedMemberFunctionAst is not null) { CompilingMemberFunction = true; SpecialMemberFunctionType = generatedMemberFunctionAst.Type; @@ -2092,7 +2092,7 @@ private static object GetExpressionValue( // Can't be exposed to untrusted input - exposing private variable names / etc. could be // information disclosure. var variableAst = expressionAst as VariableExpressionAst; - if (variableAst != null) + if (variableAst is not null) { // We can avoid creating a lambda for the common case of a simple variable expression. return VariableOps.GetVariableValue(variableAst.VariablePath, context, variableAst); @@ -2108,7 +2108,7 @@ private static object GetExpressionValue( SessionStateInternal oldSessionState = context.EngineSessionState; try { - if (sessionStateInternal != null && context.EngineSessionState != sessionStateInternal) + if (sessionStateInternal is not null && context.EngineSessionState != sessionStateInternal) { // If we're running a function from a module, we need to evaluate the initializers in the // module context, not the callers context... @@ -2127,7 +2127,7 @@ private static object GetExpressionValue( _outputPipe = pipe, _localsTuple = MutableTuple.MakeTuple(localsTupleType, DottedLocalsNameIndexMap) }; - if (usingValues != null) + if (usingValues is not null) { var boundParameters = new PSBoundParametersDictionary { ImplicitUsingParameters = usingValues }; functionContext._localsTuple.SetAutomaticVariable(AutomaticVariable.PSBoundParameters, boundParameters, context); @@ -2254,7 +2254,7 @@ private Expression CaptureAstResults( exprs.Add(Expression.Assign(resultList, Expression.New(CachedReflectionInfo.ObjectList_ctor))); exprs.Add(Expression.Assign(s_getCurrentPipe, Expression.New(CachedReflectionInfo.Pipe_ctor, resultList))); exprs.Add(Expression.Call(oldPipe, CachedReflectionInfo.Pipe_SetVariableListForTemporaryPipe, s_getCurrentPipe)); - if (generateRedirectExprs != null) + if (generateRedirectExprs is not null) { // Add merge redirection expressions if delegate is provided. generateRedirectExprs(exprs, finallyExprs); @@ -2322,7 +2322,7 @@ private Expression CaptureStatementResultsHelper( MergeRedirectExprs generateRedirectExprs) { var commandExpressionAst = stmt as CommandExpressionAst; - if (commandExpressionAst != null) + if (commandExpressionAst is not null) { if (commandExpressionAst.Redirections.Count > 0) { @@ -2333,7 +2333,7 @@ private Expression CaptureStatementResultsHelper( } var assignmentStatementAst = stmt as AssignmentStatementAst; - if (assignmentStatementAst != null) + if (assignmentStatementAst is not null) { var expr = Compile(assignmentStatementAst); if (stmt.Parent is StatementBlockAst) @@ -2346,10 +2346,10 @@ private Expression CaptureStatementResultsHelper( var pipelineAst = stmt as PipelineAst; // If it's a pipeline that isn't being backgrounded, try to optimize expression - if (pipelineAst != null && !pipelineAst.Background) + if (pipelineAst is not null && !pipelineAst.Background) { var expr = pipelineAst.GetPureExpression(); - if (expr != null) + if (expr is not null) { return Compile(expr); } @@ -2374,7 +2374,7 @@ private Expression CaptureStatementResults( // We do this after evaluating the condition so that you could do something like: // if ((dir file1,file2 -ea SilentlyContinue) -and $?) { <# files both exist, otherwise $? would be $false if 0 or 1 files existed #> } // - if (context == CaptureAstContext.Condition && AstSearcher.FindFirst(stmt, ast => ast is CommandAst, searchNestedScriptBlocks: false) != null) + if (context == CaptureAstContext.Condition && AstSearcher.FindFirst(stmt, ast => ast is CommandAst, searchNestedScriptBlocks: false) is not null) { var tmp = NewTemp(result.Type, "condTmp"); result = Expression.Block( @@ -2412,26 +2412,26 @@ public object VisitErrorExpression(ErrorExpressionAst errorExpressionAst) public object VisitScriptBlock(ScriptBlockAst scriptBlockAst) { var funcDefn = scriptBlockAst.Parent as FunctionDefinitionAst; - var funcName = (funcDefn != null) ? funcDefn.Name : ""; + var funcName = (funcDefn is not null) ? funcDefn.Name : ""; - var rootForDefiningTypesAndUsings = scriptBlockAst.Find(ast => ast is TypeDefinitionAst || ast is UsingStatementAst, true) != null + var rootForDefiningTypesAndUsings = scriptBlockAst.Find(ast => ast is TypeDefinitionAst || ast is UsingStatementAst, true) is not null ? scriptBlockAst : null; - if (scriptBlockAst.DynamicParamBlock != null) + if (scriptBlockAst.DynamicParamBlock is not null) { _dynamicParamBlockLambda = CompileNamedBlock(scriptBlockAst.DynamicParamBlock, funcName + "", rootForDefiningTypesAndUsings); rootForDefiningTypesAndUsings = null; } // Skip param block - nothing to generate, defaults get generated when generating parameter metadata. - if (scriptBlockAst.BeginBlock != null) + if (scriptBlockAst.BeginBlock is not null) { _beginBlockLambda = CompileNamedBlock(scriptBlockAst.BeginBlock, funcName + "", rootForDefiningTypesAndUsings); rootForDefiningTypesAndUsings = null; } - if (scriptBlockAst.ProcessBlock != null) + if (scriptBlockAst.ProcessBlock is not null) { var processFuncName = funcName; if (!scriptBlockAst.ProcessBlock.Unnamed) @@ -2443,7 +2443,7 @@ public object VisitScriptBlock(ScriptBlockAst scriptBlockAst) rootForDefiningTypesAndUsings = null; } - if (scriptBlockAst.EndBlock != null) + if (scriptBlockAst.EndBlock is not null) { if (!scriptBlockAst.EndBlock.Unnamed) { @@ -2464,7 +2464,7 @@ private Expression> CompileNamedBlock(NamedBlockAst name { // Get extent from the function or scriptblock expression parent, if any. var scriptBlock = (ScriptBlockAst)namedBlockAst.Parent; - if (scriptBlock.Parent != null && scriptBlock.Extent is InternalScriptExtent) + if (scriptBlock.Parent is not null && scriptBlock.Extent is InternalScriptExtent) { // We must have curlies at the start/end. var scriptExtent = (InternalScriptExtent)scriptBlock.Extent; @@ -2485,7 +2485,7 @@ private Tuple, Type> CompileTrap(TrapStatementAst trap) { var compiler = new Compiler(_sequencePoints, _sequencePointIndexMap) { _compilingTrap = true }; string funcName = _currentFunctionName + ""; - if (trap.TrapType != null) + if (trap.TrapType is not null) { funcName += "<" + trap.TrapType.TypeName.Name + ">"; } @@ -2522,7 +2522,7 @@ private Expression> CompileSingleLambda( GenerateFunctionProlog(exprs, temps, entryExtent); - if (rootForDefiningTypesAndUsings != null) + if (rootForDefiningTypesAndUsings is not null) { GenerateTypesAndUsings(rootForDefiningTypesAndUsings, exprs); } @@ -2553,7 +2553,7 @@ private Expression> CompileSingleLambda( // body of regular begin/process/end blocks with a try/catch so a return from the trap returns // to the right place. We can avoid also avoid generating the catch if we know there aren't any traps. if (!_compilingTrap && - ((traps != null && traps.Count > 0) + ((traps is not null && traps.Count > 0) || statements.Any(stmt => AstSearcher.Contains(stmt, ast => ast is TrapStatementAst, searchNestedScriptBlocks: false)))) { body = Expression.Block( @@ -2654,7 +2654,7 @@ internal static void GenerateLoadUsings(IEnumerable usingStat exprs.Add(Expression.Call( CachedReflectionInfo.TypeOps_SetCurrentTypeResolutionState, Expression.Constant(trs), s_executionContextParameter)); - if (typesToAdd != null && typesToAdd.Count > 0) + if (typesToAdd is not null && typesToAdd.Count > 0) { exprs.Add(Expression.Call( CachedReflectionInfo.TypeOps_AddPowerShellTypesToTheScope, @@ -2674,7 +2674,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"); - if (typeAsts[0].Type != null) + if (typeAsts[0].Type is not null) { // We treat Type as a mutable buffer field and wipe it here to start definitions from scratch. @@ -2720,9 +2720,9 @@ private static Dictionary LoadUsingsImpl(IEnumerable< break; case UsingStatementKind.Module: var module = LoadModule(usingStmt.ModuleInfo); - if (module != null) + if (module is not null) { - if (module.ImplementingAssembly != null) + if (module.ImplementingAssembly is not null) { asms.Add(module.ImplementingAssembly); } @@ -2878,7 +2878,7 @@ private void GenerateFunctionProlog(List exprs, List exprs, List exprs, IScriptExtent exitExtent) { - if (exitExtent != null) + if (exitExtent is not null) { exprs.Add(UpdatePosition(new SequencePointAst(exitExtent))); } @@ -3021,7 +3021,7 @@ private void CompileStatementListWithTraps( Expression handlerInScope; ParameterExpression oldActiveHandler; ParameterExpression trapHandlersPushed; - if (traps != null) + if (traps is not null) { // If the statement block has any traps, we'll generate code like: // try { @@ -3060,7 +3060,7 @@ private void CompileStatementListWithTraps( for (int index = 0; index < traps.Count; index++) { var trap = traps[index]; - trapTypes.Add(trap.TrapType != null + trapTypes.Add(trap.TrapType is not null ? CompileTypeName(trap.TrapType.TypeName, trap.TrapType.Extent) : ExpressionCache.CatchAllType); var tuple = CompileTrap(trap); @@ -3208,7 +3208,7 @@ private void CompileStatementListWithTraps( { var parameterExprs = new List(); var finallyBlockExprs = new List(); - if (oldActiveHandler != null) + if (oldActiveHandler is not null) { parameterExprs.Add(oldActiveHandler); finallyBlockExprs.Add(Expression.Assign(handlerInScope, oldActiveHandler)); @@ -3222,7 +3222,7 @@ private void CompileStatementListWithTraps( Expression.Block(parameterExprs, Expression.TryFinally(Expression.Block(exprs), Expression.Block(finallyBlockExprs)))); } - if (traps != null) + if (traps is not null) { _trapNestingCount -= 1; } @@ -3344,7 +3344,7 @@ private bool ShouldSetExecutionStatusToSuccess(ExpressionAst expressionAst) case 1: // Single expressions with a trap are handled as statements // For example: @(trap { continue } "Value") - if (arrayExpressionAst.SubExpression.Traps != null) + if (arrayExpressionAst.SubExpression.Traps is not null) { return false; } @@ -3435,7 +3435,7 @@ public object VisitIfStatement(IfStatementAst ifStmtAst) } Expression elseExpr = null; - if (ifStmtAst.ElseClause != null) + if (ifStmtAst.ElseClause is not null) { elseExpr = Compile(ifStmtAst.ElseClause); } @@ -3445,7 +3445,7 @@ public object VisitIfStatement(IfStatementAst ifStmtAst) { var cond = exprs[i].Item1; var body = exprs[i].Item2; - if (elseExpr != null) + if (elseExpr is not null) { result = elseExpr = Expression.IfThenElse(cond, body, elseExpr); } @@ -3475,7 +3475,7 @@ private Expression CompileAssignment( { var arrayLHS = assignmentStatementAst.Left as ArrayLiteralAst; var parenExpressionAst = assignmentStatementAst.Left as ParenExpressionAst; - if (parenExpressionAst != null) + if (parenExpressionAst is not null) { arrayLHS = parenExpressionAst.Pipeline.GetPureExpression() as ArrayLiteralAst; } @@ -3486,10 +3486,10 @@ private Expression CompileAssignment( // We should not preserve the partial output if exception is thrown when evaluating right-hand-side expression. Expression rightExpr = CaptureStatementResults( assignmentStatementAst.Right, - arrayLHS != null ? CaptureAstContext.Enumerable : CaptureAstContext.AssignmentWithoutResultPreservation, + arrayLHS is not null ? CaptureAstContext.Enumerable : CaptureAstContext.AssignmentWithoutResultPreservation, generateRedirectExprs); - if (arrayLHS != null) + if (arrayLHS is not null) { rightExpr = DynamicExpression.Dynamic(PSArrayAssignmentRHSBinder.Get(arrayLHS.Elements.Count), typeof(IList), rightExpr); } @@ -3622,7 +3622,7 @@ public object VisitPipelineChain(PipelineChainAst pipelineChainAst) currentChain = currentChain.Parent as PipelineChainAst; } - while (currentChain != null); + while (currentChain is not null); // Add empty expression to make the block value void tryBodyExprs.Add(ExpressionCache.Empty); @@ -3702,7 +3702,7 @@ public object VisitPipeline(PipelineAst pipelineAst) var pipeElements = pipelineAst.PipelineElements; var firstCommandExpr = pipeElements[0] as CommandExpressionAst; - if (firstCommandExpr != null && pipeElements.Count == 1) + if (firstCommandExpr is not null && pipeElements.Count == 1) { if (firstCommandExpr.Redirections.Count > 0) { @@ -3718,7 +3718,7 @@ public object VisitPipeline(PipelineAst pipelineAst) Expression input; int i, commandsInPipe; - if (firstCommandExpr != null) + if (firstCommandExpr is not null) { if (firstCommandExpr.Redirections.Count > 0) { @@ -3775,7 +3775,7 @@ public object VisitPipeline(PipelineAst pipelineAst) typeof(CommandRedirection[]), commandRedirections.Select(r => (r as Expression) ?? Expression.Constant(r, typeof(CommandRedirection[])))); } - else if (commandRedirections.Any(r => r != null)) + else if (commandRedirections.Any(r => r is not null)) { // There were redirections, but all were compile time constant, so build the array at compile time. redirectionExpr = @@ -3787,7 +3787,7 @@ public object VisitPipeline(PipelineAst pipelineAst) redirectionExpr = ExpressionCache.NullCommandRedirections; } - if (firstCommandExpr != null) + if (firstCommandExpr is not null) { var inputTemp = Expression.Variable(input.Type); temps.Add(inputTemp); @@ -3798,7 +3798,7 @@ public object VisitPipeline(PipelineAst pipelineAst) Expression invokePipe = Expression.Call( CachedReflectionInfo.PipelineOps_InvokePipeline, input.Cast(typeof(object)), - firstCommandExpr != null ? ExpressionCache.FalseConstant : ExpressionCache.TrueConstant, + firstCommandExpr is not null ? ExpressionCache.FalseConstant : ExpressionCache.TrueConstant, Expression.NewArrayInit(typeof(CommandParameterInternal[]), pipelineExprs), Expression.Constant(pipeElementAsts), redirectionExpr, @@ -3876,7 +3876,7 @@ private Expression GetRedirectedExpression(CommandExpressionAst commandExpr, boo ParameterExpression resultList = null; ParameterExpression oldPipe = null; var subExpr = commandExpr.Expression as SubExpressionAst; - if (subExpr != null && captureForInput) + if (subExpr is not null && captureForInput) { oldPipe = NewTemp(typeof(Pipe), "oldPipe"); resultList = NewTemp(typeof(List), "resultList"); @@ -3952,12 +3952,12 @@ private Expression GetRedirectedExpression(CommandExpressionAst commandExpr, boo Expression result = null; var parenExpr = commandExpr.Expression as ParenExpressionAst; - if (parenExpr != null) + if (parenExpr is not null) { // Special processing for paren expressions that capture output. // Insert any merge redirect expressions during paren expression compilation. var assignmentStatementAst = parenExpr.Pipeline as AssignmentStatementAst; - if (assignmentStatementAst != null) + if (assignmentStatementAst is not null) { result = CompileAssignment( assignmentStatementAst, @@ -3974,13 +3974,13 @@ private Expression GetRedirectedExpression(CommandExpressionAst commandExpr, boo (mergeExprs, mergeFinallyExprs) => AddMergeRedirectionExpressions(commandExpr.Redirections, temps, mergeExprs, mergeFinallyExprs)); } } - else if (subExpr != null) + else if (subExpr is not null) { // Include any redirection merging. AddMergeRedirectionExpressions(commandExpr.Redirections, temps, exprs, finallyExprs); exprs.Add(Compile(subExpr.SubExpression)); - if (resultList != null) + if (resultList is not null) { // If there is no resultList, we wrote our results of the subexpression directly to the pipe // instead of being collected to be written here. @@ -3995,7 +3995,7 @@ private Expression GetRedirectedExpression(CommandExpressionAst commandExpr, boo result = Compile(commandExpr.Expression); } - if (result != null) + if (result is not null) { if (!outputRedirected && captureForInput) { @@ -4013,7 +4013,7 @@ private Expression GetRedirectedExpression(CommandExpressionAst commandExpr, boo } } - if (extraFileRedirectExprs != null) + if (extraFileRedirectExprs is not null) { // Now that the redirection is done, we need to call 'DoComplete' on the file redirection pipeline processors. // Exception may be thrown when running 'DoComplete', but we don't want the exception to affect the cleanup @@ -4032,7 +4032,7 @@ private Expression GetRedirectedExpression(CommandExpressionAst commandExpr, boo exprs.Add(wrapExpr); } - if (oldPipe != null) + if (oldPipe is not null) { // If a temporary pipe was created at the beginning, we should restore the original pipe in the // very end of the finally block. Otherwise, s_getCurrentPipe may be messed up by the following @@ -4098,7 +4098,7 @@ public object VisitFileRedirection(FileRedirectionAst fileRedirectionAst) { Expression fileNameExpr; var strConst = fileRedirectionAst.Location as StringConstantExpressionAst; - if (strConst != null) + if (strConst is not null) { // When the filename is a constant, we still must generate a new FileRedirection // at runtime because we can't keep a cached object in the closure because the object @@ -4140,13 +4140,13 @@ public object VisitCommand(CommandAst commandAst) bool splatted = false; UsingExpressionAst usingExpression = element as UsingExpressionAst; - if (usingExpression != null) + if (usingExpression is not null) { splatTest = usingExpression.SubExpression; } VariableExpressionAst variableExpression = splatTest as VariableExpressionAst; - if (variableExpression != null) + if (variableExpression is not null) { splatted = variableExpression.Splatted; } @@ -4187,7 +4187,7 @@ public object VisitCommand(CommandAst commandAst) private Expression GetCommandArgumentExpression(CommandElementAst element) { var constElement = element as ConstantExpressionAst; - if (constElement != null + if (constElement is not null && (LanguagePrimitives.IsNumeric(LanguagePrimitives.GetTypeCode(constElement.StaticType)) || constElement.StaticType == typeof(System.Numerics.BigInteger))) { @@ -4218,7 +4218,7 @@ public object VisitCommandExpression(CommandExpressionAst commandExpressionAst) var child = commandExpressionAst.Expression; var expr = Compile(child); var unary = child as UnaryExpressionAst; - if ((unary != null && unary.TokenKind.HasTrait(TokenFlags.PrefixOrPostfixOperator)) || expr.Type == typeof(void)) + if ((unary is not null && unary.TokenKind.HasTrait(TokenFlags.PrefixOrPostfixOperator)) || expr.Type == typeof(void)) { return expr; } @@ -4230,7 +4230,7 @@ public object VisitCommandParameter(CommandParameterAst commandParameterAst) { var arg = commandParameterAst.Argument; var errorPos = commandParameterAst.ErrorPosition; - if (arg != null) + if (arg is not null) { bool spaceAfterParameter = errorPos.EndLineNumber != arg.Extent.StartLineNumber || errorPos.EndColumnNumber != arg.Extent.StartColumnNumber; @@ -4263,7 +4263,7 @@ internal static Expression ThrowRuntimeError(string errorID, string resourceStri internal static Expression ThrowRuntimeError(Type exceptionType, string errorID, string resourceString, Type throwResultType, params Expression[] exceptionArgs) { - var exceptionArgArray = exceptionArgs != null + var exceptionArgArray = exceptionArgs is not null ? Expression.NewArrayInit(typeof(object), exceptionArgs.Select(e => e.Cast(typeof(object)))) : ExpressionCache.NullConstant; Expression[] argExprs = new Expression[] @@ -4297,7 +4297,7 @@ internal static Expression ThrowRuntimeErrorWithInnerException( Type throwResultType, params Expression[] exceptionArgs) { - var exceptionArgArray = exceptionArgs != null + var exceptionArgArray = exceptionArgs is not null ? Expression.NewArrayInit(typeof(object), exceptionArgs) : ExpressionCache.NullConstant; Expression[] argExprs = new Expression[] @@ -4341,12 +4341,12 @@ internal static Expression CreateThrow(Type resultType, Type exception, Type[] e internal static Expression CreateThrow(Type resultType, Type exception, params object[] exceptionArgs) { Type[] argTypes = Type.EmptyTypes; - if (exceptionArgs != null) + if (exceptionArgs is not null) { argTypes = new Type[exceptionArgs.Length]; for (int i = 0; i < exceptionArgs.Length; i++) { - Diagnostics.Assert(exceptionArgs[i] != null, "Can't deduce argument type from null"); + Diagnostics.Assert(exceptionArgs[i] is not null, "Can't deduce argument type from null"); argTypes[i] = exceptionArgs[i].GetType(); } } @@ -4359,7 +4359,7 @@ public object VisitSwitchStatement(SwitchStatementAst switchStatementAst) var avs = new AutomaticVarSaver(this, SpecialVariables.UnderbarVarPath, (int)AutomaticVariable.Underbar); var temps = new List(); ParameterExpression skipDefault = null; - if (switchStatementAst.Default != null) + if (switchStatementAst.Default is not null) { skipDefault = NewTemp(typeof(bool), "skipDefault"); temps.Add(skipDefault); @@ -4377,7 +4377,7 @@ public object VisitSwitchStatement(SwitchStatementAst switchStatementAst) // { // sr = new StreamReader(path); // string line; - // while ((line = sr.ReadLine()) != null) + // while ((line = sr.ReadLine()) is not null) // { // $_ = line // test clauses @@ -4393,7 +4393,7 @@ public object VisitSwitchStatement(SwitchStatementAst switchStatementAst) // } // finally // { - // if (sr != null) sr.Dispose(); + // if (sr is not null) sr.Dispose(); // } var exprs = new List(); @@ -4495,7 +4495,7 @@ private Action, Expression> GetSwitchBodyGenerator(SwitchStatem var clauseEvalBinder = PSSwitchClauseEvalBinder.Get(switchStatementAst.Flags); exprs.Add(avs.SetNewValue(newValue)); - if (skipDefault != null) + if (skipDefault is not null) { exprs.Add(Expression.Assign(skipDefault, ExpressionCache.Constant(false))); } @@ -4522,7 +4522,7 @@ private Action, Expression> GetSwitchBodyGenerator(SwitchStatem /*args=*/ ExpressionCache.NullObjectArray); test = DynamicExpression.Dynamic(PSConvertBinder.Get(typeof(bool)), typeof(bool), call); } - else if (constValue != null) + else if (constValue is not null) { SwitchFlags flags = switchStatementAst.Flags; Expression conditionExpr = constValue is Regex || constValue is WildcardPattern @@ -4573,7 +4573,7 @@ private Action, Expression> GetSwitchBodyGenerator(SwitchStatem } exprs.Add(UpdatePosition(clause.Item1)); - if (skipDefault != null) + if (skipDefault is not null) { exprs.Add(Expression.IfThen( test, @@ -4586,7 +4586,7 @@ private Action, Expression> GetSwitchBodyGenerator(SwitchStatem } } - if (skipDefault != null) + if (skipDefault is not null) { exprs.Add(Expression.IfThen(Expression.Not(skipDefault), Compile(switchStatementAst.Default))); } @@ -4656,7 +4656,7 @@ public object VisitDataStatement(DataStatementAst dataStatementAst) // If we'll be assigning directly, we need to capture the value, otherwise just write to the current output pipe. // We should not preserve the partial output if exception is thrown when evaluating the body expr. - var dataExpr = dataStatementAst.Variable != null + var dataExpr = dataStatementAst.Variable is not null ? CaptureAstResults(dataStatementAst.Body, CaptureAstContext.AssignmentWithoutResultPreservation).Cast(typeof(object)) : Compile(dataStatementAst.Body); exprs.Add(dataExpr); @@ -4665,7 +4665,7 @@ public object VisitDataStatement(DataStatementAst dataStatementAst) new[] { oldLanguageMode }, Expression.TryFinally(Expression.Block(exprs), Expression.Assign(languageModePropertyExpr, oldLanguageMode))); - if (dataStatementAst.Variable != null) + if (dataStatementAst.Variable is not null) { return dataStatementAst.TupleIndex < 0 ? CallSetVariable(Expression.Constant(new VariablePath("local:" + dataStatementAst.Variable)), block) @@ -4755,7 +4755,7 @@ private Expression GenerateWhileLoop(string loopLabel, var breakLabel = Expression.Label(!string.IsNullOrEmpty(loopLabel) ? loopLabel + "Break" : "break"); var enterLoop = new EnterLoopExpression(); - var loopTop = (continueAst != null) + var loopTop = (continueAst is not null) ? Expression.Label(!string.IsNullOrEmpty(loopLabel) ? loopLabel + "LoopTop" : "looptop") : continueLabel; @@ -4778,12 +4778,12 @@ private Expression GenerateWhileLoop(string loopLabel, Expression loopBody = Expression.TryCatch(Expression.Block(loopBodyExprs), GenerateLoopBreakContinueCatchBlocks(loopLabel, breakLabel, continueLabel)); - if (continueAst != null) + if (continueAst is not null) { var x = new List(); x.Add(loopBody); x.Add(Expression.Label(continueLabel)); - if (continueAst.GetPureExpression() != null) + if (continueAst.GetPureExpression() is not null) { // Assignments generate the code to update the position automatically, // but pre/post increments don't, so we add it here explicitly. @@ -4796,7 +4796,7 @@ private Expression GenerateWhileLoop(string loopLabel, loopBody = Expression.Block(x); } - if (generateCondition != null) + if (generateCondition is not null) { exprs.Add(Expression.IfThen(generateCondition().Convert(typeof(bool)), loopBody)); } @@ -5036,10 +5036,10 @@ public object VisitForEachStatement(ForEachStatementAst forEachStatementAst) private Expression GetRangeEnumerator(ExpressionAst condExpr) { - if (condExpr != null) + if (condExpr is not null) { var binaryExpr = condExpr as BinaryExpressionAst; - if (binaryExpr != null && binaryExpr.Operator == TokenKind.DotDot) + if (binaryExpr is not null && binaryExpr.Operator == TokenKind.DotDot) { Expression lhs = Compile(binaryExpr.Left); Expression rhs = Compile(binaryExpr.Right); @@ -5056,7 +5056,7 @@ private Expression GetRangeEnumerator(ExpressionAst condExpr) private Expression UpdatePositionForInitializerOrCondition(PipelineBaseAst pipelineBaseAst, Expression initializerOrCondition) { - if (pipelineBaseAst is PipelineAst pipelineAst && !pipelineAst.Background && pipelineAst.GetPureExpression() != null) + if (pipelineBaseAst is PipelineAst pipelineAst && !pipelineAst.Background && pipelineAst.GetPureExpression() is not null) { // If the initializer or condition is a pure expression (CommandExpressionAst without redirection), // then we need to add a sequence point. If it's an AssignmentStatementAst, we don't need to add @@ -5082,14 +5082,14 @@ public object VisitForStatement(ForStatementAst forStatementAst) // We should not preserve the partial output if exception is thrown when evaluating the initializer. Expression init = null; PipelineBaseAst initializer = forStatementAst.Initializer; - if (initializer != null) + if (initializer is not null) { init = CaptureStatementResults(initializer, CaptureAstContext.AssignmentWithoutResultPreservation); init = UpdatePositionForInitializerOrCondition(initializer, init); } PipelineBaseAst condition = forStatementAst.Condition; - var generateCondition = condition != null + var generateCondition = condition is not null ? () => UpdatePositionForInitializerOrCondition(condition, CaptureStatementResults(condition, CaptureAstContext.Condition)) : (Func)null; @@ -5099,7 +5099,7 @@ public object VisitForStatement(ForStatementAst forStatementAst) (loopBody, breakTarget, continueTarget) => loopBody.Add(Compile(forStatementAst.Body)), forStatementAst.Iterator); - if (init != null) + if (init is not null) { return Expression.Block(init, loop); } @@ -5157,7 +5157,7 @@ internal AutomaticVarSaver(Compiler compiler, VariablePath autoVarPath, int auto internal IEnumerable GetTemps() { - Diagnostics.Assert(_oldValue != null, "caller to only call GetTemps after calling SaveAutomaticVar"); + Diagnostics.Assert(_oldValue is not null, "caller to only call GetTemps after calling SaveAutomaticVar"); yield return _oldValue; } @@ -5398,7 +5398,7 @@ public object VisitTryStatement(TryStatementAst tryStatementAst) catches.Add(Expression.Catch(exception, Expression.Block(avs.GetTemps().Append(oldexception).ToArray(), tf))); } - if (tryStatementAst.Finally != null) + if (tryStatementAst.Finally is not null) { // Generate: // oldIsStopping = ExceptionHandlingOps.SuspendStoppingPipeline(executionContext); @@ -5464,13 +5464,13 @@ private Expression GenerateBreakOrContinue( { LabelTarget labelTarget = null; Expression labelExpr = null; - if (label != null) + if (label is not null) { labelExpr = Compile(label); if (_loopTargets.Count > 0) { var labelStrAst = label as StringConstantExpressionAst; - if (labelStrAst != null) + if (labelStrAst is not null) { labelTarget = (from t in _loopTargets where t.Label.Equals(labelStrAst.Value, StringComparison.OrdinalIgnoreCase) @@ -5484,7 +5484,7 @@ where t.Label.Equals(labelStrAst.Value, StringComparison.OrdinalIgnoreCase) } Expression result; - if (labelTarget != null) + if (labelTarget is not null) { result = exprGenerator(labelTarget); } @@ -5534,7 +5534,7 @@ public object VisitReturnStatement(ReturnStatementAst returnStatementAst) : ExpressionCache.Empty); } - if (returnStatementAst.Pipeline != null) + if (returnStatementAst.Pipeline is not null) { var pipe = returnStatementAst.Pipeline; var assignmentStatementAst = pipe as AssignmentStatementAst; @@ -5561,7 +5561,7 @@ public object VisitReturnStatement(ReturnStatementAst returnStatementAst) returnExpr); } - returnValue = assignmentStatementAst != null + returnValue = assignmentStatementAst is not null ? CallAddPipe(CompileAssignment(assignmentStatementAst), s_getCurrentPipe) : Compile(pipe); @@ -5574,7 +5574,7 @@ public object VisitReturnStatement(ReturnStatementAst returnStatementAst) public object VisitExitStatement(ExitStatementAst exitStatementAst) { // We should not preserve the partial output if exception is thrown when evaluating exitStmt.pipeline. - Expression exitCode = exitStatementAst.Pipeline != null + Expression exitCode = exitStatementAst.Pipeline is not null ? CaptureStatementResults(exitStatementAst.Pipeline, CaptureAstContext.AssignmentWithoutResultPreservation) : ExpressionCache.Constant(0); @@ -6057,7 +6057,7 @@ public object VisitConvertExpression(ConvertExpressionAst convertExpressionAst) var typeName = convertExpressionAst.Type.TypeName; var hashTableAst = convertExpressionAst.Child as HashtableAst; Expression childExpr = null; - if (hashTableAst != null) + if (hashTableAst is not null) { var temp = NewTemp(typeof(OrderedDictionary), "orderedDictionary"); if (typeName.FullName.Equals(LanguagePrimitives.OrderedAttribute, StringComparison.OrdinalIgnoreCase)) @@ -6082,7 +6082,7 @@ public object VisitConvertExpression(ConvertExpressionAst convertExpressionAst) if (convertExpressionAst.IsRef()) { var varExpr = convertExpressionAst.Child as VariableExpressionAst; - if (varExpr != null && varExpr.VariablePath.IsVariable && !varExpr.IsConstantVariable()) + if (varExpr is not null && varExpr.VariablePath.IsVariable && !varExpr.IsConstantVariable()) { // We'll wrap the variable in a PSReference, but not the constant variables ($true, $false, $null) because those // can't be changed. @@ -6093,7 +6093,7 @@ public object VisitConvertExpression(ConvertExpressionAst convertExpressionAst) CachedReflectionInfo.VariableOps_GetVariableAsRef, Expression.Constant(varExpr.VariablePath), s_executionContextParameter, - varType != null && varType != typeof(object) + varType is not null && varType != typeof(object) ? Expression.Constant(varType, typeof(Type)) : ExpressionCache.NullType); } @@ -6214,7 +6214,7 @@ internal Expression CompileTypeName(ITypeName typeName, IScriptExtent errorPos) type = null; } - if (type != null) + if (type is not null) { return Expression.Constant(type, typeof(Type)); } @@ -6238,10 +6238,10 @@ public object VisitMemberExpression(MemberExpressionAst memberExpressionAst) if (memberExpressionAst.Static && (memberExpressionAst.Expression is TypeExpressionAst)) { var type = ((TypeExpressionAst)memberExpressionAst.Expression).TypeName.GetReflectionType(); - if (type != null && !type.IsGenericTypeDefinition) + if (type is not null && !type.IsGenericTypeDefinition) { var member = memberExpressionAst.Member as StringConstantExpressionAst; - if (member != null) + if (member is not null) { // We skip Methods because the adapter wraps them in a PSMethod and it's not a common scenario. var memberInfo = type.GetMember( @@ -6251,7 +6251,7 @@ public object VisitMemberExpression(MemberExpressionAst memberExpressionAst) if (memberInfo.Length == 1) { var propertyInfo = memberInfo[0] as PropertyInfo; - if (propertyInfo != null) + if (propertyInfo is not null) { if (propertyInfo.PropertyType.IsByRefLike) { @@ -6290,7 +6290,7 @@ public object VisitMemberExpression(MemberExpressionAst memberExpressionAst) // If the ?. operator is used for null conditional check, add the null conditional expression. var memberNameAst = memberExpressionAst.Member as StringConstantExpressionAst; - Expression memberAccessExpr = memberNameAst != null + Expression memberAccessExpr = memberNameAst is not null ? DynamicExpression.Dynamic(PSGetMemberBinder.Get(memberNameAst.Value, _memberFunctionType, memberExpressionAst.Static), typeof(object), target) : DynamicExpression.Dynamic(PSGetDynamicMemberBinder.Get(_memberFunctionType, memberExpressionAst.Static), typeof(object), target, Compile(memberExpressionAst.Member)); @@ -6303,7 +6303,7 @@ internal static PSMethodInvocationConstraints GetInvokeMemberConstraints(InvokeM var targetTypeConstraint = GetTypeConstraintForMethodResolution(invokeMemberExpressionAst.Expression); return CombineTypeConstraintForMethodResolution( targetTypeConstraint, - arguments != null ? arguments.Select(Compiler.GetTypeConstraintForMethodResolution).ToArray() : null); + arguments is not null ? arguments.Select(Compiler.GetTypeConstraintForMethodResolution).ToArray() : null); } internal static PSMethodInvocationConstraints GetInvokeMemberConstraints(BaseCtorInvokeMemberExpressionAst invokeMemberExpressionAst) @@ -6311,7 +6311,7 @@ internal static PSMethodInvocationConstraints GetInvokeMemberConstraints(BaseCto Type targetTypeConstraint = null; var arguments = invokeMemberExpressionAst.Arguments; TypeDefinitionAst typeDefinitionAst = Ast.GetAncestorTypeDefinitionAst(invokeMemberExpressionAst); - if (typeDefinitionAst != null) + if (typeDefinitionAst is not null) { targetTypeConstraint = (typeDefinitionAst as TypeDefinitionAst).Type.BaseType; } @@ -6322,7 +6322,7 @@ internal static PSMethodInvocationConstraints GetInvokeMemberConstraints(BaseCto return CombineTypeConstraintForMethodResolution( targetTypeConstraint, - arguments != null ? arguments.Select(Compiler.GetTypeConstraintForMethodResolution).ToArray() : null); + arguments is not null ? arguments.Select(Compiler.GetTypeConstraintForMethodResolution).ToArray() : null); } internal Expression InvokeMember( @@ -6335,7 +6335,7 @@ internal Expression InvokeMember( bool nullConditional = false) { var callInfo = new CallInfo(args.Count()); - var classScope = _memberFunctionType != null ? _memberFunctionType.Type : null; + var classScope = _memberFunctionType is not null ? _memberFunctionType.Type : null; var binder = name.Equals("new", StringComparison.OrdinalIgnoreCase) && @static ? (CallSiteBinder)PSCreateInstanceBinder.Get(callInfo, constraints, publicTypeOnly: true) : PSInvokeMemberBinder.Get(name, callInfo, @static, propertySet, constraints, classScope); @@ -6375,7 +6375,7 @@ public object VisitInvokeMemberExpression(InvokeMemberExpressionAst invokeMember var args = CompileInvocationArguments(invokeMemberExpressionAst.Arguments); var memberNameAst = invokeMemberExpressionAst.Member as StringConstantExpressionAst; - if (memberNameAst != null) + if (memberNameAst is not null) { return InvokeMember( memberNameAst.Value, @@ -6402,10 +6402,10 @@ public object VisitArrayExpression(ArrayExpressionAst arrayExpressionAst) if (subExpr.Statements.Count == 1) { var pipelineBase = subExpr.Statements[0] as PipelineBaseAst; - if (pipelineBase != null) + if (pipelineBase is not null) { pureExprAst = pipelineBase.GetPureExpression(); - if (pureExprAst != null) + if (pureExprAst is not null) { values = Compile(pureExprAst); } @@ -6504,7 +6504,7 @@ public object VisitParenExpression(ParenExpressionAst parenExpressionAst) var pipe = parenExpressionAst.Pipeline; var assignmentStatementAst = pipe as AssignmentStatementAst; - if (assignmentStatementAst != null) + if (assignmentStatementAst is not null) { return CompileAssignment(assignmentStatementAst); } @@ -6548,7 +6548,7 @@ public object VisitIndexExpression(IndexExpressionAst indexExpressionAst) // In the former case, the user is requesting an array slice. In the latter case, they index expression is likely // an array (dynamically determined) and they don't want an array slice, they want to use the array as the index // expression. - Expression indexingExpr = arrayLiteral != null && arrayLiteral.Elements.Count > 1 + Expression indexingExpr = arrayLiteral is not null && arrayLiteral.Elements.Count > 1 ? DynamicExpression.Dynamic( PSGetIndexBinder.Get(arrayLiteral.Elements.Count, constraints), typeof(object), @@ -6609,7 +6609,7 @@ public Expression GetValue(Compiler compiler, List exprs, List exprs, List GetArgumentExprs(Compiler compiler) { - if (_argExprTemps != null) + if (_argExprTemps is not null) { return _argExprTemps; } @@ -6691,7 +6691,7 @@ public Expression GetValue(Compiler compiler, List exprs, List exprs, List(); - if (_debugSymbolDocument != null) + if (_debugSymbolDocument is not null) { exprs.Add(Expression.DebugInfo(_debugSymbolDocument, _extent.StartLineNumber, _extent.StartColumnNumber, _extent.EndLineNumber, _extent.EndColumnNumber)); } diff --git a/src/System.Management.Automation/engine/parser/ConstantValues.cs b/src/System.Management.Automation/engine/parser/ConstantValues.cs index 483e84221b5..8c6b030afce 100644 --- a/src/System.Management.Automation/engine/parser/ConstantValues.cs +++ b/src/System.Management.Automation/engine/parser/ConstantValues.cs @@ -24,7 +24,7 @@ public static bool IsConstant(Ast ast, out object constantValue, bool forAttribu if ((bool)ast.Accept(new IsConstantValueVisitor { CheckingAttributeArgument = forAttribute, CheckingRequiresArgument = forRequires })) { Ast parent = ast.Parent; - while (parent != null) + while (parent is not null) { if (parent is DataStatementAst) { @@ -146,16 +146,16 @@ public static bool IsConstant(Ast ast, out object constantValue, bool forAttribu public object VisitStatementBlock(StatementBlockAst statementBlockAst) { - if (statementBlockAst.Traps != null) return false; + if (statementBlockAst.Traps is not null) return false; if (statementBlockAst.Statements.Count > 1) return false; var pipeline = statementBlockAst.Statements.FirstOrDefault(); - return pipeline != null && (bool)pipeline.Accept(this); + return pipeline is not null && (bool)pipeline.Accept(this); } public object VisitPipeline(PipelineAst pipelineAst) { var expr = pipelineAst.GetPureExpression(); - return expr != null && (bool)expr.Accept(this); + return expr is not null && (bool)expr.Accept(this); } private static bool IsNullDivisor(ExpressionAst operand) @@ -256,7 +256,7 @@ public object VisitTypeExpression(TypeExpressionAst typeExpressionAst) // until the script/function is first run, so it's OK if a type expression // as an attribute argument cannot be resolved yet. return CheckingAttributeArgument || - typeExpressionAst.TypeName.GetReflectionType() != null; + typeExpressionAst.TypeName.GetReflectionType() is not null; } public object VisitMemberExpression(MemberExpressionAst memberExpressionAst) diff --git a/src/System.Management.Automation/engine/parser/DebugViewWriter.cs b/src/System.Management.Automation/engine/parser/DebugViewWriter.cs index 495df9c12e6..acb5754c39e 100644 --- a/src/System.Management.Automation/engine/parser/DebugViewWriter.cs +++ b/src/System.Management.Automation/engine/parser/DebugViewWriter.cs @@ -131,15 +131,15 @@ private int GetLabelTargetId(LabelTarget target) { /// Write out the given AST. /// internal static void WriteTo(Expression node, TextWriter writer) { - Debug.Assert(node != null); - Debug.Assert(writer != null); + Debug.Assert(node is not null); + Debug.Assert(writer is not null); new DebugViewWriter(writer).WriteTo(node); } private void WriteTo(Expression node) { var lambda = node as LambdaExpression; - if (lambda != null) { + if (lambda is not null) { WriteLambda(lambda); } else { Visit(node); @@ -150,7 +150,7 @@ private void WriteTo(Expression node) { // Output all lambda expression definitions. // in the order of their appearances in the tree. // - while (_lambdas != null && _lambdas.Count > 0) { + while (_lambdas is not null && _lambdas.Count > 0) { WriteLine(); WriteLine(); WriteLambda(_lambdas.Dequeue()); @@ -239,29 +239,29 @@ private static string FormatBinder(CallSiteBinder binder) { UnaryOperationBinder unary; BinaryOperationBinder binary; - if ((convert = binder as ConvertBinder) != null) { + if ((convert = binder as ConvertBinder) is not null) { return "Convert " + convert.Type.ToString(); - } else if ((getMember = binder as GetMemberBinder) != null) { + } else if ((getMember = binder as GetMemberBinder) is not null) { return "GetMember " + getMember.Name; - } else if ((setMember = binder as SetMemberBinder) != null) { + } else if ((setMember = binder as SetMemberBinder) is not null) { return "SetMember " + setMember.Name; - } else if ((deleteMember = binder as DeleteMemberBinder) != null) { + } else if ((deleteMember = binder as DeleteMemberBinder) is not null) { return "DeleteMember " + deleteMember.Name; - } else if ((getIndex = binder as GetIndexBinder) != null) { + } else if ((getIndex = binder as GetIndexBinder) is not null) { return "GetIndex"; - } else if ((setIndex = binder as SetIndexBinder) != null) { + } else if ((setIndex = binder as SetIndexBinder) is not null) { return "SetIndex"; - } else if ((deleteIndex = binder as DeleteIndexBinder) != null) { + } else if ((deleteIndex = binder as DeleteIndexBinder) is not null) { return "DeleteIndex"; - } else if ((call = binder as InvokeMemberBinder) != null) { + } else if ((call = binder as InvokeMemberBinder) is not null) { return "Call " + call.Name; - } else if ((invoke = binder as InvokeBinder) != null) { + } else if ((invoke = binder as InvokeBinder) is not null) { return "Invoke"; - } else if ((create = binder as CreateInstanceBinder) != null) { + } else if ((create = binder as CreateInstanceBinder) is not null) { return "Create"; - } else if ((unary = binder as UnaryOperationBinder) != null) { + } else if ((unary = binder as UnaryOperationBinder) is not null) { return "UnaryOperation " + unary.Operation; - } else if ((binary = binder as BinaryOperationBinder) != null) { + } else if ((binary = binder as BinaryOperationBinder) is not null) { return "BinaryOperation " + binary.Operation; } else { return binder.ToString(); @@ -292,7 +292,7 @@ private void VisitDeclarations(IList expressions) { private void VisitExpressions(char open, char separator, IList expressions, Action visit) { Out(open.ToString()); - if (expressions != null) { + if (expressions is not null) { Indent(); bool isFirst = true; foreach (T e in expressions) { @@ -469,7 +469,7 @@ protected override Expression VisitLambda(Expression node) { private static bool IsSimpleExpression(Expression node) { var binary = node as BinaryExpression; - if (binary != null) { + if (binary is not null) { return !(binary.Left is BinaryExpression || binary.Right is BinaryExpression); } @@ -520,7 +520,7 @@ protected override Expression VisitConstant(ConstantExpression node) { Out(value.ToString()); } else { string suffix = GetConstantValueSuffix(node.Type); - if (suffix != null) { + if (suffix is not null) { Out(value.ToString()); Out(suffix); } else { @@ -571,7 +571,7 @@ protected override Expression VisitRuntimeVariables(RuntimeVariablesExpression n // Prints ".instanceField" or "declaringType.staticField" private void OutMember(Expression node, Expression instance, MemberInfo member) { - if (instance != null) { + if (instance is not null) { ParenthesizedVisit(node, instance); Out("." + member.Name); } else { @@ -594,7 +594,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); + Debug.Assert(parent is not null); if (child is null) { return false; } @@ -646,7 +646,7 @@ private static bool NeedsParentheses(Expression parent, Expression child) { case ExpressionType.Divide: case ExpressionType.Modulo: BinaryExpression binary = parent as BinaryExpression; - Debug.Assert(binary != null); + Debug.Assert(binary is not null); // Need to have parenthesis for the right operand. return child == binary.Right; } @@ -656,7 +656,7 @@ private static bool NeedsParentheses(Expression parent, Expression child) { // Special case: negate of a constant needs parentheses, to // disambiguate it from a negative constant. - if (child != null && child.NodeType == ExpressionType.Constant && + if (child is not null && child.NodeType == ExpressionType.Constant && (parent.NodeType == ExpressionType.Negate || parent.NodeType == ExpressionType.NegateChecked)) { return true; } @@ -798,9 +798,9 @@ private void ParenthesizedVisit(Expression parent, Expression nodeToVisit) { protected override Expression VisitMethodCall(MethodCallExpression node) { Out(".Call "); - if (node.Object != null) { + if (node.Object is not null) { ParenthesizedVisit(node, node.Object); - } else if (node.Method.DeclaringType != null) { + } else if (node.Method.DeclaringType is not null) { Out(node.Method.DeclaringType.ToString()); } else { Out(""); @@ -1022,7 +1022,7 @@ protected override Expression VisitGoto(GotoExpression node) { protected override Expression VisitLoop(LoopExpression node) { Out(".Loop", Flow.Space); - if (node.ContinueLabel != null) { + if (node.ContinueLabel is not null) { DumpLabel(node.ContinueLabel); } @@ -1031,7 +1031,7 @@ protected override Expression VisitLoop(LoopExpression node) { Visit(node.Body); Dedent(); Out(Flow.NewLine, "}"); - if (node.BreakLabel != null) { + if (node.BreakLabel is not null) { Out(string.Empty, Flow.NewLine); DumpLabel(node.BreakLabel); } @@ -1059,7 +1059,7 @@ protected override Expression VisitSwitch(SwitchExpression node) { Visit(node.SwitchValue); Out(") {", Flow.NewLine); Visit(node.Cases, VisitSwitchCase); - if (node.DefaultBody != null) { + if (node.DefaultBody is not null) { Out(".Default:", Flow.NewLine); Indent(); Indent(); Visit(node.DefaultBody); @@ -1073,12 +1073,12 @@ protected override Expression VisitSwitch(SwitchExpression node) { protected override CatchBlock VisitCatchBlock(CatchBlock node) { Out(Flow.NewLine, "} .Catch (" + node.Test.ToString()); - if (node.Variable != null) { + if (node.Variable is not null) { Out(Flow.Space, string.Empty); VisitParameter(node.Variable); } - if (node.Filter != null) { + if (node.Filter is not null) { Out(") .If (", Flow.Break); Visit(node.Filter); } @@ -1096,12 +1096,12 @@ protected override Expression VisitTry(TryExpression node) { Visit(node.Body); Dedent(); Visit(node.Handlers, VisitCatchBlock); - if (node.Finally != null) { + if (node.Finally is not null) { Out(Flow.NewLine, "} .Finally {", Flow.NewLine); Indent(); Visit(node.Finally); Dedent(); - } else if (node.Fault != null) { + } else if (node.Fault is not null) { Out(Flow.NewLine, "} .Fault {", Flow.NewLine); Indent(); Visit(node.Fault); @@ -1113,7 +1113,7 @@ protected override Expression VisitTry(TryExpression node) { } protected override Expression VisitIndex(IndexExpression node) { - if (node.Indexer != null) { + if (node.Indexer is not null) { OutMember(node, node.Object, node.Indexer); } else { ParenthesizedVisit(node, node.Object); diff --git a/src/System.Management.Automation/engine/parser/FusionAssemblyIdentity.cs b/src/System.Management.Automation/engine/parser/FusionAssemblyIdentity.cs index f1511a24d9f..a1020296c09 100644 --- a/src/System.Management.Automation/engine/parser/FusionAssemblyIdentity.cs +++ b/src/System.Management.Automation/engine/parser/FusionAssemblyIdentity.cs @@ -235,7 +235,7 @@ internal static IAssemblyName ToAssemblyNameObject(string displayName) return null; } - Debug.Assert(displayName != null); + Debug.Assert(displayName is not null); IAssemblyName result; int hr = CreateAssemblyNameObject(out result, displayName, CANOF.PARSE_DISPLAY_NAME, IntPtr.Zero); if (hr != 0) @@ -243,7 +243,7 @@ internal static IAssemblyName ToAssemblyNameObject(string displayName) return null; } - Debug.Assert(result != null); + Debug.Assert(result is not null); return result; } @@ -258,29 +258,29 @@ internal static IAssemblyName GetBestMatch(IEnumerable candidates string bestCulture = null; foreach (var candidate in candidates) { - if (bestCandidate != null) + if (bestCandidate is not null) { Version candidateVersion = GetVersion(candidate); - Debug.Assert(candidateVersion != null); + Debug.Assert(candidateVersion is not null); if (bestVersion is null) { bestVersion = GetVersion(bestCandidate); - Debug.Assert(bestVersion != null); + Debug.Assert(bestVersion is not null); } int cmp = bestVersion.CompareTo(candidateVersion); if (cmp == 0) { - if (preferredCultureOpt != null) + if (preferredCultureOpt is not null) { string candidateCulture = GetCulture(candidate); - Debug.Assert(candidateCulture != null); + Debug.Assert(candidateCulture is not null); if (bestCulture is null) { bestCulture = GetCulture(candidate); - Debug.Assert(bestCulture != null); + Debug.Assert(bestCulture is not null); } // we have exactly the preferred culture or diff --git a/src/System.Management.Automation/engine/parser/GlobalAssemblyCache.cs b/src/System.Management.Automation/engine/parser/GlobalAssemblyCache.cs index 9fb742db7c0..971c61124af 100644 --- a/src/System.Management.Automation/engine/parser/GlobalAssemblyCache.cs +++ b/src/System.Management.Automation/engine/parser/GlobalAssemblyCache.cs @@ -110,7 +110,7 @@ private enum ASM_CACHE yield break; } - if (e != null) + if (e is not null) { throw e; } @@ -134,7 +134,7 @@ private enum ASM_CACHE break; } - if (architectureFilter != null) + if (architectureFilter is not null) { var assemblyArchitecture = FusionAssemblyIdentity.GetProcessorArchitecture(nameObject); if (!architectureFilter.Contains(assemblyArchitecture)) @@ -175,7 +175,7 @@ public static unsafe string ResolvePartialName( } var candidates = GetAssemblyObjects(nameObject, architectureFilter); - string cultureName = (preferredCulture != null && !preferredCulture.IsNeutralCulture) ? preferredCulture.Name : null; + string cultureName = (preferredCulture is not null && !preferredCulture.IsNeutralCulture) ? preferredCulture.Name : null; var bestMatch = FusionAssemblyIdentity.GetBestMatch(candidates, cultureName); if (bestMatch is null) @@ -197,7 +197,7 @@ public static unsafe string ResolvePartialName( IAssemblyCache assemblyCacheObject; CreateAssemblyCache(out assemblyCacheObject, 0); assemblyCacheObject.QueryAssemblyInfo(0, fullName, ref info); - Debug.Assert(info.pszCurrentAssemblyPathBuf != null); + Debug.Assert(info.pszCurrentAssemblyPathBuf is not null); Debug.Assert(info.pszCurrentAssemblyPathBuf[info.cchBuf - 1] == '\0'); var result = Marshal.PtrToStringUni((IntPtr)info.pszCurrentAssemblyPathBuf, (int)info.cchBuf - 1); diff --git a/src/System.Management.Automation/engine/parser/PSType.cs b/src/System.Management.Automation/engine/parser/PSType.cs index cf57d0e1ff8..5387d810ff6 100644 --- a/src/System.Management.Automation/engine/parser/PSType.cs +++ b/src/System.Management.Automation/engine/parser/PSType.cs @@ -33,7 +33,7 @@ internal class TypeDefiner private static bool TryConvertArg(object arg, Type type, out object result, Parser parser, IScriptExtent errorExtent) { // This code could be added to LanguagePrimitives.ConvertTo - if (arg != null && arg.GetType() == type) + if (arg is not null && arg.GetType() == type) { result = arg; return true; @@ -54,7 +54,7 @@ private static bool TryConvertArg(object arg, Type type, out object result, Pars private static CustomAttributeBuilder GetAttributeBuilder(Parser parser, AttributeAst attributeAst, AttributeTargets attributeTargets) { var attributeType = attributeAst.TypeName.GetReflectionAttributeType(); - Diagnostics.Assert(attributeType != null, "Semantic checks should have verified attribute type exists"); + Diagnostics.Assert(attributeType is not null, "Semantic checks should have verified attribute type exists"); Diagnostics.Assert( attributeType.GetCustomAttribute(true) is null || @@ -110,7 +110,7 @@ private static CustomAttributeBuilder GetAttributeBuilder(Parser parser, Attribu // This inconsistent behavior affects OneCore powershell because we are using the extension method here when compiling // against CoreCLR. So we need to add a null check until this is fixed in CLR. var paramArrayAttrs = parameterInfo[argIndex].GetCustomAttributes(typeof(ParamArrayAttribute), true); - if (paramArrayAttrs != null && paramArrayAttrs.Length > 0 && expandParamsOnBest) + if (paramArrayAttrs is not null && paramArrayAttrs.Length > 0 && expandParamsOnBest) { var elementType = parameterInfo[argIndex].ParameterType.GetElementType(); var paramsArray = Array.CreateInstance(elementType, positionalArgCount - argIndex); @@ -159,9 +159,9 @@ private static CustomAttributeBuilder GetAttributeBuilder(Parser parser, Attribu arg = namedArg.Argument.Accept(cvv); var propertyInfo = members[0] as PropertyInfo; - if (propertyInfo != null) + if (propertyInfo is not null) { - Diagnostics.Assert(propertyInfo.GetSetMethod() != null, "Semantic checks ensures property is settable"); + Diagnostics.Assert(propertyInfo.GetSetMethod() is not null, "Semantic checks ensures property is settable"); if (!TryConvertArg(arg, propertyInfo.PropertyType, out arg, parser, namedArg.Argument.Extent)) { @@ -192,12 +192,12 @@ private static CustomAttributeBuilder GetAttributeBuilder(Parser parser, Attribu internal static void DefineCustomAttributes(TypeBuilder member, ReadOnlyCollection attributes, Parser parser, AttributeTargets attributeTargets) { - if (attributes != null) + if (attributes is not null) { foreach (var attr in attributes) { var cabuilder = GetAttributeBuilder(parser, attr, attributeTargets); - if (cabuilder != null) + if (cabuilder is not null) { member.SetCustomAttribute(cabuilder); } @@ -207,12 +207,12 @@ internal static void DefineCustomAttributes(TypeBuilder member, ReadOnlyCollecti internal static void DefineCustomAttributes(PropertyBuilder member, ReadOnlyCollection attributes, Parser parser, AttributeTargets attributeTargets) { - if (attributes != null) + if (attributes is not null) { foreach (var attr in attributes) { var cabuilder = GetAttributeBuilder(parser, attr, attributeTargets); - if (cabuilder != null) + if (cabuilder is not null) { member.SetCustomAttribute(cabuilder); } @@ -222,12 +222,12 @@ internal static void DefineCustomAttributes(PropertyBuilder member, ReadOnlyColl internal static void DefineCustomAttributes(ConstructorBuilder member, ReadOnlyCollection attributes, Parser parser, AttributeTargets attributeTargets) { - if (attributes != null) + if (attributes is not null) { foreach (var attr in attributes) { var cabuilder = GetAttributeBuilder(parser, attr, attributeTargets); - if (cabuilder != null) + if (cabuilder is not null) { member.SetCustomAttribute(cabuilder); } @@ -237,12 +237,12 @@ internal static void DefineCustomAttributes(ConstructorBuilder member, ReadOnlyC internal static void DefineCustomAttributes(MethodBuilder member, ReadOnlyCollection attributes, Parser parser, AttributeTargets attributeTargets) { - if (attributes != null) + if (attributes is not null) { foreach (var attr in attributes) { var cabuilder = GetAttributeBuilder(parser, attr, attributeTargets); - if (cabuilder != null) + if (cabuilder is not null) { member.SetCustomAttribute(cabuilder); } @@ -252,12 +252,12 @@ internal static void DefineCustomAttributes(MethodBuilder member, ReadOnlyCollec internal static void DefineCustomAttributes(EnumBuilder member, ReadOnlyCollection attributes, Parser parser, AttributeTargets attributeTargets) { - if (attributes != null) + if (attributes is not null) { foreach (var attr in attributes) { var cabuilder = GetAttributeBuilder(parser, attr, attributeTargets); - if (cabuilder != null) + if (cabuilder is not null) { member.SetCustomAttribute(cabuilder); } @@ -377,12 +377,12 @@ private Type GetBaseTypes(Parser parser, TypeDefinitionAst typeDefinitionAst, ou } } - if (baseClass != null) + if (baseClass is not null) { // All PS classes are TypeName instances. // For PS classes we cannot use reflection API, because type is not created yet. var baseTypeName = firstBaseTypeAst.TypeName as TypeName; - if (baseTypeName != null) + if (baseTypeName is not null) { _baseClassHasDefaultCtor = baseTypeName.HasDefaultCtor(); } @@ -488,10 +488,10 @@ public void DefineMembers() foreach (var member in _typeDefinitionAst.Members) { var propertyMemberAst = member as PropertyMemberAst; - if (propertyMemberAst != null) + if (propertyMemberAst is not null) { DefineProperty(propertyMemberAst); - if (propertyMemberAst.InitialValue != null) + if (propertyMemberAst.InitialValue is not null) { if (propertyMemberAst.IsStatic) { @@ -506,7 +506,7 @@ public void DefineMembers() else { FunctionMemberAst method = member as FunctionMemberAst; - Diagnostics.Assert(method != null, StringUtil.Format("Unexpected subtype of MemberAst '{0}'. Expect `{1}`", + Diagnostics.Assert(method is not null, StringUtil.Format("Unexpected subtype of MemberAst '{0}'. Expect `{1}`", member.GetType().Name, typeof(FunctionMemberAst).GetType().Name)); if (method.IsConstructor) { @@ -603,7 +603,7 @@ private void DefineProperty(PropertyMemberAst propertyMemberAst) else { type = propertyMemberAst.PropertyType.TypeName.GetReflectionType(); - Diagnostics.Assert(type != null, "Semantic checks should have ensure type can't be null"); + Diagnostics.Assert(type is not null, "Semantic checks should have ensure type can't be null"); } PropertyBuilder property = this.EmitPropertyIl(propertyMemberAst, type); @@ -633,12 +633,12 @@ private PropertyBuilder EmitPropertyIl(PropertyMemberAst propertyMemberAst, Type var backingField = _typeBuilder.DefineField(backingFieldName, type, backingFieldAttributes); bool hasValidateAttributes = false; - if (propertyMemberAst.Attributes != null) + if (propertyMemberAst.Attributes is not null) { for (int i = 0; i < propertyMemberAst.Attributes.Count; i++) { Type attributeType = propertyMemberAst.Attributes[i].TypeName.GetReflectionAttributeType(); - if (attributeType != null && attributeType.IsSubclassOf(typeof(ValidateArgumentsAttribute))) + if (attributeType is not null && attributeType.IsSubclassOf(typeof(ValidateArgumentsAttribute))) { hasValidateAttributes = true; break; @@ -776,7 +776,7 @@ private Type[] GetParameterTypes(FunctionMemberAst functionMemberAst) for (var i = 0; i < parameters.Count; i++) { var typeConstraint = parameters[i].Attributes.OfType().FirstOrDefault(); - var paramType = (typeConstraint != null) + var paramType = (typeConstraint is not null) ? typeConstraint.TypeName.GetReflectionType() : typeof(object); if (paramType is null) @@ -813,7 +813,7 @@ private bool MethodExistsOnBaseClassAndFinal(string methodName, Type[] parameter } var mi = baseType.GetMethod(methodName, parameterTypes); - return mi != null && mi.IsFinal; + return mi is not null && mi.IsFinal; } private void DefineMethod(FunctionMemberAst functionMemberAst) @@ -1085,13 +1085,13 @@ internal static List Sort(List defineEnumHel foreach (var memberExpr in initExpr.FindAll(ast => ast is MemberExpressionAst, false)) { var typeExpr = ((MemberExpressionAst)memberExpr).Expression as TypeExpressionAst; - if (typeExpr != null) + if (typeExpr is not null) { // We only want to add edges for enums being defined in the current scope. // We detect this by seeing if the ast is in our graph or not. var typeName = typeExpr.TypeName as TypeName; - if (typeName != null - && typeName._typeDefinitionAst != null + if (typeName is not null + && typeName._typeDefinitionAst is not null && typeName._typeDefinitionAst != helper._enumDefinitionAst // Don't add self edges && graph.ContainsKey(typeName._typeDefinitionAst)) { @@ -1203,14 +1203,14 @@ internal void DefineEnum() foreach (var member in _enumDefinitionAst.Members) { var enumerator = (PropertyMemberAst)member; - if (enumerator.InitialValue != null) + if (enumerator.InitialValue is not null) { object constValue; if (IsConstantValueVisitor.IsConstant(enumerator.InitialValue, out constValue, false, false)) { if (!LanguagePrimitives.TryConvertTo(constValue, underlyingType, out value)) { - if (constValue != null && + if (constValue is not null && LanguagePrimitives.IsNumeric(LanguagePrimitives.GetTypeCode(constValue.GetType()))) { _parser.ReportError( @@ -1257,7 +1257,7 @@ internal void DefineEnum() ParserStrings.MemberAlreadyDefined, enumerator.Name); } - else if (value != null) + else if (value is not null) { value = Convert.ChangeType(value, underlyingType); definedEnumerators.Add(enumerator.Name); @@ -1363,7 +1363,7 @@ internal static Assembly DefineTypes(Parser parser, Ast rootAst, TypeDefinitionA SessionStateKeeper sessionStateKeeper = new SessionStateKeeper(); helperType.GetField(s_sessionStateKeeperFieldName, BindingFlags.NonPublic | BindingFlags.Static).SetValue(null, sessionStateKeeper); - if (helper._fieldsToInitForMemberFunctions != null) + if (helper._fieldsToInitForMemberFunctions is not null) { foreach (var tuple in helper._fieldsToInitForMemberFunctions) { @@ -1407,13 +1407,13 @@ private static string GetClassNameInAssembly(TypeDefinitionAst typeDefinitionAst // Only allocate a list if necessary - in the most common case, we don't need it. List nameParts = null; var parent = typeDefinitionAst.Parent; - while (parent.Parent != null) + while (parent.Parent is not null) { if (parent is IParameterMetadataProvider) { nameParts = nameParts ?? new List(); var fnDefn = parent.Parent as FunctionDefinitionAst; - if (fnDefn != null) + if (fnDefn is not null) { parent = fnDefn; nameParts.Add(fnDefn.Name); diff --git a/src/System.Management.Automation/engine/parser/Parser.cs b/src/System.Management.Automation/engine/parser/Parser.cs index 8c3f8c75bdd..40a28f8cb55 100644 --- a/src/System.Management.Automation/engine/parser/Parser.cs +++ b/src/System.Management.Automation/engine/parser/Parser.cs @@ -177,7 +177,7 @@ private ScriptBlockAst ParseTask(string fileName, string input, List toke _parseMode = parseMode; _fileName = fileName; _tokenizer.Initialize(fileName, input, tokenList); - _savingTokens = (tokenList != null); + _savingTokens = (tokenList is not null); ErrorList.Clear(); try @@ -312,13 +312,13 @@ private static bool IgnoreTokenWhenUpdatingPreviousFirstLast(Token token) internal void SetPreviousFirstLastToken(ExecutionContext context) { var firstToken = _tokenizer.FirstToken; - if (firstToken != null) + if (firstToken is not null) { context.SetVariable(SpecialVariables.FirstTokenVarPath, _previousFirstTokenText); if (!IgnoreTokenWhenUpdatingPreviousFirstLast(firstToken)) { var stringToken = firstToken as StringToken; - _previousFirstTokenText = stringToken != null + _previousFirstTokenText = stringToken is not null ? stringToken.Value : firstToken.Text; } @@ -329,7 +329,7 @@ internal void SetPreviousFirstLastToken(ExecutionContext context) if (!IgnoreTokenWhenUpdatingPreviousFirstLast(lastToken)) { var stringToken = lastToken as StringToken; - _previousLastTokenText = stringToken != null + _previousLastTokenText = stringToken is not null ? stringToken.Value : lastToken.Text; } @@ -444,7 +444,7 @@ private Token PeekToken() private Token NextMemberAccessToken(bool allowLBracket) { // If _ungotToken is not null, we're in some sort of error state, don't return the token. - if (_ungotToken != null) + if (_ungotToken is not null) return null; return _tokenizer.GetMemberAccessOperator(allowLBracket); } @@ -452,14 +452,14 @@ private Token NextMemberAccessToken(bool allowLBracket) private Token NextInvokeMemberToken() { // If _ungotToken is not null, we're in some sort of error state, don't return the token. - if (_ungotToken != null) + if (_ungotToken is not null) return null; return _tokenizer.GetInvokeMemberOpenParen(); } private Token NextLBracket() { - if (_ungotToken != null) + if (_ungotToken is not null) { if (_ungotToken.Kind == TokenKind.LBracket) return NextToken(); // If _ungotToken is not null, we're in some sort of error state, don't return the token. @@ -482,7 +482,7 @@ private StringToken GetVerbatimCommandArgumentToken() private void SkipToken() { - Diagnostics.Assert(_ungotToken != null, "Don't skip a token you didn't unget"); + Diagnostics.Assert(_ungotToken is not null, "Don't skip a token you didn't unget"); _ungotToken = null; } @@ -494,7 +494,7 @@ private void UngetToken(Token token) private void SetTokenizerMode(TokenizerMode mode) { - if (mode != _tokenizer.Mode && _ungotToken != null) + if (mode != _tokenizer.Mode && _ungotToken is not null) { // Only rescan tokens that differ b/w command and expression modes. if (!_ungotToken.Kind.HasTrait(TokenFlags.ParseModeInvariant)) @@ -612,22 +612,22 @@ internal static IScriptExtent ExtentFromFirstOf(params object[] objs) { foreach (object obj in objs) { - if (obj != null) + if (obj is not null) { var token = obj as Token; - if (token != null) + if (token is not null) { return token.Extent; } var ast = obj as Ast; - if (ast != null) + if (ast is not null) { return ast.Extent; } var typename = obj as ITypeName; - if (typename != null) + if (typename is not null) { return typename.Extent; } @@ -668,21 +668,21 @@ private static IEnumerable GetNestedErrorAsts(params object[] asts) { foreach (var obj in asts) { - if (obj != null) + if (obj is not null) { Ast ast = obj as Ast; - if (ast != null) + if (ast is not null) { yield return ast; } else { var enumerable = obj as IEnumerable; - if (enumerable != null) + if (enumerable is not null) { foreach (var ast2 in enumerable) { - if (ast2 != null) + if (ast2 is not null) { yield return ast2; } @@ -718,10 +718,10 @@ internal static bool TryParseAsConstantHashtable(string input, out Hashtable res if ((ast is null) || parseErrors.Length > 0 || - ast.BeginBlock != null || - ast.ProcessBlock != null || - ast.DynamicParamBlock != null || - ast.EndBlock.Traps != null) + ast.BeginBlock is not null || + ast.ProcessBlock is not null || + ast.DynamicParamBlock is not null || + ast.EndBlock.Traps is not null) { return false; } @@ -757,7 +757,7 @@ internal static bool TryParseAsConstantHashtable(string input, out Hashtable res } var data = hashtable as Hashtable; - Diagnostics.Assert((data != null), "IsConstantValueVisitor.IsConstant() should return false when the specified HashtableAst is not a avalid Hashtable"); + Diagnostics.Assert((data is not null), "IsConstantValueVisitor.IsConstant() should return false when the specified HashtableAst is not a avalid Hashtable"); result = data; return true; } @@ -825,7 +825,7 @@ private List UsingStatementsRule() var usingStatement = statement as UsingStatementAst; // otherwise returned statement is ErrorStatementAst. // We ignore it here, because error already reported to the parser. - if (usingStatement != null) + if (usingStatement is not null) { result.Add(usingStatement); } @@ -880,18 +880,18 @@ private ParamBlockAst ParamBlockRule() UngetToken(rParen); endExtent = Before(rParen); - ReportIncompleteInput(After(parameters != null && parameters.Count > 0 ? parameters.Last().Extent : lparen.Extent), + ReportIncompleteInput(After(parameters is not null && parameters.Count > 0 ? parameters.Last().Extent : lparen.Extent), nameof(ParserStrings.MissingEndParenthesisInFunctionParameterList), ParserStrings.MissingEndParenthesisInFunctionParameterList); } List attributes = new List(); - if (candidateAttributes != null) + if (candidateAttributes is not null) { foreach (AttributeBaseAst attr in candidateAttributes) { AttributeAst attribute = attr as AttributeAst; - if (attribute != null) + if (attribute is not null) { attributes.Add(attribute); } @@ -924,7 +924,7 @@ private List ParameterListRule() ParameterAst parameter = ParameterRule(); if (parameter is null) { - if (commaToken != null) + if (commaToken is not null) { // ErrorRecovery: ?? @@ -976,7 +976,7 @@ private ParameterAst ParameterRule() if (token.Kind != TokenKind.Variable && token.Kind != TokenKind.SplattedVariable) { UngetToken(token); - if (attributes != null) + if (attributes is not null) { // ErrorRecovery: skip to closing paren because returning null signals the last parameter. @@ -1032,7 +1032,7 @@ private List AttributeListRule(bool inExpressionMode) List attributes = new List(); AttributeBaseAst attribute = AttributeRule(); - while (attribute != null) + while (attribute is not null) { attributes.Add(attribute); if (!inExpressionMode || attribute is AttributeAst) @@ -1121,7 +1121,7 @@ private AttributeBaseAst AttributeRule() UngetToken(rBracket); rBracket = null; // Don't bother reporting a missing ']' if we reported a missing ')'. - if (rParen != null) + if (rParen is not null) { ReportIncompleteInput(After(rParen), nameof(ParserStrings.EndSquareBracketExpectedAtEndOfAttribute), @@ -1177,7 +1177,7 @@ private void AttributeArgumentsRule(ICollection positionalArgumen ExpressionAst expr; bool expressionOmitted = false; - if (name != null) + if (name is not null) { Token token = PeekToken(); if (token.Kind == TokenKind.Equals) @@ -1215,7 +1215,7 @@ private void AttributeArgumentsRule(ICollection positionalArgumen expr = ExpressionRule(); } - if (name != null) + if (name is not null) { if (keysSeen.Contains(name.Value)) { @@ -1232,12 +1232,12 @@ private void AttributeArgumentsRule(ICollection positionalArgumen name.Value, expr, expressionOmitted)); } } - else if (expr != null) + else if (expr is not null) { positionalArguments.Add(expr); lastItemExtent = expr.Extent; } - else if (commaToken != null) + else if (commaToken is not null) { // ErrorRecovery: Pretend we saw the argument and keep going. @@ -1414,7 +1414,7 @@ private ITypeName GetSingleGenericArgument(Token firstToken) } ITypeName typeName = FinishTypeNameRule(token); - if (typeName != null) + if (typeName is not null) { Token rBracket = NextToken(); if (rBracket.Kind != TokenKind.RBracket) @@ -1599,7 +1599,7 @@ private bool CompleteScriptBlockBody(Token lCurly, ref IScriptExtent bodyExtent, { // If the caller passed in the open curly, then they expect us to consume the closing curly // and include that in the extent. - if (lCurly != null) + if (lCurly is not null) { Token rCurly = NextToken(); IScriptExtent endScriptBlock; @@ -1663,12 +1663,12 @@ private ScriptBlockAst ScriptBlockBodyRule(Token lCurly, List List traps = new List(); List statements = new List(); - if (predefinedStatementAst != null) + if (predefinedStatementAst is not null) { statements.Add(predefinedStatementAst); } - IScriptExtent statementListExtent = paramBlockAst != null ? paramBlockAst.Extent : null; + IScriptExtent statementListExtent = paramBlockAst is not null ? paramBlockAst.Extent : null; IScriptExtent scriptBlockExtent; while (true) @@ -1678,7 +1678,7 @@ private ScriptBlockAst ScriptBlockBodyRule(Token lCurly, List { statementListExtent = extent; } - else if (extent != null) + else if (extent is not null) { statementListExtent = ExtentOf(statementListExtent, extent); } @@ -1707,9 +1707,9 @@ private ScriptBlockAst NamedBlockListRule(Token lCurly, List NamedBlockAst beginBlock = null; NamedBlockAst processBlock = null; NamedBlockAst endBlock = null; - IScriptExtent startExtent = lCurly != null + IScriptExtent startExtent = lCurly is not null ? lCurly.Extent - : (paramBlockAst != null) ? paramBlockAst.Extent : null; + : (paramBlockAst is not null) ? paramBlockAst.Extent : null; IScriptExtent endExtent = null; IScriptExtent extent = null; IScriptExtent scriptBlockExtent = null; @@ -1722,7 +1722,7 @@ private ScriptBlockAst NamedBlockListRule(Token lCurly, List default: // Next token is unexpected. // ErrorRecovery: if 'lCurly' is present, pretend we saw a closing curly; otherwise, eat the unexpected token. - if (lCurly != null) + if (lCurly is not null) { UngetToken(blockNameToken); scriptBlockExtent = ExtentOf(startExtent, endExtent); @@ -1875,7 +1875,7 @@ private IScriptExtent StatementListRule(List statements, List 0) { if ((token.TokenFlags & TokenFlags.StatementDoesntSupportAttributes) != 0) @@ -2044,7 +2044,7 @@ private StatementAst StatementRule() statement = BlockStatementRule(token); break; case TokenKind.Configuration: - statement = ConfigurationStatementRule(attributes != null ? attributes.OfType() : null, token); + statement = ConfigurationStatementRule(attributes is not null ? attributes.OfType() : null, token); break; case TokenKind.From: case TokenKind.Define: @@ -2060,7 +2060,7 @@ private StatementAst StatementRule() statement = LabeledStatementRule((LabelToken)token); break; case TokenKind.EndOfInput: - if (attributes != null) + if (attributes is not null) { Resync(restorePoint); statement = PipelineChainRule(); @@ -2105,7 +2105,7 @@ private StatementAst StatementRule() break; default: - if (attributes != null) + if (attributes is not null) { Resync(restorePoint); } @@ -2162,7 +2162,7 @@ private ExpressionAst LabelOrKeyRule() // G unary-expression var simpleName = SimpleNameRule(); - if (simpleName != null) + if (simpleName is not null) { return simpleName; } @@ -2182,7 +2182,7 @@ private ExpressionAst LabelOrKeyRule() _disableCommaOperator = disableCommaOperator; } - if (labelExpr != null) + if (labelExpr is not null) { return labelExpr; } @@ -2202,7 +2202,7 @@ private BreakStatementAst BreakStatementRule(Token breakToken) // G 'break' label-expression:opt ExpressionAst labelExpr = LabelOrKeyRule(); - IScriptExtent extent = (labelExpr != null) + IScriptExtent extent = (labelExpr is not null) ? ExtentOf(breakToken, labelExpr) : breakToken.Extent; @@ -2215,7 +2215,7 @@ private ContinueStatementAst ContinueStatementRule(Token continueToken) // G 'continue' label-expression:opt ExpressionAst labelExpr = LabelOrKeyRule(); - IScriptExtent extent = (labelExpr != null) + IScriptExtent extent = (labelExpr is not null) ? ExtentOf(continueToken, labelExpr) : continueToken.Extent; @@ -2228,7 +2228,7 @@ private ReturnStatementAst ReturnStatementRule(Token token) // G 'return' pipeline-chain:opt PipelineBaseAst pipeline = PipelineChainRule(); - IScriptExtent extent = (pipeline != null) + IScriptExtent extent = (pipeline is not null) ? ExtentOf(token, pipeline) : token.Extent; return new ReturnStatementAst(extent, pipeline); @@ -2240,7 +2240,7 @@ private ExitStatementAst ExitStatementRule(Token token) // G 'exit' pipeline-chain:opt PipelineBaseAst pipeline = PipelineChainRule(); - IScriptExtent extent = (pipeline != null) + IScriptExtent extent = (pipeline is not null) ? ExtentOf(token, pipeline) : token.Extent; return new ExitStatementAst(extent, pipeline); @@ -2252,7 +2252,7 @@ private ThrowStatementAst ThrowStatementRule(Token token) // G 'throw' pipeline:opt PipelineBaseAst pipeline = PipelineChainRule(); - IScriptExtent extent = (pipeline != null) + IScriptExtent extent = (pipeline is not null) ? ExtentOf(token, pipeline) : token.Extent; @@ -2335,7 +2335,7 @@ private bool InlineScriptRule(Token inlineScriptToken, List e // G Command // G InlineScript scriptblock-expression - Diagnostics.Assert(elements != null && elements.Count == 0, "The CommandElement list should be empty"); + Diagnostics.Assert(elements is not null && elements.Count == 0, "The CommandElement list should be empty"); var commandName = new StringConstantExpressionAst(inlineScriptToken.Extent, inlineScriptToken.Text, StringConstantType.BareWord); inlineScriptToken.TokenFlags |= TokenFlags.CommandName; elements.Add(commandName); @@ -2496,7 +2496,7 @@ private StatementAst IfStatementRule(Token ifToken) break; } - IScriptExtent endExtent = (elseClause != null) + IScriptExtent endExtent = (elseClause is not null) ? elseClause.Extent : clauses[clauses.Count - 1].Item2.Extent; IScriptExtent extent = ExtentOf(ifToken, endExtent); @@ -2799,7 +2799,7 @@ private StatementAst SwitchStatementRule(LabelToken labelToken, Token switchToke if (isDefaultClause) { - if (@default != null) + if (@default is not null) { // ErrorRecovery: just report the error and continue, forget the previous default clause. @@ -2850,7 +2850,7 @@ private StatementAst SwitchStatementRule(LabelToken labelToken, Token switchToke } return new SwitchStatementAst(ExtentOf(labelToken ?? switchToken, rCurly), - labelToken != null ? labelToken.LabelText : null, condition, flags, clauses, @default); + labelToken is not null ? labelToken.LabelText : null, condition, flags, clauses, @default); } private StatementAst ConfigurationStatementRule(IEnumerable customAttributes, Token configurationToken) @@ -2978,7 +2978,7 @@ private StatementAst ConfigurationStatementRule(IEnumerable custom try { - if (localRunspace != null) + if (localRunspace is not null) { p = PowerShell.Create(); p.Runspace = localRunspace; @@ -3006,7 +3006,7 @@ private StatementAst ConfigurationStatementRule(IEnumerable custom } // Load any keywords that have been defined earlier in the script. - if (_configurationKeywordsDefinedInThisFile != null) + if (_configurationKeywordsDefinedInThisFile is not null) { foreach (var kw in _configurationKeywordsDefinedInThisFile.Values) { @@ -3033,7 +3033,7 @@ private StatementAst ConfigurationStatementRule(IEnumerable custom } finally { - if (p != null) + if (p is not null) { p.Dispose(); } @@ -3087,7 +3087,7 @@ private StatementAst ConfigurationStatementRule(IEnumerable custom // If we are at the top level, then we'll add it to the list of keywords defined in this // parse so it can be used as a resource in subsequent config statements. var scAst = configurationName as StringConstantExpressionAst; - if (scAst != null) + if (scAst is not null) { var keywordToAddForThisConfigurationStatement = new System.Management.Automation.Language.DynamicKeyword { @@ -3116,32 +3116,32 @@ private StatementAst ConfigurationStatementRule(IEnumerable custom // Extract the parameters, if any and them to the keyword definition. var sbeAst = configurationBodyScriptBlock as ScriptBlockExpressionAst; - if (sbeAst != null) + if (sbeAst is not null) { var pList = sbeAst.ScriptBlock.ParamBlock; - if (pList != null) + if (pList is not null) { foreach (var parm in pList.Parameters) { var keywordProp = new DynamicKeywordProperty(); keywordProp.Name = parm.Name.VariablePath.UserPath; - if (parm.Attributes != null) + if (parm.Attributes is not null) { foreach (var attr in parm.Attributes) { var typeConstraint = attr as TypeConstraintAst; - if (typeConstraint != null) + if (typeConstraint is not null) { keywordProp.TypeConstraint = typeConstraint.TypeName.Name; continue; } var aAst = attr as AttributeAst; - if (aAst != null) + if (aAst is not null) { if (string.Equals(aAst.TypeName.Name, "Parameter", StringComparison.OrdinalIgnoreCase)) { - if (aAst.NamedArguments != null) + if (aAst.NamedArguments is not null) { foreach (var na in aAst.NamedArguments) { @@ -3151,10 +3151,10 @@ private StatementAst ConfigurationStatementRule(IEnumerable custom { keywordProp.Mandatory = true; } - else if (na.Argument != null) + else if (na.Argument is not null) { ConstantExpressionAst ceAst = na.Argument as ConstantExpressionAst; - if (ceAst != null) + if (ceAst is not null) { keywordProp.Mandatory = System.Management.Automation.LanguagePrimitives.IsTrue(ceAst.Value); } @@ -3194,10 +3194,10 @@ private StatementAst ConfigurationStatementRule(IEnumerable custom //############################################################ bool isMetaConfiguration = false; - if (customAttributes != null) + if (customAttributes is not null) { isMetaConfiguration = customAttributes.Any( - attribute => (attribute.TypeName.GetReflectionAttributeType() != null) && + attribute => (attribute.TypeName.GetReflectionAttributeType() is not null) && (attribute.TypeName.GetReflectionAttributeType() == typeof(DscLocalConfigurationManagerAttribute))); } @@ -3226,7 +3226,7 @@ private StatementAst ConfigurationStatementRule(IEnumerable custom finally { // If we had to allocate a runspace for the parser, we'll free it now. - if (localRunspace != null) + if (localRunspace is not null) { // If a runspace was created for this operation, close it and reset the default runspace to null. localRunspace.Close(); @@ -3300,7 +3300,7 @@ private StatementAst ForeachStatementRule(LabelToken labelToken, Token forEachTo // G command-argument // G primary-expression - IScriptExtent startOfStatement = labelToken != null ? labelToken.Extent : forEachToken.Extent; + IScriptExtent startOfStatement = labelToken is not null ? labelToken.Extent : forEachToken.Extent; IScriptExtent endErrorStatement = null; SkipNewlines(); @@ -3434,14 +3434,14 @@ private StatementAst ForeachStatementRule(LabelToken labelToken, Token forEachTo } } - if (endErrorStatement != null) + if (endErrorStatement is not null) { return new ErrorStatementAst(ExtentOf(startOfStatement, endErrorStatement), GetNestedErrorAsts(variableAst, pipeline, body)); } return new ForEachStatementAst(ExtentOf(startOfStatement, body), - labelToken != null ? labelToken.LabelText : null, + labelToken is not null ? labelToken.LabelText : null, flags, throttleLimit, variableAst, pipeline, body); } @@ -3486,7 +3486,7 @@ private StatementAst ForStatementRule(LabelToken labelToken, Token forToken) SkipNewlines(); PipelineBaseAst initializer = PipelineChainRule(); - if (initializer != null) + if (initializer is not null) { endErrorStatement = initializer.Extent; } @@ -3498,7 +3498,7 @@ private StatementAst ForStatementRule(LabelToken labelToken, Token forToken) SkipNewlines(); PipelineBaseAst condition = PipelineChainRule(); - if (condition != null) + if (condition is not null) { endErrorStatement = condition.Extent; } @@ -3510,7 +3510,7 @@ private StatementAst ForStatementRule(LabelToken labelToken, Token forToken) SkipNewlines(); PipelineBaseAst iterator = PipelineChainRule(); - if (iterator != null) + if (iterator is not null) { endErrorStatement = iterator.Extent; } @@ -3554,7 +3554,7 @@ private StatementAst ForStatementRule(LabelToken labelToken, Token forToken) } return new ForStatementAst(ExtentOf(labelToken ?? forToken, body), - labelToken != null ? labelToken.LabelText : null, initializer, condition, iterator, body); + labelToken is not null ? labelToken.LabelText : null, initializer, condition, iterator, body); } private StatementAst WhileStatementRule(LabelToken labelToken, Token whileToken) @@ -3636,7 +3636,7 @@ private StatementAst WhileStatementRule(LabelToken labelToken, Token whileToken) } return new WhileStatementAst(ExtentOf(labelToken ?? whileToken, body), - labelToken != null ? labelToken.LabelText : null, condition, body); + labelToken is not null ? labelToken.LabelText : null, condition, body); } /// @@ -3658,12 +3658,12 @@ private StatementAst DynamicKeywordStatementRule(Token functionName, DynamicKeyw ////////////////////////////////////////////////////////////////////////////////// // If a custom action was provided. then invoke it ////////////////////////////////////////////////////////////////////////////////// - if (keywordData.PreParse != null) + if (keywordData.PreParse is not null) { try { ParseError[] errors = keywordData.PreParse(keywordData); - if (errors != null && errors.Length > 0) + if (errors is not null && errors.Length > 0) { foreach (var e in errors) { @@ -3875,7 +3875,7 @@ private StatementAst DynamicKeywordStatementRule(Token functionName, DynamicKeyw InvokeMemberExpressionAst instanceInvokeMemberExpressionAst = instanceName as InvokeMemberExpressionAst; - if (instanceInvokeMemberExpressionAst != null && + if (instanceInvokeMemberExpressionAst is not null && instanceInvokeMemberExpressionAst.Arguments.Count == 1 && instanceInvokeMemberExpressionAst.Arguments[0] is ScriptBlockExpressionAst && // the last condition checks that there is no space between "method" name and '{' @@ -3894,7 +3894,7 @@ instanceInvokeMemberExpressionAst.Arguments[0] is ScriptBlockExpressionAst && lCurly.Text); } - if (lCurly.Kind == TokenKind.Dot && originalInstanceName != null && lCurly.Extent.StartOffset == originalInstanceName.Extent.EndOffset) + if (lCurly.Kind == TokenKind.Dot && originalInstanceName is not null && lCurly.Extent.StartOffset == originalInstanceName.Extent.EndOffset) { // Generate more useful ast for tab-completing extension methods on special DSC collection variables // e.g. configuration foo { node $AllNodes. @@ -3997,12 +3997,12 @@ instanceInvokeMemberExpressionAst.Arguments[0] is ScriptBlockExpressionAst && ////////////////////////////////////////////////////////////////////////////////// // If a custom action was provided. then invoke it ////////////////////////////////////////////////////////////////////////////////// - if (keywordData.PostParse != null) + if (keywordData.PostParse is not null) { try { ParseError[] errors = keywordData.PostParse(dynamicKeywordAst); - if (errors != null && errors.Length > 0) + if (errors is not null && errors.Length > 0) { foreach (var e in errors) { @@ -4112,7 +4112,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) + if (condition is not null) { endErrorStatement = condition.Extent; ReportIncompleteInput(After(endErrorStatement), @@ -4125,13 +4125,13 @@ private StatementAst DoWhileStatementRule(LabelToken labelToken, Token doToken) } } - if (endErrorStatement != null) + if (endErrorStatement is not null) { return new ErrorStatementAst(ExtentOf(startExtent, endErrorStatement), GetNestedErrorAsts(body, condition)); } IScriptExtent extent = ExtentOf(startExtent, rParen); - string label = (labelToken != null) ? labelToken.LabelText : null; + string label = (labelToken is not null) ? labelToken.LabelText : null; if (whileOrUntilToken.Kind == TokenKind.Until) { return new DoUntilStatementAst(extent, label, condition, body); @@ -4246,15 +4246,15 @@ private StatementAst ClassDefinitionRule(List customAttributes List members = new List(); List astsOnError = null; - while ((member = ClassMemberRule(name.Value, out astsOnError)) != null || astsOnError != null) + while ((member = ClassMemberRule(name.Value, out astsOnError)) is not null || astsOnError is not null) { - if (member != null) + if (member is not null) { members.Add(member); lastExtent = member.Extent; } - if (astsOnError != null && astsOnError.Count > 0) + if (astsOnError is not null && astsOnError.Count > 0) { if (nestedAsts is null) { @@ -4281,12 +4281,12 @@ private StatementAst ClassDefinitionRule(List customAttributes lastExtent = rCurly.Extent; } - var startExtent = customAttributes != null && customAttributes.Count > 0 + var startExtent = customAttributes is not null && customAttributes.Count > 0 ? 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); - if (customAttributes != null && customAttributes.OfType().Any()) + if (customAttributes is not null && customAttributes.OfType().Any()) { if (nestedAsts is null) { @@ -4297,7 +4297,7 @@ private StatementAst ClassDefinitionRule(List customAttributes nestedAsts.Add(classDefn); } - if (nestedAsts != null && nestedAsts.Count > 0) + if (nestedAsts is not null && nestedAsts.Count > 0) { return new ErrorStatementAst(extent, nestedAsts); } @@ -4352,7 +4352,7 @@ private MemberAst ClassMemberRule(string className, out List astsOnError) SkipNewlines(); var attribute = AttributeRule(); - if (attribute != null) + if (attribute is not null) { lastAttribute = attribute; if (startExtent is null) @@ -4361,7 +4361,7 @@ private MemberAst ClassMemberRule(string className, out List astsOnError) } var attributeAst = attribute as AttributeAst; - if (attributeAst != null) + if (attributeAst is not null) { attributeList.Add(attributeAst); } @@ -4387,7 +4387,7 @@ private MemberAst ClassMemberRule(string className, out List astsOnError) { #if SUPPORT_PUBLIC_PRIVATE case TokenKind.Public: - if (publicToken != null) + if (publicToken is not null) { ReportError(token.Extent, nameof(ParserStrings.DuplicateQualifier), @@ -4395,7 +4395,7 @@ private MemberAst ClassMemberRule(string className, out List astsOnError) token.Text); } - if (privateToken != null) + if (privateToken is not null) { ReportError(token.Extent, nameof(ParserStrings.ModifiersCannotBeCombined), @@ -4409,7 +4409,7 @@ private MemberAst ClassMemberRule(string className, out List astsOnError) break; case TokenKind.Private: - if (privateToken != null) + if (privateToken is not null) { ReportError(token.Extent, nameof(ParserStrings.DuplicateQualifier), @@ -4417,7 +4417,7 @@ private MemberAst ClassMemberRule(string className, out List astsOnError) token.Text); } - if (publicToken != null) + if (publicToken is not null) { ReportError(token.Extent, nameof(ParserStrings.ModifiersCannotBeCombined), @@ -4432,7 +4432,7 @@ private MemberAst ClassMemberRule(string className, out List astsOnError) #endif case TokenKind.Hidden: - if (hiddenToken != null) + if (hiddenToken is not null) { ReportError(token.Extent, nameof(ParserStrings.DuplicateQualifier), @@ -4446,7 +4446,7 @@ private MemberAst ClassMemberRule(string className, out List astsOnError) break; case TokenKind.Static: - if (staticToken != null) + if (staticToken is not null) { ReportError(token.Extent, nameof(ParserStrings.DuplicateQualifier), @@ -4481,21 +4481,21 @@ private MemberAst ClassMemberRule(string className, out List astsOnError) } #if SUPPORT_PUBLIC_PRIVATE - PropertyAttributes attributes = privateToken != null ? PropertyAttributes.Private : PropertyAttributes.Public; + PropertyAttributes attributes = privateToken is not null ? PropertyAttributes.Private : PropertyAttributes.Public; #else PropertyAttributes attributes = PropertyAttributes.Public; #endif - if (staticToken != null) + if (staticToken is not null) { attributes |= PropertyAttributes.Static; } - if (hiddenToken != null) + if (hiddenToken is not null) { attributes |= PropertyAttributes.Hidden; } - var endExtent = initialValueAst != null ? initialValueAst.Extent : varToken.Extent; + var endExtent = initialValueAst is not null ? initialValueAst.Extent : varToken.Extent; Token terminatorToken = PeekToken(); if (terminatorToken.Kind != TokenKind.NewLine && terminatorToken.Kind != TokenKind.Semi && terminatorToken.Kind != TokenKind.RCurly) { @@ -4533,7 +4533,7 @@ private MemberAst ClassMemberRule(string className, out List astsOnError) if (TryUseTokenAsSimpleName(token)) { SkipToken(); - var functionDefinition = MethodDeclarationRule(token, className, staticToken != null) as FunctionDefinitionAst; + var functionDefinition = MethodDeclarationRule(token, className, staticToken is not null) as FunctionDefinitionAst; if (functionDefinition is null) { @@ -4546,16 +4546,16 @@ private MemberAst ClassMemberRule(string className, out List astsOnError) } #if SUPPORT_PUBLIC_PRIVATE - MethodAttributes attributes = privateToken != null ? MethodAttributes.Private : MethodAttributes.Public; + MethodAttributes attributes = privateToken is not null ? MethodAttributes.Private : MethodAttributes.Public; #else MethodAttributes attributes = MethodAttributes.Public; #endif - if (staticToken != null) + if (staticToken is not null) { attributes |= MethodAttributes.Static; } - if (hiddenToken != null) + if (hiddenToken is not null) { attributes |= MethodAttributes.Hidden; } @@ -4563,7 +4563,7 @@ private MemberAst ClassMemberRule(string className, out List astsOnError) return new FunctionMemberAst(ExtentOf(startExtent, functionDefinition), functionDefinition, typeConstraint, attributeList, attributes); } - if (lastAttribute != null) + if (lastAttribute is not null) { // We have the start of a member, but didn't see a variable or 'def'. ReportIncompleteInput(After(ExtentFromFirstOf(lastAttribute)), @@ -4725,7 +4725,7 @@ private StatementAst EnumDefinitionRule(List customAttributes, IScriptExtent lastExtent = lCurly.Extent; MemberAst member; List members = new List(); - while ((member = EnumMemberRule()) != null) + while ((member = EnumMemberRule()) is not null) { members.Add(member); lastExtent = member.Extent; @@ -4742,12 +4742,12 @@ private StatementAst EnumDefinitionRule(List customAttributes, ParserStrings.MissingEndCurlyBrace); } - var startExtent = customAttributes != null && customAttributes.Count > 0 + var startExtent = customAttributes is not null && customAttributes.Count > 0 ? 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 }); - if (customAttributes != null && customAttributes.OfType().Any()) + if (customAttributes is not null && customAttributes.OfType().Any()) { // No need to report error since there is error reported in method StatementRule List nestedAsts = new List(); @@ -5055,7 +5055,7 @@ private StringConstantExpressionAst ResolveUsingAssembly(StringConstantExpressio // # using assembly behavior should be the same in these two cases: // cd A; $script.Invoke() // cd B; $script.Invoke() - if (Runspaces.Runspace.DefaultRunspace != null) + if (Runspaces.Runspace.DefaultRunspace is not null) { workingDirectory = Runspaces.Runspace.DefaultRunspace.ExecutionContext.EngineIntrinsics.SessionState.Path.CurrentLocation.Path; } @@ -5207,7 +5207,7 @@ private StatementAst MethodDeclarationRule(Token functionNameToken, string class } } - if (endErrorStatement != null) + if (endErrorStatement is not null) { return new ErrorStatementAst(ExtentOf(functionNameToken, endErrorStatement), parameters); } @@ -5217,7 +5217,7 @@ private StatementAst MethodDeclarationRule(Token functionNameToken, string class { IScriptExtent baseCallExtent; IScriptExtent baseKeywordExtent; - if (baseToken != null) + if (baseToken is not null) { baseCallExtent = ExtentOf(baseToken, baseCallLastExtent); baseKeywordExtent = baseToken.Extent; @@ -5319,7 +5319,7 @@ private StatementAst FunctionDeclarationRule(Token functionToken) } } - if (endErrorStatement != null) + if (endErrorStatement is not null) { return new ErrorStatementAst(ExtentOf(functionToken, endErrorStatement), parameters); } @@ -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 is not null && typeConstraintAst is 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 @@ -5452,7 +5452,7 @@ private CatchClauseAst CatchBlockRule(ref IScriptExtent endErrorStatement, ref L if (type is null) { - if (commaToken != null) + if (commaToken is not null) { // ErrorRecovery: Just consume the comma, pretend it wasn't there and look for the handler block. @@ -5504,13 +5504,13 @@ private CatchClauseAst CatchBlockRule(ref IScriptExtent endErrorStatement, ref L { // ErrorRecovery: just use the "missing" block in the result ast. - endErrorStatement = exceptionTypes != null ? exceptionTypes.Last().Extent : catchToken.Extent; + endErrorStatement = exceptionTypes is not null ? exceptionTypes.Last().Extent : catchToken.Extent; ReportIncompleteInput(After(endErrorStatement), nameof(ParserStrings.MissingCatchHandlerBlock), ParserStrings.MissingCatchHandlerBlock); } - if (exceptionTypes != null) + if (exceptionTypes is not null) { if (errorAsts is null) { @@ -5562,7 +5562,7 @@ private StatementAst TryStatementRule(Token tryToken) CatchClauseAst catchClause; List catches = new List(); List errorAsts = null; - while ((catchClause = CatchBlockRule(ref endErrorStatement, ref errorAsts)) != null) + while ((catchClause = CatchBlockRule(ref endErrorStatement, ref errorAsts)) is not null) { catches.Add(catchClause); } @@ -5598,12 +5598,12 @@ private StatementAst TryStatementRule(Token tryToken) ParserStrings.MissingCatchOrFinally); } - if (endErrorStatement != null) + if (endErrorStatement is not null) { return new ErrorStatementAst(ExtentOf(tryToken, endErrorStatement), GetNestedErrorAsts(body, catches, errorAsts)); } - return new TryStatementAst(ExtentOf(tryToken, finallyBlock != null ? finallyBlock.Extent : catches.Last().Extent), + return new TryStatementAst(ExtentOf(tryToken, finallyBlock is not null ? finallyBlock.Extent : catches.Last().Extent), body, catches, finallyBlock); } @@ -5624,7 +5624,7 @@ private StatementAst DataStatementRule(Token dataToken) IScriptExtent endErrorStatement = null; SkipNewlines(); var dataVariableNameAst = SimpleNameRule(); - string dataVariableName = (dataVariableNameAst != null) ? dataVariableNameAst.Value : null; + string dataVariableName = (dataVariableNameAst is not null) ? dataVariableNameAst.Value : null; SkipNewlines(); Token supportedCommandToken = PeekToken(); @@ -5662,7 +5662,7 @@ private StatementAst DataStatementRule(Token dataToken) ParserStrings.MissingValueForSupportedCommandInDataSectionStatement); } - endErrorStatement = commaToken != null ? commaToken.Extent : supportedCommandToken.Extent; + endErrorStatement = commaToken is not null ? commaToken.Extent : supportedCommandToken.Extent; break; } @@ -5687,7 +5687,7 @@ private StatementAst DataStatementRule(Token dataToken) { // ErrorRecovery: return an error statement. - endErrorStatement = commands != null + endErrorStatement = commands is not null ? commands.Last().Extent : ExtentFromFirstOf(dataVariableNameAst, dataToken); ReportIncompleteInput(After(endErrorStatement), @@ -5696,7 +5696,7 @@ private StatementAst DataStatementRule(Token dataToken) } } - if (endErrorStatement != null) + if (endErrorStatement is not null) { return new ErrorStatementAst(ExtentOf(dataToken, endErrorStatement), GetNestedErrorAsts(commands)); } @@ -5736,7 +5736,7 @@ private PipelineBaseAst PipelineChainRule() { SetTokenizerMode(TokenizerMode.Expression); expr = ExpressionRule(); - if (expr != null) + if (expr is not null) { // We peek here because we are in expression mode, otherwise =0 will get scanned // as a single token. @@ -5754,7 +5754,7 @@ private PipelineBaseAst PipelineChainRule() } // If we have an assign token, deal with assignment - if (expr != null && assignToken != null) + if (expr is not null && assignToken is not null) { SkipNewlines(); StatementAst statement = StatementRule(); @@ -5794,7 +5794,7 @@ private PipelineBaseAst PipelineChainRule() // in enclosing calls to PipelineChainRule PipelineAst nextPipeline; Token firstPipelineToken = null; - if (startExpression != null) + if (startExpression is not null) { nextPipeline = (PipelineAst)PipelineRule(startExpression); startExpression = null; @@ -5966,7 +5966,7 @@ private PipelineBaseAst PipelineRule( } } - if (expr != null) + if (expr is not null) { if (pipelineElements.Count > 0) { @@ -5980,7 +5980,7 @@ private PipelineBaseAst PipelineRule( RedirectionAst[] redirections = null; var redirectionToken = PeekToken() as RedirectionToken; RedirectionAst lastRedirection = null; - while (redirectionToken != null) + while (redirectionToken is not null) { SkipToken(); @@ -5995,18 +5995,18 @@ private PipelineBaseAst PipelineRule( redirectionToken = PeekToken() as RedirectionToken; } - var exprExtent = lastRedirection != null ? ExtentOf(expr, lastRedirection) : expr.Extent; + var exprExtent = lastRedirection is not null ? ExtentOf(expr, lastRedirection) : expr.Extent; commandAst = new CommandExpressionAst( exprExtent, expr, - redirections?.Where(r => r != null)); + redirections?.Where(r => r is not null)); } else { commandAst = (CommandAst)CommandRule(forDynamicKeyword: false); } - if (commandAst != null) + if (commandAst is not null) { if (startExtent is null) { @@ -6021,7 +6021,7 @@ private PipelineBaseAst PipelineRule( // If the first pipe element is null, the position points to the pipe (ideally it would // point before, but the pipe could be the first character), otherwise the empty element // is after the pipe character. - IScriptExtent errorPosition = nextToken != null ? After(nextToken) : PeekToken().Extent; + IScriptExtent errorPosition = nextToken is not null ? After(nextToken) : PeekToken().Extent; ReportIncompleteInput( errorPosition, nameof(ParserStrings.EmptyPipeElement), @@ -6118,7 +6118,7 @@ private RedirectionAst RedirectionRule(RedirectionToken redirectionToken, Redire RedirectionAst result; var fileRedirectionToken = redirectionToken as FileRedirectionToken; - if (fileRedirectionToken != null || (redirectionToken is InputRedirectionToken)) + if (fileRedirectionToken is not null || (redirectionToken is InputRedirectionToken)) { // get location var filename = GetSingleCommandArgument(CommandArgumentContext.FileName); @@ -6293,7 +6293,7 @@ private ExpressionAst GetCommandArgument(CommandArgumentContext context, Token t case TokenKind.LCurly: UngetToken(token); exprAst = PrimaryExpressionRule(withMemberAccess: true); - Diagnostics.Assert(exprAst != null, "PrimaryExpressionRule should never return null"); + Diagnostics.Assert(exprAst is not null, "PrimaryExpressionRule should never return null"); break; case TokenKind.Generic: @@ -6306,7 +6306,7 @@ private ExpressionAst GetCommandArgument(CommandArgumentContext context, Token t var expandableToken = genericToken as StringExpandableToken; // A command name w/o invocation operator is not expandable even if the token has expandable parts // If we have seen an invocation operator, the command name is expandable. - if (expandableToken != null && context != CommandArgumentContext.CommandName) + if (expandableToken is not null && context != CommandArgumentContext.CommandName) { var nestedExpressions = ParseNestedExpressions(expandableToken); exprAst = new ExpandableStringExpressionAst(expandableToken, expandableToken.Value, @@ -6377,9 +6377,9 @@ private ExpressionAst GetCommandArgument(CommandArgumentContext context, Token t token = NextToken(); } - Diagnostics.Assert(commandArgs != null || exprAst != null, "How did that happen?"); + Diagnostics.Assert(commandArgs is not null || exprAst is not null, "How did that happen?"); - if (commandArgs != null) + if (commandArgs is not null) { commandArgs.Add(exprAst); return new ArrayLiteralAst(ExtentOf(commandArgs[0], commandArgs[commandArgs.Count - 1]), commandArgs); @@ -6569,13 +6569,13 @@ internal Ast CommandRule(bool forDynamicKeyword) // If this is the special verbatim argument syntax, look for the next element StringToken argumentToken = token as StringToken; - if ((argumentToken != null) && string.Equals(argumentToken.Value, VERBATIM_ARGUMENT, StringComparison.OrdinalIgnoreCase)) + if ((argumentToken is not null) && string.Equals(argumentToken.Value, VERBATIM_ARGUMENT, StringComparison.OrdinalIgnoreCase)) { elements.Add(ast); endExtent = ast.Extent; var verbatimToken = GetVerbatimCommandArgumentToken(); - if (verbatimToken != null) + if (verbatimToken is not null) { foundVerbatimArgument = true; scanning = false; @@ -6630,7 +6630,7 @@ internal Ast CommandRule(bool forDynamicKeyword) return new CommandAst(ExtentOf(firstToken, endExtent), elements, dotSource || ampersand ? firstToken.Kind : TokenKind.Unknown, - redirections != null ? redirections.Where(r => r != null) : null); + redirections is not null ? redirections.Where(r => r is not null) : null); } #endregion Pipelines @@ -6804,7 +6804,7 @@ private ExpressionAst BinaryExpressionRule(bool endNumberOnTernaryOpChars = fals if (!token.Kind.HasTrait(TokenFlags.BinaryOperator)) { paramToken = token as ParameterToken; - if (paramToken != null) + if (paramToken is not null) { return ErrorRecoveryParameterInExpression(paramToken, expr); } @@ -6886,7 +6886,7 @@ private ExpressionAst BinaryExpressionRule(bool endNumberOnTernaryOpChars = fals rhs = new BinaryExpressionAst(ExtentOf(lhs, rhs), lhs, token.Kind, rhs, token.Extent); } - if (paramToken != null) + if (paramToken is not null) { return ErrorRecoveryParameterInExpression(paramToken, rhs); } @@ -7013,7 +7013,7 @@ private ExpressionAst UnaryExpressionRule(bool endNumberOnTernaryOpChars = false _tokenizer.AllowSignedNumbers = true; _tokenizer.ForceEndNumberOnTernaryOpChars = endNumberOnTernaryOpChars; - if (_ungotToken != null) + if (_ungotToken is not null) { // Possibly a signed number. Need to resync. bool needResync = _ungotToken.Kind == TokenKind.Minus; @@ -7051,7 +7051,7 @@ private ExpressionAst UnaryExpressionRule(bool endNumberOnTernaryOpChars = false // We have seen a unary operator token and now expecting an expression. child = UnaryExpressionRule(endNumberOnTernaryOpChars: true); - if (child != null) + if (child is not null) { if (token.Kind == TokenKind.Comma) { @@ -7117,8 +7117,8 @@ private ExpressionAst UnaryExpressionRule(bool endNumberOnTernaryOpChars = false // If we've looked ahead, don't go looking for a member access token, we've already issued an error, // just assume we're not trying to access a member. - var memberAccessToken = _ungotToken != null ? null : NextMemberAccessToken(false); - if (memberAccessToken != null) + var memberAccessToken = _ungotToken is not null ? null : NextMemberAccessToken(false); + if (memberAccessToken is not null) { expr = CheckPostPrimaryExpressionOperators( memberAccessToken, @@ -7131,7 +7131,7 @@ private ExpressionAst UnaryExpressionRule(bool endNumberOnTernaryOpChars = false { // We are now expecting a child expression. child = UnaryExpressionRule(endNumberOnTernaryOpChars: true); - if (child != null) + if (child is not null) { expr = new ConvertExpressionAst( ExtentOf(lastAttribute, child), @@ -7150,7 +7150,7 @@ private ExpressionAst UnaryExpressionRule(bool endNumberOnTernaryOpChars = false { var typeConstraint = attributes[i] as TypeConstraintAst; - expr = typeConstraint != null + expr = typeConstraint is not null ? new ConvertExpressionAst(ExtentOf(typeConstraint, expr), typeConstraint, expr) : new AttributedExpressionAst(ExtentOf(attributes[i], expr), attributes[i], expr); } @@ -7160,7 +7160,7 @@ private ExpressionAst UnaryExpressionRule(bool endNumberOnTernaryOpChars = false expr = PrimaryExpressionRule(withMemberAccess: true); } - if (expr != null) + if (expr is not null) { token = PeekToken(); TokenKind operation = (token.Kind == TokenKind.PlusPlus) @@ -7271,7 +7271,7 @@ private ExpressionAst CheckUsingVariable(VariableToken variableToken, bool withM private ExpressionAst CheckPostPrimaryExpressionOperators(Token token, ExpressionAst expr) { - while (token != null) + while (token is not null) { // To support fluent style programming, allow newlines after the member access operator. SkipNewlines(); @@ -7582,7 +7582,7 @@ private List ParseNestedExpressions(StringExpandableToken expanda ExpressionAst exprAst; var varToken = token as VariableToken; - if (varToken != null) + if (varToken is not null) { exprAst = CheckUsingVariable(varToken, false); if (_savingTokens) { newNestedTokens.Add(varToken); } @@ -7631,7 +7631,7 @@ private ExpressionAst ExpandableStringRule(StringExpandableToken strToken) ExpressionAst expr; // We need to scan the nested tokens even if there was some error. This is used by the tab completion: "pshome is $psh - if (strToken.NestedTokens != null) + if (strToken.NestedTokens is not null) { List nestedExpressions = ParseNestedExpressions(strToken); expr = new ExpandableStringExpressionAst(strToken, strToken.Value, strToken.FormatString, nestedExpressions); @@ -7654,7 +7654,7 @@ private ExpressionAst MemberNameRule() // G value ExpressionAst simpleName = SimpleNameRule(); - if (simpleName != null) + if (simpleName is not null) { return simpleName; } @@ -7692,7 +7692,7 @@ private ExpressionAst MemberAccessRule(ExpressionAst targetExpr, Token operatorT else { Token lParen = NextInvokeMemberToken(); - if (lParen != null) + if (lParen is not null) { Diagnostics.Assert(lParen.Kind == TokenKind.LParen || lParen.Kind == TokenKind.LCurly, "token kind incorrect"); Diagnostics.Assert(member.Extent.EndColumnNumber == lParen.Extent.StartColumnNumber, @@ -7772,7 +7772,7 @@ private List InvokeParamParenListRule(Token lParen, out IScriptEx ExpressionAst argument = ExpressionRule(); if (argument is null) { - if (comma != null) + if (comma is not null) { // ErrorRecovery: sync at closing paren or newline. @@ -7893,7 +7893,7 @@ private void SaveError(IScriptExtent extent, string errorId, string errorMsg, bo { AssertErrorIdCorrespondsToMsgString(errorId, errorMsg); - if (args != null && args.Length > 0) + if (args is not null && args.Length > 0) { errorMsg = string.Format(CultureInfo.CurrentCulture, errorMsg, args); } @@ -8017,11 +8017,11 @@ internal void ReportError(ParseError error) private void ReportErrorsAsWarnings(Collection errors) { var executionContext = Runspaces.Runspace.DefaultRunspace.ExecutionContext; - if (executionContext != null && executionContext.InternalHost != null && executionContext.InternalHost.UI != null) + if (executionContext is not null && executionContext.InternalHost is not null && executionContext.InternalHost.UI is not null) { foreach (var error in errors) { - if (error != null) + if (error is not null) { executionContext.InternalHost.UI.WriteWarningLine(error.ToString()); } @@ -8051,7 +8051,7 @@ public ParseError(IScriptExtent extent, string errorId, string message) internal ParseError(IScriptExtent extent, string errorId, string message, bool incompleteInput) { - Diagnostics.Assert(extent != null, "can't have a null position for a parse error"); + Diagnostics.Assert(extent is not null, "can't have a null position for a parse error"); Diagnostics.Assert(!string.IsNullOrEmpty(message), "can't have a null error message"); Diagnostics.Assert(!string.IsNullOrEmpty(errorId), "can't have a null error id"); diff --git a/src/System.Management.Automation/engine/parser/Position.cs b/src/System.Management.Automation/engine/parser/Position.cs index 91a284d4c71..4f67d385edf 100644 --- a/src/System.Management.Automation/engine/parser/Position.cs +++ b/src/System.Management.Automation/engine/parser/Position.cs @@ -296,7 +296,7 @@ internal static IScriptExtent NewScriptExtent(IScriptExtent start, IScriptExtent InternalScriptExtent startExtent = start as InternalScriptExtent; InternalScriptExtent endExtent = end as InternalScriptExtent; - Diagnostics.Assert(startExtent != null && endExtent != null, "This function only handles internal and empty extents"); + Diagnostics.Assert(startExtent is not null && endExtent is not null, "This function only handles internal and empty extents"); Diagnostics.Assert(startExtent.PositionHelper == endExtent.PositionHelper, "Extents must be from same source"); return new InternalScriptExtent(startExtent.PositionHelper, startExtent.StartOffset, endExtent.EndOffset); diff --git a/src/System.Management.Automation/engine/parser/PreOrderVisitor.cs b/src/System.Management.Automation/engine/parser/PreOrderVisitor.cs index b865a76ee40..f6e144f9453 100644 --- a/src/System.Management.Automation/engine/parser/PreOrderVisitor.cs +++ b/src/System.Management.Automation/engine/parser/PreOrderVisitor.cs @@ -37,7 +37,7 @@ public abstract class AstVisitor internal AstVisitAction CheckForPostAction(Ast ast, AstVisitAction action) { var postActionHandler = this as IAstPostVisitHandler; - if (postActionHandler != null) + if (postActionHandler is not null) { postActionHandler.PostVisit(ast); } diff --git a/src/System.Management.Automation/engine/parser/SafeValues.cs b/src/System.Management.Automation/engine/parser/SafeValues.cs index 7a0ddffbeba..9fad69fc245 100644 --- a/src/System.Management.Automation/engine/parser/SafeValues.cs +++ b/src/System.Management.Automation/engine/parser/SafeValues.cs @@ -203,7 +203,7 @@ public object VisitStatementBlock(StatementBlockAst statementBlockAst) public object VisitPipeline(PipelineAst pipelineAst) { var expr = pipelineAst.GetPureExpression(); - return expr != null && (bool)expr.Accept(this); + return expr is not null && (bool)expr.Accept(this); } public object VisitTernaryExpression(TernaryExpressionAst ternaryExpressionAst) @@ -483,7 +483,7 @@ public static object GetSafeValue(Ast ast, ExecutionContext context, SafeValueCo private object GetSingleValueFromTarget(object target, object index) { var targetString = target as string; - if (targetString != null) + if (targetString is not null) { var offset = (int)index; if (Math.Abs(offset) >= targetString.Length) @@ -495,7 +495,7 @@ private object GetSingleValueFromTarget(object target, object index) } var targetArray = target as object[]; - if (targetArray != null) + if (targetArray is not null) { // this can throw, that just gets percolated back var offset = (int)index; @@ -508,7 +508,7 @@ private object GetSingleValueFromTarget(object target, object index) } var targetHashtable = target as Hashtable; - if (targetHashtable != null) + if (targetHashtable is not null) { return targetHashtable[index]; } @@ -520,7 +520,7 @@ private object GetSingleValueFromTarget(object target, object index) private object GetIndexedValueFromTarget(object target, object index) { var indexArray = index as object[]; - return indexArray != null ? ((object[])indexArray).Select(i => GetSingleValueFromTarget(target, i)).ToArray() : GetSingleValueFromTarget(target, index); + return indexArray is not null ? ((object[])indexArray).Select(i => GetSingleValueFromTarget(target, i)).ToArray() : GetSingleValueFromTarget(target, index); } public object VisitIndexExpression(IndexExpressionAst indexExpressionAst) @@ -541,7 +541,7 @@ public object VisitExpandableStringExpression(ExpandableStringExpressionAst expa object[] safeValues = new object[expandableStringExpressionAst.NestedExpressions.Count]; // retrieve OFS, and if it doesn't exist set it to space string ofs = null; - if (t_context != null) + if (t_context is not null) { ofs = t_context.SessionState.PSVariable.GetValue("OFS") as string; } @@ -578,7 +578,7 @@ public object VisitExpandableStringExpression(ExpandableStringExpressionAst expa // Also, this will not call any script implementations of ToString (ala types.clixml) // This *will* result in a different result in those cases. However, to execute some // arbitrary script at this stage would be opening ourselves up to an attack - if (resultArray != null) + if (resultArray is not null) { object[] subExpressionResult = new object[resultArray.Length]; for (int subExpressionOffset = 0; @@ -587,7 +587,7 @@ public object VisitExpandableStringExpression(ExpandableStringExpressionAst expa { // check to see if there is an array in our array, object[] subResult = resultArray[subExpressionOffset] as object[]; - if (subResult != null) + if (subResult is not null) { subExpressionResult[subExpressionOffset] = string.Join(ofs, subResult); } @@ -613,11 +613,11 @@ public object VisitStatementBlock(StatementBlockAst statementBlockAst) ArrayList statementList = new ArrayList(); foreach (var statement in statementBlockAst.Statements) { - if (statement != null) + if (statement is not null) { var obj = statement.Accept(this); var enumerator = LanguagePrimitives.GetEnumerator(obj); - if (enumerator != null) + if (enumerator is not null) { while (enumerator.MoveNext()) { @@ -641,7 +641,7 @@ public object VisitStatementBlock(StatementBlockAst statementBlockAst) public object VisitPipeline(PipelineAst pipelineAst) { var expr = pipelineAst.GetPureExpression(); - if (expr != null) + if (expr is not null) { return expr.Accept(this); } @@ -737,7 +737,7 @@ public object VisitVariableExpression(VariableExpressionAst variableExpressionAs return Path.GetDirectoryName(scriptFileName); } - if (t_context != null) + if (t_context is not null) { return VariableOps.GetVariableValue(variableExpressionAst.VariablePath, t_context, variableExpressionAst); } diff --git a/src/System.Management.Automation/engine/parser/SemanticChecks.cs b/src/System.Management.Automation/engine/parser/SemanticChecks.cs index 1e87ff9e3d4..3c29ef6d980 100644 --- a/src/System.Management.Automation/engine/parser/SemanticChecks.cs +++ b/src/System.Management.Automation/engine/parser/SemanticChecks.cs @@ -59,7 +59,7 @@ private bool AnalyzingStaticMember() } var fnMemberAst = currentMember as FunctionMemberAst; - return fnMemberAst != null ? fnMemberAst.IsStatic : ((PropertyMemberAst)currentMember).IsStatic; + return fnMemberAst is not null ? fnMemberAst.IsStatic : ((PropertyMemberAst)currentMember).IsStatic; } private bool IsValidAttributeArgument(Ast ast, IsConstantValueVisitor visitor) @@ -102,7 +102,7 @@ private void CheckForDuplicateParameters(ReadOnlyCollection parame var voidConstraint = parameter.Attributes.OfType().FirstOrDefault(t => typeof(void) == t.TypeName.GetReflectionType()); - if (voidConstraint != null) + if (voidConstraint is not null) { _parser.ReportError(voidConstraint.Extent, nameof(ParserStrings.VoidTypeConstraintNotAllowed), @@ -135,7 +135,7 @@ public override AstVisitAction VisitAttribute(AttributeAst attributeAst) var parent = attributeAst.Parent; TypeDefinitionAst typeDefinitionAst = parent as TypeDefinitionAst; - if (typeDefinitionAst != null) + if (typeDefinitionAst is not null) { checkingAttributeOnClass = true; attributeTargets = typeDefinitionAst.IsClass @@ -152,7 +152,7 @@ public override AstVisitAction VisitAttribute(AttributeAst attributeAst) else { var functionMemberAst = parent as FunctionMemberAst; - if (functionMemberAst != null) + if (functionMemberAst is not null) { checkingAttributeOnClass = true; attributeTargets = functionMemberAst.IsConstructor @@ -182,7 +182,7 @@ public override AstVisitAction VisitAttribute(AttributeAst attributeAst) else { var usage = attributeType.GetCustomAttribute(true); - if (usage != null && (usage.ValidOn & attributeTargets) == 0) + if (usage is not null && (usage.ValidOn & attributeTargets) == 0) { _parser.ReportError(attributeAst.Extent, nameof(ParserStrings.AttributeNotAllowedOnDeclaration), @@ -210,7 +210,7 @@ public override AstVisitAction VisitAttribute(AttributeAst attributeAst) } var propertyInfo = members[0] as PropertyInfo; - if (propertyInfo != null) + if (propertyInfo is not null) { if (propertyInfo.GetSetMethod() is null) { @@ -276,7 +276,7 @@ private static string GetValidNamedAttributeProperties(Type attributeType) for (int i = 0; i < properties.Length; i++) { PropertyInfo propertyInfo = properties[i]; - if (propertyInfo.GetSetMethod() != null) + if (propertyInfo.GetSetMethod() is not null) { propertyNames.Add(propertyInfo.Name); } @@ -383,7 +383,7 @@ public override AstVisitAction VisitTypeDefinition(TypeDefinitionAst typeDefinit } } - if (dscResourceAttributeAst != null) + if (dscResourceAttributeAst is not null) { DscResourceChecker.CheckType(_parser, typeDefinitionAst, dscResourceAttributeAst); } @@ -396,16 +396,16 @@ public override AstVisitAction VisitFunctionMember(FunctionMemberAst functionMem _memberScopeStack.Push(functionMemberAst); var body = functionMemberAst.Body; - if (body.ParamBlock != null) + if (body.ParamBlock is not null) { _parser.ReportError(body.ParamBlock.Extent, nameof(ParserStrings.ParamBlockNotAllowedInMethod), ParserStrings.ParamBlockNotAllowedInMethod); } - if (body.BeginBlock != null || - body.ProcessBlock != null || - body.DynamicParamBlock != null || + if (body.BeginBlock is not null || + body.ProcessBlock is not null || + body.DynamicParamBlock is not null || !body.EndBlock.Unnamed) { _parser.ReportError(Parser.ExtentFromFirstOf(body.DynamicParamBlock, body.BeginBlock, body.ProcessBlock, body.EndBlock), @@ -413,7 +413,7 @@ public override AstVisitAction VisitFunctionMember(FunctionMemberAst functionMem ParserStrings.NamedBlockNotAllowedInMethod); } - if (functionMemberAst.IsConstructor && functionMemberAst.ReturnType != null) + if (functionMemberAst.IsConstructor && functionMemberAst.ReturnType is not null) { _parser.ReportError(functionMemberAst.ReturnType.Extent, nameof(ParserStrings.ConstructorCantHaveReturnType), @@ -434,14 +434,14 @@ public override AstVisitAction VisitFunctionMember(FunctionMemberAst functionMem public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst) { - if (functionDefinitionAst.Parameters != null - && functionDefinitionAst.Body.ParamBlock != null) + if (functionDefinitionAst.Parameters is not null + && functionDefinitionAst.Body.ParamBlock is not null) { _parser.ReportError(functionDefinitionAst.Body.ParamBlock.Extent, nameof(ParserStrings.OnlyOneParameterListAllowed), ParserStrings.OnlyOneParameterListAllowed); } - else if (functionDefinitionAst.Parameters != null) + else if (functionDefinitionAst.Parameters is not null) { CheckForDuplicateParameters(functionDefinitionAst.Parameters); } @@ -504,7 +504,7 @@ public override AstVisitAction VisitForEachStatement(ForEachStatementAst forEach "parallel"); } - if (forEachStatementAst.ThrottleLimit != null) + if (forEachStatementAst.ThrottleLimit is not null) { _parser.ReportError( forEachStatementAst.Extent, @@ -515,7 +515,7 @@ public override AstVisitAction VisitForEachStatement(ForEachStatementAst forEach } // Throttle limit must be combined with Parallel flag - if ((forEachStatementAst.ThrottleLimit != null) && + if ((forEachStatementAst.ThrottleLimit is not null) && ((forEachStatementAst.Flags & ForEachFlags.Parallel) != ForEachFlags.Parallel)) { _parser.ReportError( @@ -591,7 +591,7 @@ private void CheckLabelExists(StatementAst ast, string label) } Ast parent; - for (parent = ast.Parent; parent != null; parent = parent.Parent) + for (parent = ast.Parent; parent is not null; parent = parent.Parent) { if (parent is FunctionDefinitionAst) { @@ -607,7 +607,7 @@ private void CheckLabelExists(StatementAst ast, string label) } var loop = parent as LoopStatementAst; - if (loop != null) + if (loop is not null) { if (LoopFlowException.MatchLoopLabel(label, loop.Label ?? string.Empty)) break; @@ -625,7 +625,7 @@ private void CheckLabelExists(StatementAst ast, string label) private void CheckForFlowOutOfFinally(Ast ast, string label) { Ast parent; - for (parent = ast.Parent; parent != null; parent = parent.Parent) + for (parent = ast.Parent; parent is not null; parent = parent.Parent) { if (parent is NamedBlockAst || parent is TrapStatementAst || parent is ScriptBlockAst) { @@ -638,17 +638,17 @@ private void CheckForFlowOutOfFinally(Ast ast, string label) // If label is not null, we have a break/continue where we know the loop label at compile // time. If we can match the label before finding the finally, then we're not flowing out // of the finally. - if (label != null && parent is LabeledStatementAst) + if (label is not null && parent is LabeledStatementAst) { if (LoopFlowException.MatchLoopLabel(label, ((LabeledStatementAst)parent).Label ?? string.Empty)) break; } var stmtBlock = parent as StatementBlockAst; - if (stmtBlock != null) + if (stmtBlock is not null) { var tryStatementAst = stmtBlock.Parent as TryStatementAst; - if (tryStatementAst != null && tryStatementAst.Finally == stmtBlock) + if (tryStatementAst is not null && tryStatementAst.Finally == stmtBlock) { _parser.ReportError(ast.Extent, nameof(ParserStrings.ControlLeavingFinally), @@ -669,7 +669,7 @@ private static string GetLabel(ExpressionAst expr) } var str = expr as StringConstantExpressionAst; - return str != null ? str.Value : null; + return str is not null ? str.Value : null; } public override AstVisitAction VisitBreakStatement(BreakStatementAst breakStatementAst) @@ -698,7 +698,7 @@ private void CheckForReturnStatement(ReturnStatementAst ast) return; } - if (ast.Pipeline != null) + if (ast.Pipeline is not null) { if (functionMemberAst.IsReturnTypeVoid()) { @@ -735,7 +735,7 @@ private void CheckAssignmentTarget(ExpressionAst ast, bool simpleAssignment, Act { ArrayLiteralAst arrayLiteralAst = ast as ArrayLiteralAst; Ast errorAst = null; - if (arrayLiteralAst != null) + if (arrayLiteralAst is not null) { if (simpleAssignment) { @@ -749,7 +749,7 @@ private void CheckAssignmentTarget(ExpressionAst ast, bool simpleAssignment, Act else { ParenExpressionAst parenExpressionAst = ast as ParenExpressionAst; - if (parenExpressionAst != null) + if (parenExpressionAst is not null) { ExpressionAst expr = parenExpressionAst.Pipeline.GetPureExpression(); if (expr is null) @@ -783,7 +783,7 @@ private void CheckAssignmentTarget(ExpressionAst ast, bool simpleAssignment, Act while (expr is AttributedExpressionAst) { var convertExpr = expr as ConvertExpressionAst; - if (convertExpr != null) + if (convertExpr is not null) { converts += 1; lastConvertType = convertExpr.Type.TypeName.GetReflectionType(); @@ -802,7 +802,7 @@ private void CheckAssignmentTarget(ExpressionAst ast, bool simpleAssignment, Act expr = ((AttributedExpressionAst)expr).Child; } - if ((errorPosition != null) && converts > 1) + if ((errorPosition is not null) && converts > 1) { _parser.ReportError(errorPosition, nameof(ParserStrings.ReferenceNeedsToBeByItselfInTypeConstraint), @@ -811,7 +811,7 @@ private void CheckAssignmentTarget(ExpressionAst ast, bool simpleAssignment, Act else { var varExprAst = expr as VariableExpressionAst; - if (varExprAst != null) + if (varExprAst is not null) { var varPath = varExprAst.VariablePath; if (varPath.IsVariable && varPath.IsAnyLocal()) @@ -844,7 +844,7 @@ private void CheckAssignmentTarget(ExpressionAst ast, bool simpleAssignment, Act } } - if (errorAst != null) + if (errorAst is not null) { reportError(errorAst); } @@ -927,10 +927,10 @@ public override AstVisitAction VisitConvertExpression(ConvertExpressionAst conve while (true) { var childAttrExpr = child as AttributedExpressionAst; - if (childAttrExpr != null) + if (childAttrExpr is not null) { var childConvert = childAttrExpr as ConvertExpressionAst; - if (childConvert != null && typeof(PSReference) == childConvert.Type.TypeName.GetReflectionType()) + if (childConvert is not null && typeof(PSReference) == childConvert.Type.TypeName.GetReflectionType()) { multipleRefs = true; _parser.ReportError(childConvert.Type.Extent, @@ -947,10 +947,10 @@ public override AstVisitAction VisitConvertExpression(ConvertExpressionAst conve // Check for [int][ref], but don't add an extra error for [ref][ref]. var parent = convertExpressionAst.Parent as AttributedExpressionAst; - while (parent != null) + while (parent is not null) { var parentConvert = parent as ConvertExpressionAst; - if (parentConvert != null && !multipleRefs) + if (parentConvert is not null && !multipleRefs) { if (typeof(PSReference) == parentConvert.Type.TypeName.GetReflectionType()) { @@ -961,12 +961,12 @@ public override AstVisitAction VisitConvertExpression(ConvertExpressionAst conve // that is checked as part of assignment. var ast = parent.Parent; bool skipError = false; - while (ast != null) + while (ast is not null) { var statementAst = ast as AssignmentStatementAst; - if (statementAst != null) + if (statementAst is not null) { - skipError = statementAst.Left.Find(ast1 => ast1 == convertExpressionAst, searchNestedScriptBlocks: true) != null; + skipError = statementAst.Left.Find(ast1 => ast1 == convertExpressionAst, searchNestedScriptBlocks: true) is not null; break; } @@ -1007,7 +1007,7 @@ public override AstVisitAction VisitUsingExpression(UsingExpressionAst usingExpr var exprAst = usingExpressionAst.SubExpression; var badExpr = CheckUsingExpression(exprAst); - if (badExpr != null) + if (badExpr is not null) { _parser.ReportError(badExpr.Extent, nameof(ParserStrings.InvalidUsingExpression), @@ -1026,13 +1026,13 @@ private ExpressionAst CheckUsingExpression(ExpressionAst exprAst) } var memberExpr = exprAst as MemberExpressionAst; - if (memberExpr != null && !(memberExpr is InvokeMemberExpressionAst) && (memberExpr.Member is StringConstantExpressionAst)) + if (memberExpr is not null && !(memberExpr is InvokeMemberExpressionAst) && (memberExpr.Member is StringConstantExpressionAst)) { return CheckUsingExpression(memberExpr.Expression); } var indexExpr = exprAst as IndexExpressionAst; - if (indexExpr != null) + if (indexExpr is not null) { if (!IsValidAttributeArgument(indexExpr.Index, s_isConstantAttributeArgVisitor)) { @@ -1100,7 +1100,7 @@ public override AstVisitAction VisitHashtable(HashtableAst hashtableAst) foreach (var entry in hashtableAst.KeyValuePairs) { var keyStrAst = entry.Item1 as ConstantExpressionAst; - if (keyStrAst != null) + if (keyStrAst is not null) { var keyStr = keyStrAst.Value.ToString(); if (keys.Contains(keyStr)) @@ -1134,7 +1134,7 @@ public override AstVisitAction VisitAttributedExpression(AttributedExpressionAst { // The attribute (and not the entire expression) is used for the error extent. var errorAst = attributedExpressionAst.Attribute; - while (attributedExpressionAst != null) + while (attributedExpressionAst is not null) { if (attributedExpressionAst.Child is VariableExpressionAst) { @@ -1202,7 +1202,7 @@ private void MarkAstParentsAsSuspicious(Ast ast) Ast targetAst = ast; var parent = ast; - while (parent != null) + while (parent is not null) { targetAst = parent; targetAst.HasSuspiciousContent = true; @@ -1242,18 +1242,18 @@ public override AstVisitAction VisitScriptBlockExpression(ScriptBlockExpressionA // "SomeDSCResource" followed by a ScriptBlockExpressionAst. Following code check if there are patterns // that one ScriptBlockExpressionAst follows a CommandAst, and report Parser error(s) if true. // - if (configAst != null) + if (configAst is not null) { var ast = scriptBlockExpressionAst.Parent; // Traverse all ancestor ast to find NamedBlockAst PipelineAst statementAst = null; // The nearest ancestor PipelineAst of the 'scriptBlockExpressionAst' int ancestorNodeLevel = 0; // The nearest ancestor PipelineAst should be two level above the 'scriptBlockExpressionAst' - while ((ast != null) && (ancestorNodeLevel <= 2)) + while ((ast is not null) && (ancestorNodeLevel <= 2)) { // // Find nearest ancestor NamedBlockAst // var namedBlockedAst = ast as NamedBlockAst; - if ((namedBlockedAst != null) && (statementAst != null) && (ancestorNodeLevel == 2)) + if ((namedBlockedAst is not null) && (statementAst is not null) && (ancestorNodeLevel == 2)) { int index = namedBlockedAst.Statements.IndexOf(statementAst); if (index > 0) @@ -1262,17 +1262,17 @@ public override AstVisitAction VisitScriptBlockExpression(ScriptBlockExpressionA // Check if previous Statement is CommandAst // var pipelineAst = namedBlockedAst.Statements[index - 1] as PipelineAst; - if (pipelineAst != null && pipelineAst.PipelineElements.Count == 1) + if (pipelineAst is not null && pipelineAst.PipelineElements.Count == 1) { var commandAst = pipelineAst.PipelineElements[0] as CommandAst; - if (commandAst != null && + if (commandAst is not null && commandAst.CommandElements.Count <= 2 && commandAst.DefiningKeyword is null) { // Here indicates a CommandAst followed by a ScriptBlockExpression, // which is invalid if the DSC resource is not defined var commandNameAst = commandAst.CommandElements[0] as StringConstantExpressionAst; - if (commandNameAst != null) + if (commandNameAst is not null) { _parser.ReportError(commandNameAst.Extent, nameof(ParserStrings.ResourceNotDefined), @@ -1301,7 +1301,7 @@ public override AstVisitAction VisitUsingStatement(UsingStatementAst usingStatem usingStatementAst.UsingStatementKind == UsingStatementKind.Assembly || usingStatementAst.UsingStatementKind == UsingStatementKind.Module; if (!usingKindSupported || - usingStatementAst.Alias != null) + usingStatementAst.Alias is not null) { _parser.ReportError(usingStatementAst.Extent, nameof(ParserStrings.UsingStatementNotSupported), @@ -1317,12 +1317,12 @@ public override AstVisitAction VisitConfigurationDefinition(ConfigurationDefinit // Check if the ScriptBlockAst contains NamedBlockAst other than the End block // ScriptBlockAst configBody = configurationDefinitionAst.Body.ScriptBlock; - if (configBody.BeginBlock != null || configBody.ProcessBlock != null || configBody.DynamicParamBlock != null) + if (configBody.BeginBlock is not null || configBody.ProcessBlock is not null || configBody.DynamicParamBlock is not null) { var unsupportedNamedBlocks = new NamedBlockAst[] { configBody.BeginBlock, configBody.ProcessBlock, configBody.DynamicParamBlock }; foreach (NamedBlockAst namedBlock in unsupportedNamedBlocks) { - if (namedBlock != null) + if (namedBlock is not null) { _parser.ReportError(namedBlock.OpenCurlyExtent, nameof(ParserStrings.UnsupportedNamedBlockInConfiguration), @@ -1341,12 +1341,12 @@ public override AstVisitAction VisitDynamicKeywordStatement(DynamicKeywordStatem ////////////////////////////////////////////////////////////////////////////////// // If a custom action was provided. then invoke it ////////////////////////////////////////////////////////////////////////////////// - if (dynamicKeywordStatementAst.Keyword.SemanticCheck != null) + if (dynamicKeywordStatementAst.Keyword.SemanticCheck is not null) { try { ParseError[] errors = dynamicKeywordStatementAst.Keyword.SemanticCheck(dynamicKeywordStatementAst); - if (errors != null && errors.Length > 0) + if (errors is not null && errors.Length > 0) errors.ToList().ForEach(e => _parser.ReportError(e)); } catch (Exception e) @@ -1361,7 +1361,7 @@ public override AstVisitAction VisitDynamicKeywordStatement(DynamicKeywordStatem DynamicKeyword keyword = dynamicKeywordStatementAst.Keyword; HashtableAst hashtable = dynamicKeywordStatementAst.BodyExpression as HashtableAst; - if (hashtable != null) + if (hashtable is not null) { // // If it's a hash table, validate that only valid members have been specified. @@ -1395,10 +1395,10 @@ public override AstVisitAction VisitDynamicKeywordStatement(DynamicKeywordStatem // Check compatibility between DSC Resource and Configuration // ConfigurationDefinitionAst configAst = Ast.GetAncestorAst(dynamicKeywordStatementAst); - if (configAst != null) + if (configAst is not null) { StringConstantExpressionAst nameAst = dynamicKeywordStatementAst.CommandElements[0] as StringConstantExpressionAst; - Diagnostics.Assert(nameAst != null, "nameAst should never be null"); + Diagnostics.Assert(nameAst is not null, "nameAst should never be null"); if (!DscClassCache.SystemResourceNames.Contains(nameAst.Extent.Text.Trim())) { if (configAst.ConfigurationType == ConfigurationType.Meta && !dynamicKeywordStatementAst.Keyword.IsMetaDSCResource()) @@ -1423,12 +1423,12 @@ public override AstVisitAction VisitDynamicKeywordStatement(DynamicKeywordStatem public override AstVisitAction VisitPropertyMember(PropertyMemberAst propertyMemberAst) { - if (propertyMemberAst.PropertyType != null) + if (propertyMemberAst.PropertyType is not null) { // Type must be resolved, but if it's not, the error was reported by the symbol resolver. var type = propertyMemberAst.PropertyType.TypeName.GetReflectionType(); - if (type != null && (type == typeof(void) || type.IsGenericTypeDefinition)) + if (type is not null && (type == typeof(void) || type.IsGenericTypeDefinition)) { _parser.ReportError(propertyMemberAst.PropertyType.Extent, nameof(ParserStrings.TypeNotAllowedForProperty), @@ -1444,7 +1444,7 @@ public override AstVisitAction VisitPropertyMember(PropertyMemberAst propertyMem public void PostVisit(Ast ast) { var scriptBlockAst = ast as ScriptBlockAst; - if (scriptBlockAst != null) + if (scriptBlockAst is not null) { if (scriptBlockAst.Parent is null || scriptBlockAst.Parent is ScriptBlockExpressionAst || !(scriptBlockAst.Parent.Parent is FunctionMemberAst)) { @@ -1482,13 +1482,13 @@ internal static void CheckType(Parser parser, TypeDefinitionAst typeDefinitionAs bool hasNonDefaultCtor = false; bool hasKey = false; - Diagnostics.Assert(dscResourceAttributeAst != null, "CheckType called only for DSC resources. dscResourceAttributeAst must be non-null."); + Diagnostics.Assert(dscResourceAttributeAst is not null, "CheckType called only for DSC resources. dscResourceAttributeAst must be non-null."); foreach (var member in typeDefinitionAst.Members) { var functionMemberAst = member as FunctionMemberAst; - if (functionMemberAst != null) + if (functionMemberAst is not null) { CheckSet(functionMemberAst, ref hasSet); CheckGet(parser, functionMemberAst, ref hasGet); @@ -1513,7 +1513,7 @@ internal static void CheckType(Parser parser, TypeDefinitionAst typeDefinitionAs } } - if (typeDefinitionAst.BaseTypes != null && (!hasSet || !hasGet || !hasTest || !hasKey)) + if (typeDefinitionAst.BaseTypes is not null && (!hasSet || !hasGet || !hasTest || !hasKey)) { LookupRequiredMembers(parser, typeDefinitionAst, ref hasSet, ref hasGet, ref hasTest, ref hasKey); } @@ -1598,7 +1598,7 @@ private static void LookupRequiredMembers(Parser parser, TypeDefinitionAst typeD foreach (var member in baseTypeDefinitionAst.Members) { var functionMemberAst = member as FunctionMemberAst; - if (functionMemberAst != null) + if (functionMemberAst is not null) { CheckSet(functionMemberAst, ref hasSet); CheckGet(parser, functionMemberAst, ref hasGet); @@ -1611,7 +1611,7 @@ private static void LookupRequiredMembers(Parser parser, TypeDefinitionAst typeD } } - if (baseTypeDefinitionAst.BaseTypes != null && (!hasSet || !hasGet || !hasTest || !hasKey)) + if (baseTypeDefinitionAst.BaseTypes is not null && (!hasSet || !hasGet || !hasTest || !hasKey)) { LookupRequiredMembers(parser, baseTypeDefinitionAst, ref hasSet, ref hasGet, ref hasTest, ref hasKey); } @@ -1633,13 +1633,13 @@ private static void CheckGet(Parser parser, FunctionMemberAst functionMemberAst, if (functionMemberAst.Name.Equals("Get", StringComparison.OrdinalIgnoreCase) && functionMemberAst.Parameters.Count == 0) { - if (functionMemberAst.ReturnType != null) + if (functionMemberAst.ReturnType is not null) { // Return type is of the class we're defined in // it must return the class type, or array of the class type. var arrayTypeName = functionMemberAst.ReturnType.TypeName as ArrayTypeName; var typeName = - (arrayTypeName != null ? arrayTypeName.ElementType : functionMemberAst.ReturnType.TypeName) as + (arrayTypeName is not null ? arrayTypeName.ElementType : functionMemberAst.ReturnType.TypeName) as TypeName; if (typeName is null || typeName._typeDefinitionAst != functionMemberAst.Parent) { @@ -1672,7 +1672,7 @@ private static void CheckTest(FunctionMemberAst functionMemberAst, ref bool hasT if (hasTest) return; hasTest = (functionMemberAst.Name.Equals("Test", StringComparison.OrdinalIgnoreCase) && functionMemberAst.Parameters.Count == 0 && - functionMemberAst.ReturnType != null && + functionMemberAst.ReturnType is not null && functionMemberAst.ReturnType.TypeName.GetReflectionType() == typeof(bool)); } /// @@ -1712,20 +1712,20 @@ private static void CheckKey(Parser parser, PropertyMemberAst propertyMemberAst, bool keyPropertyTypeAllowed = false; var propertyType = propertyMemberAst.PropertyType; - if (propertyType != null) + if (propertyType is not null) { TypeName typeName = propertyType.TypeName as TypeName; - if (typeName != null) + if (typeName is not null) { var type = typeName.GetReflectionType(); - if (type != null) + if (type is not null) { keyPropertyTypeAllowed = type == typeof(string) || type.IsInteger(); } else { var typeDefinitionAst = typeName._typeDefinitionAst; - if (typeDefinitionAst != null) + if (typeDefinitionAst is not null) { keyPropertyTypeAllowed = typeDefinitionAst.IsEnum; } @@ -1762,7 +1762,7 @@ internal RestrictedLanguageChecker(Parser parser, IEnumerable allowedCom _parser = parser; _allowedCommands = allowedCommands; - if (allowedVariables != null) + if (allowedVariables is not null) { // A single '*' allows any variable to be used. The use of a single '*' aligns with the // way SessionState.Applications and SessionState.Scripts lists work. diff --git a/src/System.Management.Automation/engine/parser/SymbolResolver.cs b/src/System.Management.Automation/engine/parser/SymbolResolver.cs index 02e1e05af2a..291b058689b 100644 --- a/src/System.Management.Automation/engine/parser/SymbolResolver.cs +++ b/src/System.Management.Automation/engine/parser/SymbolResolver.cs @@ -34,7 +34,7 @@ public TypeLookupResult(TypeDefinitionAst type = null) public bool IsAmbiguous() { - return (ExternalNamespaces != null && ExternalNamespaces.Count > 1); + return (ExternalNamespaces is not null && ExternalNamespaces.Count > 1); } } @@ -66,7 +66,7 @@ internal Scope(TypeDefinitionAst typeDefinition) foreach (var member in typeDefinition.Members) { var propertyMember = member as PropertyMemberAst; - if (propertyMember != null) + if (propertyMember is not null) { // Duplicate members are an error, but we catch that later after all types // have been resolved. We could report errors for properties here, but @@ -85,7 +85,7 @@ internal void AddType(Parser parser, TypeDefinitionAst typeDefinitionAst) TypeLookupResult result; if (_typeTable.TryGetValue(typeDefinitionAst.Name, out result)) { - if (result.ExternalNamespaces != null) + if (result.ExternalNamespaces is not null) { // override external type by the type defined in the current namespace result.ExternalNamespaces = null; @@ -110,7 +110,7 @@ internal void AddTypeFromUsingModule(Parser parser, TypeDefinitionAst typeDefini TypeLookupResult result; if (_typeTable.TryGetValue(typeDefinitionAst.Name, out result)) { - if (result.ExternalNamespaces != null) + if (result.ExternalNamespaces is not null) { // override external type by the type defined in the current namespace result.ExternalNamespaces.Add(moduleInfo.Name); @@ -142,7 +142,7 @@ internal void AddTypeFromUsingModule(Parser parser, TypeDefinitionAst typeDefini internal TypeLookupResult LookupType(TypeName typeName) { - if (typeName.AssemblyName != null) + if (typeName.AssemblyName is not null) { return null; } @@ -230,7 +230,7 @@ public TypeLookupResult LookupType(TypeName typeName) for (int i = _scopes.Count - 1; i >= 0; i--) { result = _scopes[i].LookupType(typeName); - if (result != null) + if (result is not null) break; } @@ -243,7 +243,7 @@ public Ast LookupVariable(VariablePath variablePath) for (int i = _scopes.Count - 1; i >= 0; i--) { result = _scopes[i].LookupVariable(variablePath); - if (result != null) + if (result is not null) break; } @@ -259,7 +259,7 @@ public TypeDefinitionAst GetCurrentTypeDefinitionAst() for (int i = _scopes.Count - 1; i >= 0; i--) { TypeDefinitionAst ast = _scopes[i]._ast as TypeDefinitionAst; - if (ast != null) + if (ast is not null) { return ast; } @@ -291,7 +291,7 @@ private static PowerShell UsingStatementResolvePowerShell // The goal is to re-use runspaces, because creating runspace is an expensive part in creating PowerShell instance. if (t_usingStatementResolvePowerShell is null) { - if (Runspace.DefaultRunspace != null) + if (Runspace.DefaultRunspace is not null) { t_usingStatementResolvePowerShell = PowerShell.Create(RunspaceMode.CurrentRunspace); } @@ -307,7 +307,7 @@ private static PowerShell UsingStatementResolvePowerShell t_usingStatementResolvePowerShell = PowerShell.Create(iss); } } - else if (Runspace.DefaultRunspace != null && t_usingStatementResolvePowerShell.Runspace != Runspace.DefaultRunspace) + else if (Runspace.DefaultRunspace is not null && t_usingStatementResolvePowerShell.Runspace != Runspace.DefaultRunspace) { t_usingStatementResolvePowerShell = PowerShell.Create(RunspaceMode.CurrentRunspace); } @@ -381,10 +381,10 @@ public override AstVisitAction VisitAssignmentStatement(AssignmentStatementAst a { var expression = expressionAst; var variableExpressionAst = expression as VariableExpressionAst; - while (variableExpressionAst is null && expression != null) + while (variableExpressionAst is null && expression is not null) { var convertExpressionAst = expression as ConvertExpressionAst; - if (convertExpressionAst != null) + if (convertExpressionAst is not null) { expression = convertExpressionAst.Child; variableExpressionAst = convertExpressionAst.Child as VariableExpressionAst; @@ -395,16 +395,16 @@ public override AstVisitAction VisitAssignmentStatement(AssignmentStatementAst a } } - if (variableExpressionAst != null && variableExpressionAst.VariablePath.IsVariable) + if (variableExpressionAst is not null && variableExpressionAst.VariablePath.IsVariable) { var ast = _symbolTable.LookupVariable(variableExpressionAst.VariablePath); var propertyMember = ast as PropertyMemberAst; - if (propertyMember != null) + if (propertyMember is not null) { if (propertyMember.IsStatic) { var typeAst = _symbolTable.GetCurrentTypeDefinitionAst(); - Diagnostics.Assert(typeAst != null, "Method scopes can exist only inside type definitions."); + Diagnostics.Assert(typeAst is not null, "Method scopes can exist only inside type definitions."); string typeString = string.Format(CultureInfo.InvariantCulture, "[{0}]::", typeAst.Name); _parser.ReportError(variableExpressionAst.Extent, @@ -463,7 +463,7 @@ private Collection GetModulesFromUsingModule(UsingStatementAst usi // fullyQualifiedName can be string or hashtable object fullyQualifiedName; - if (usingStatementAst.ModuleSpecification != null) + if (usingStatementAst.ModuleSpecification is not null) { object resultObject; if (!IsConstantValueVisitor.IsConstant(usingStatementAst.ModuleSpecification, out resultObject, forAttribute: false, forRequires: true)) @@ -475,7 +475,7 @@ private Collection GetModulesFromUsingModule(UsingStatementAst usi var hashtable = resultObject as System.Collections.Hashtable; var ms = new ModuleSpecification(); exception = ModuleSpecification.ModuleSpecificationInitHelper(ms, hashtable); - if (exception != null) + if (exception is not null) { return null; } @@ -503,7 +503,7 @@ private Collection GetModulesFromUsingModule(UsingStatementAst usi if (isPath && !LocationGlobber.IsAbsolutePath(fullyQualifiedNameStr)) { string rootPath = Path.GetDirectoryName(_parser._fileName); - if (rootPath != null) + if (rootPath is not null) { fullyQualifiedNameStr = Path.Combine(rootPath, fullyQualifiedNameStr); } @@ -547,7 +547,7 @@ public override AstVisitAction VisitUsingStatement(UsingStatementAst usingStatem nameof(ParserStrings.RequiresArgumentMustBeConstant), ParserStrings.RequiresArgumentMustBeConstant); } - else if (exception != null) + else if (exception is not null) { // we re-using RequiresModuleInvalid string, semantic is very similar so it's fine to do that. _parser.ReportError(usingStatementAst.Extent, @@ -561,7 +561,7 @@ public override AstVisitAction VisitUsingStatement(UsingStatementAst usingStatem nameof(ParserStrings.WildCardModuleNameError), ParserStrings.WildCardModuleNameError); } - else if (moduleInfo != null && moduleInfo.Count > 0) + else if (moduleInfo is not null && moduleInfo.Count > 0) { // it's ok, if we get more then one module. They are already sorted in the right order // we just need to use the first one @@ -577,7 +577,7 @@ public override AstVisitAction VisitUsingStatement(UsingStatementAst usingStatem else { // if there is no exception, but we didn't find the module then it's not present - string moduleText = usingStatementAst.Name != null ? usingStatementAst.Name.Value : usingStatementAst.ModuleSpecification.Extent.Text; + string moduleText = usingStatementAst.Name is not null ? usingStatementAst.Name.Value : usingStatementAst.ModuleSpecification.Extent.Text; _parser.ReportError(usingStatementAst.Extent, nameof(ParserStrings.ModuleNotFoundDuringParse), ParserStrings.ModuleNotFoundDuringParse, @@ -598,21 +598,21 @@ private bool DispatchTypeName(ITypeName type, int genericArgumentCount, bool isA { RuntimeHelpers.EnsureSufficientExecutionStack(); var typeName = type as TypeName; - if (typeName != null) + if (typeName is not null) { return VisitTypeName(typeName, genericArgumentCount, isAttribute); } else { var arrayTypeName = type as ArrayTypeName; - if (arrayTypeName != null) + if (arrayTypeName is not null) { return VisitArrayTypeName(arrayTypeName); } else { var genericTypeName = type as GenericTypeName; - if (genericTypeName != null) + if (genericTypeName is not null) { return VisitGenericTypeName(genericTypeName); } @@ -638,7 +638,7 @@ private bool VisitTypeName(TypeName typeName, int genericArgumentCount, bool isA { var classDefn = _symbolTable.LookupType(typeName); - if (classDefn != null && classDefn.IsAmbiguous()) + if (classDefn is not null && classDefn.IsAmbiguous()) { _parser.ReportError(typeName.Extent, nameof(ParserStrings.AmbiguousTypeReference), @@ -647,7 +647,7 @@ private bool VisitTypeName(TypeName typeName, int genericArgumentCount, bool isA GetModuleQualifiedName(classDefn.ExternalNamespaces[0], typeName.Name), GetModuleQualifiedName(classDefn.ExternalNamespaces[1], typeName.Name)); } - else if (classDefn != null && genericArgumentCount == 0) + else if (classDefn is not null && genericArgumentCount == 0) { typeName.SetTypeDefinition(classDefn.Type); } @@ -661,7 +661,7 @@ private bool VisitTypeName(TypeName typeName, int genericArgumentCount, bool isA var type = TypeResolver.ResolveTypeNameWithContext(typeName, out e, null, trs); if (type is null) { - if (_symbolTable.GetCurrentTypeDefinitionAst() != null) + if (_symbolTable.GetCurrentTypeDefinitionAst() is not null) { // [ordered] is an attribute, but it's looks like a type constraint. if (!typeName.FullName.Equals(LanguagePrimitives.OrderedAttribute, StringComparison.OrdinalIgnoreCase)) @@ -696,7 +696,7 @@ private bool VisitTypeName(TypeName typeName, int genericArgumentCount, bool isA private bool VisitGenericTypeName(GenericTypeName genericTypeName) { var foundType = TypeCache.Lookup(genericTypeName, _typeResolutionState); - if (foundType != null) + if (foundType is not null) { ((ISupportsTypeCaching)genericTypeName).CachedType = foundType; return true; diff --git a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs index 0c544713ec6..cc85279b293 100644 --- a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs +++ b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs @@ -138,7 +138,7 @@ public TypeInferenceContext() : this(PowerShell.Create(RunspaceMode.CurrentRunsp /// The instance of powershell to use for expression evaluation needed for type inference. public TypeInferenceContext(PowerShell powerShell) { - Diagnostics.Assert(powerShell.Runspace != null, "Callers are required to ensure we have a runspace"); + Diagnostics.Assert(powerShell.Runspace is not null, "Callers are required to ensure we have a runspace"); _powerShell = powerShell; Helper = new PowerShellExecutionHelper(powerShell); @@ -164,7 +164,7 @@ public bool TryGetRepresentativeTypeNameFromExpressionSafeEval(ExpressionAst exp return false; } - return expression != null && + return expression is not null && SafeExprEvaluator.TrySafeEval(expression, ExecutionContext, out var value) && TryGetRepresentativeTypeNameFromValue(value, out typeName); } @@ -182,11 +182,11 @@ internal IList GetMembersByInferredType(PSTypeName typename, bool isStat } } - if (typename.Type != null) + if (typename.Type is not null) { AddMembersByInferredTypesClrType(typename, isStatic, filter, filterToCall, results); } - else if (typename.TypeDefinitionAst != null) + else if (typename.TypeDefinitionAst is not null) { AddMembersByInferredTypeDefinitionAst(typename, isStatic, filter, filterToCall, results); } @@ -251,7 +251,7 @@ internal void AddMembersByInferredTypesClrType(PSTypeName typename, bool isStati ? PSObject.DotNetStaticAdapter.BaseGetMembers(type) : PSObject.DotNetInstanceAdapter.GetPropertiesAndMethods(type, false); - if (filterToCall != null) + if (filterToCall is not null) { foreach (var member in members) { @@ -302,7 +302,7 @@ internal void AddMembersByInferredTypeDefinitionAst( foundConstructor |= functionMember.IsConstructor; } - if (filterToCall != null && add) + if (filterToCall is not null && add) { add = filterToCall(member); } @@ -399,14 +399,14 @@ internal void AddMembersByInferredTypeCimType(PSTypeName typename, List internal IEnumerable InferType(Ast ast, TypeInferenceVisitor visitor) { var res = ast.Accept(visitor); - Diagnostics.Assert(res != null, "Fix visit methods to not return null"); + Diagnostics.Assert(res is not null, "Fix visit methods to not return null"); return (IEnumerable)res; } private static bool TryGetRepresentativeTypeNameFromValue(object value, out PSTypeName type) { type = null; - if (value != null) + if (value is not null) { if (value is IList list && list.Count > 0) @@ -415,7 +415,7 @@ private static bool TryGetRepresentativeTypeNameFromValue(object value, out PSTy } value = PSObject.Base(value); - if (value != null) + if (value is not null) { type = new PSTypeName(value.GetType()); return true; @@ -434,7 +434,7 @@ internal static bool ParseCimCommandsTypeName(PSTypeName typename, out string ci return false; } - if (typename.Type != null) + if (typename.Type is not null) { return false; } @@ -476,7 +476,7 @@ private static bool IsConstructor(object member) { var psMethod = member as PSMethod; var methodCacheEntry = psMethod?.adapterData as DotNetAdapter.MethodCacheEntry; - return methodCacheEntry != null && methodCacheEntry.methodInformationStructures[0].method.IsConstructor; + return methodCacheEntry is not null && methodCacheEntry.methodInformationStructures[0].method.IsConstructor; } } @@ -555,7 +555,7 @@ object ICustomAstVisitor.VisitHashtable(HashtableAst hashtableAst) name = nameValue.ToString(); } - if (name != null) + if (name is not null) { object value = null; if (kv.Item2 is PipelineAst pipelineAst && pipelineAst.GetPureExpression() is ExpressionAst expression) @@ -579,7 +579,7 @@ object ICustomAstVisitor.VisitHashtable(HashtableAst hashtableAst) } } - var pstypeName = value != null ? new PSTypeName(value.GetType()) : new PSTypeName(typeName ?? "System.Object"); + var pstypeName = value is not null ? new PSTypeName(value.GetType()) : new PSTypeName(typeName ?? "System.Object"); properties.Add(new PSMemberNameAndType(name, pstypeName, value)); } } @@ -664,14 +664,14 @@ object ICustomAstVisitor.VisitConvertExpression(ConvertExpressionAst convertExpr } } - var psTypeName = type != null ? new PSTypeName(type) : new PSTypeName(convertExpressionAst.Type.TypeName.FullName); + var psTypeName = type is not null ? new PSTypeName(type) : new PSTypeName(convertExpressionAst.Type.TypeName.FullName); return new[] { psTypeName }; } object ICustomAstVisitor.VisitConstantExpression(ConstantExpressionAst constantExpressionAst) { var value = constantExpressionAst.Value; - return value != null ? new[] { new PSTypeName(value.GetType()) } : TypeInferenceContext.EmptyPSTypeNameArray; + return value is not null ? new[] { new PSTypeName(value.GetType()) } : TypeInferenceContext.EmptyPSTypeNameArray; } object ICustomAstVisitor.VisitStringConstantExpression(StringConstantExpressionAst stringConstantExpressionAst) @@ -724,17 +724,17 @@ object ICustomAstVisitor.VisitScriptBlock(ScriptBlockAst scriptBlockAst) var endBlock = scriptBlockAst.EndBlock; // The following is used when we don't find OutputType, which is checked elsewhere. - if (beginBlock != null) + if (beginBlock is not null) { res.AddRange(InferTypes(beginBlock)); } - if (processBlock != null) + if (processBlock is not null) { res.AddRange(InferTypes(processBlock)); } - if (endBlock != null) + if (endBlock is not null) { res.AddRange(InferTypes(endBlock)); } @@ -801,7 +801,7 @@ object ICustomAstVisitor.VisitParameter(ParameterAst parameterAst) { } - if (attribute != null) + if (attribute is not null) { res.Add(new PSTypeName(attribute.PSTypeName)); } @@ -839,7 +839,7 @@ object ICustomAstVisitor.VisitIfStatement(IfStatementAst ifStmtAst) } var elseClause = ifStmtAst.ElseClause; - if (elseClause != null) + if (elseClause is not null) { res.AddRange(InferTypes(elseClause)); } @@ -863,7 +863,7 @@ object ICustomAstVisitor.VisitSwitchStatement(SwitchStatementAst switchStatement res.AddRange(InferTypes(clause.Item2)); } - if (defaultStatement != null) + if (defaultStatement is not null) { res.AddRange(InferTypes(defaultStatement)); } @@ -910,7 +910,7 @@ object ICustomAstVisitor.VisitTryStatement(TryStatementAst tryStatementAst) res.AddRange(InferTypes(catchClauseAst)); } - if (tryStatementAst.Finally != null) + if (tryStatementAst.Finally is not null) { res.AddRange(InferTypes(tryStatementAst.Finally)); } @@ -1048,7 +1048,7 @@ private List InferTypesFromObjectCmdlets(CommandAst commandAst, Cmdl { // new - object - yields an instance of whatever -Type is bound to var newObjectType = InferTypesFromNewObjectCommand(pseudoBinding); - if (newObjectType != null) + if (newObjectType is not null) { inferredTypes.Add(newObjectType); } @@ -1131,7 +1131,7 @@ private void InferTypesFromForeachCommand(PseudoBindingInfo pseudoBinding, Comma { var memberName = (((AstPair)argument).Argument as StringConstantExpressionAst)?.Value; - if (memberName != null) + if (memberName is not null) { var members = _context.GetMembersByInferredType(t, false, null); bool maybeWantDefaultCtor = false; @@ -1236,7 +1236,7 @@ bool IsInPropertyArgument(object o) continue; } - if (properties != null) + if (properties is not null) { foreach (var memType in memberNameAndTypes) { @@ -1381,7 +1381,7 @@ bool IsInPropertyArgument(object o) { var memberName = (((AstPair)expandedPropertyArgument).Argument as StringConstantExpressionAst)?.Value; - if (memberName != null) + if (memberName is not null) { var members = _context.GetMembersByInferredType(t, false, null); bool maybeWantDefaultCtor = false; @@ -1611,7 +1611,7 @@ private bool TryGetTypeFromMember( if (memberAst is PropertyMemberAst propertyMemberAst) { result.Add( - propertyMemberAst.PropertyType != null + propertyMemberAst.PropertyType is not null ? new PSTypeName(propertyMemberAst.PropertyType.TypeName) : new PSTypeName(typeof(object))); @@ -1654,7 +1654,7 @@ private bool TryGetTypeFromMember( memberNamesToCheck.Add(aliasProperty.ReferencedMemberName); return true; case PSCodeProperty codeProperty: - if (codeProperty.GetterCodeReference != null) + if (codeProperty.GetterCodeReference is not null) { result.Add(new PSTypeName(codeProperty.GetterCodeReference.ReturnType)); } @@ -1671,14 +1671,14 @@ private bool TryGetTypeFromMember( break; } - if (scriptBlock != null) + if (scriptBlock is not null) { var thisToRestore = _context.CurrentThisType; try { _context.CurrentThisType = currentType; var outputType = scriptBlock.OutputType; - if (outputType != null && outputType.Count != 0) + if (outputType is not null && outputType.Count != 0) { result.AddRange(outputType); return true; @@ -1785,7 +1785,7 @@ private void InferTypeFrom(VariableExpressionAst variableExpressionAst, List).MakeGenericType(exceptionType))); } @@ -1850,7 +1850,7 @@ private void InferTypeFrom(VariableExpressionAst variableExpressionAst, List().FirstOrDefault(); - if (foreachAst != null) + if (foreachAst is not null) { inferredTypes.AddRange( GetInferredEnumeratedTypes(InferTypes(foreachAst.Condition))); @@ -1990,7 +1990,7 @@ private void InferTypeFrom(VariableExpressionAst variableExpressionAst, List().FirstOrDefault(); - if (commandCompletionAst != null) + if (commandCompletionAst is not null) { inferredTypes.AddRange(InferTypes(commandCompletionAst)); return; @@ -2008,7 +2008,7 @@ private void InferTypeFrom(VariableExpressionAst variableExpressionAst, List inferredTypes) } Type enumeratedItemType = GetMostSpecificEnumeratedItemType(foundType.Type); - if (enumeratedItemType != null) + if (enumeratedItemType is not null) { return new PSTypeName(enumeratedItemType.MakeArrayType()); } @@ -2107,7 +2107,7 @@ private Type GetMostSpecificEnumeratedItemType(Type enumerableType) ref hasSeenNonGeneric, ref hasSeenDictionaryEnumerator); - if (collectionInterface != null) + if (collectionInterface is not null) { return collectionInterface.GetGenericArguments()[0]; } @@ -2119,7 +2119,7 @@ private Type GetMostSpecificEnumeratedItemType(Type enumerableType) ref hasSeenNonGeneric, ref hasSeenDictionaryEnumerator); - if (collectionInterface != null) + if (collectionInterface is not null) { return collectionInterface.GetGenericArguments()[0]; } @@ -2197,7 +2197,7 @@ private IEnumerable InferTypeFrom(IndexExpressionAst indexExpression foreach (var psType in targetTypes) { var type = psType.Type; - if (type != null) + if (type is not null) { if (type.IsArray) { @@ -2230,7 +2230,7 @@ private IEnumerable InferTypeFrom(IndexExpressionAst indexExpression } var defaultMember = type.GetCustomAttributes(true).FirstOrDefault(); - if (defaultMember != null) + if (defaultMember is not null) { var indexers = type.GetGetterProperty(defaultMember.MemberName); foreach (var indexer in indexers) @@ -2375,7 +2375,7 @@ public static bool AstAssignsToSameVariable(this VariableExpressionAst variableA { var parameterAst = ast as ParameterAst; var variableAstVariablePath = variableAst.VariablePath; - if (parameterAst != null) + if (parameterAst is not null) { return variableAstVariablePath.IsUnscopedVariable && parameterAst.Name.VariablePath.UnqualifiedPath.Equals(variableAstVariablePath.UnqualifiedPath, StringComparison.OrdinalIgnoreCase); @@ -2392,7 +2392,7 @@ public static bool AstAssignsToSameVariable(this VariableExpressionAst variableA string[] variableParameters = { "PV", "PipelineVariable", "OV", "OutVariable" }; StaticBindingResult bindingResult = StaticParameterBinder.BindCommand(commandAst, false, variableParameters); - if (bindingResult != null) + if (bindingResult is not null) { foreach (string commandVariableParameter in variableParameters) { diff --git a/src/System.Management.Automation/engine/parser/TypeResolver.cs b/src/System.Management.Automation/engine/parser/TypeResolver.cs index c7e7bce672c..1e568cce2c5 100644 --- a/src/System.Management.Automation/engine/parser/TypeResolver.cs +++ b/src/System.Management.Automation/engine/parser/TypeResolver.cs @@ -40,7 +40,7 @@ internal static class TypeResolver private static Type LookForTypeInSingleAssembly(Assembly assembly, string typename) { Type targetType = assembly.GetType(typename, false, true); - if (targetType != null && IsPublic(targetType)) + if (targetType is not null && IsPublic(targetType)) { return targetType; } @@ -84,12 +84,12 @@ private static Type LookForTypeInAssemblies(TypeName typeName, try { Type targetType = LookForTypeInSingleAssembly(assembly, typeName.Name); - if (targetType is null && alternateNameToFind != null) + if (targetType is null && alternateNameToFind is not null) { targetType = LookForTypeInSingleAssembly(assembly, alternateNameToFind); } - if (targetType != null) + if (targetType is not null) { if (!reportAmbiguousException) { @@ -104,7 +104,7 @@ private static Type LookForTypeInAssemblies(TypeName typeName, // In the case (2) we should not report duplicate, hence this check if (foundType != targetType) { - if (foundType != null) + if (foundType is not null) { foundType2 = targetType; break; @@ -126,7 +126,7 @@ private static Type LookForTypeInAssemblies(TypeName typeName, } } - if (foundType2 != null) + if (foundType2 is not null) { exception = new AmbiguousTypeException(typeName, new string[] { foundType.AssemblyQualifiedName, foundType2.AssemblyQualifiedName }); return null; @@ -150,7 +150,7 @@ internal static bool IsPublic(Type type) return false; } - while ((type = type.DeclaringType) != null) + while ((type = type.DeclaringType) is not null) { if (!(type.IsPublic || type.IsNestedPublic)) { @@ -175,10 +175,10 @@ private static Type ResolveTypeNameWorker(TypeName typeName, if (!onlySearchInGivenAssemblies) { - while (currentScope != null) + while (currentScope is not null) { result = currentScope.LookupType(typeName.Name); - if (result != null) + if (result is not null) { return result; } @@ -193,7 +193,7 @@ private static Type ResolveTypeNameWorker(TypeName typeName, } result = LookForTypeInAssemblies(typeName, loadedAssemblies, searchedAssemblies, typeResolutionState, reportAmbiguousException, out exception); - if (exception != null) + if (exception is not null) { // skip the rest of lookups, if exception reported. return result; @@ -246,12 +246,12 @@ private static Type CallResolveTypeNameWorkerHelper(TypeName typeName, try { exception = null; - var currentScope = context != null ? context.EngineSessionState.CurrentScope : null; + var currentScope = context is not 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 (context != null && !isAssembliesExplicitlyPassedIn) + if (context is not null && !isAssembliesExplicitlyPassedIn) { // If the assemblies to search from is not specified by the caller of 'ResolveTypeNameWithContext', // then we search our assembly cache first, so as to give preference to resolving the type against @@ -291,7 +291,7 @@ internal static Type ResolveAssemblyQualifiedTypeName(TypeName typeName, out Exc var result = Type.GetType(typeName.FullName, false, true) ?? Type.GetType("System." + typeName.FullName, false, true); - if (result != null && IsPublic(result)) + if (result is not null && IsPublic(result)) { return result; } @@ -320,12 +320,12 @@ internal static Type ResolveTypeNameWithContext(TypeName typeName, out Exception var result = typeResolutionState.ContainsTypeDefined(typeName.Name) ? null : TypeCache.Lookup(typeName, typeResolutionState); - if (result != null) + if (result is not null) { return result; } - if (typeName.AssemblyName != null) + if (typeName.AssemblyName is not null) { result = ResolveAssemblyQualifiedTypeName(typeName, out exception); TypeCache.Add(typeName, typeResolutionState, result); @@ -365,7 +365,7 @@ internal static Type ResolveTypeNameWithContext(TypeName typeName, out Exception // We must search all using aliases and REPORT an error if there is an ambiguity. // If this is TypeDefinition we should not cache anything in TypeCache. - if (typeName._typeDefinitionAst != null) + if (typeName._typeDefinitionAst is not null) { return typeName._typeDefinitionAst.Type; } @@ -378,11 +378,11 @@ internal static Type ResolveTypeNameWithContext(TypeName typeName, out Exception // Use the explicitly passed-in assembly list when it's specified by the caller. // Otherwise, retrieve all currently loaded assemblies. var assemList = assemblies ?? ClrFacade.GetAssemblies(typeResolutionState, typeName); - var isAssembliesExplicitlyPassedIn = assemblies != null; + var isAssembliesExplicitlyPassedIn = assemblies is not null; result = CallResolveTypeNameWorkerHelper(typeName, context, assemList, isAssembliesExplicitlyPassedIn, typeResolutionState, out exception); - if (result != null) + if (result is not null) { TypeCache.Add(typeName, typeResolutionState, result); return result; @@ -406,12 +406,12 @@ internal static Type ResolveTypeNameWithContext(TypeName typeName, out Exception #endif var newResult = CallResolveTypeNameWorkerHelper(newTypeName, context, assemList, isAssembliesExplicitlyPassedIn, typeResolutionState, out exception); - if (exception != null) + if (exception is not null) { break; } - if (newResult != null) + if (newResult is not null) { if (result is null) { @@ -427,11 +427,11 @@ internal static Type ResolveTypeNameWithContext(TypeName typeName, out Exception } } - if (exception != null) + if (exception is not null) { // AmbiguousTypeException is for internal representation only. var ambiguousException = exception as AmbiguousTypeException; - if (ambiguousException != null) + if (ambiguousException is not null) { exception = new PSInvalidCastException("AmbiguousTypeReference", exception, ParserStrings.AmbiguousTypeReference, ambiguousException.TypeName.Name, @@ -439,7 +439,7 @@ internal static Type ResolveTypeNameWithContext(TypeName typeName, out Exception } } - if (result != null) + if (result is not null) { TypeCache.Add(typeName, typeResolutionState, result); } @@ -456,7 +456,7 @@ internal static bool TryResolveType(string typeName, out Type type) { Exception exception; type = ResolveType(typeName, out exception); - return (type != null); + return (type is not null); } internal static Type ResolveITypeName(ITypeName iTypeName, out Exception exception) @@ -587,7 +587,7 @@ internal static TypeResolutionState GetDefaultUsingState(ExecutionContext contex context = LocalPipeline.GetExecutionContextFromTLS(); } - if (context != null) + if (context is not null) { return context.EngineSessionState.CurrentScope.TypeResolutionState; } @@ -860,7 +860,7 @@ static TypeAccelerators() // Add all the core types foreach (KeyValuePair coreType in CoreTypes.Items.Value) { - if (coreType.Value != null) + if (coreType.Value is not null) { foreach (string accelerator in coreType.Value) { @@ -905,7 +905,7 @@ internal static string FindBuiltinAccelerator(Type type, string expectedKey = nu { Type resultType = null; builtinTypeAccelerators.TryGetValue(expectedKey, out resultType); - if (resultType != null && resultType == type) + if (resultType is not null && resultType == type) { return expectedKey; } @@ -921,7 +921,7 @@ internal static string FindBuiltinAccelerator(Type type, string expectedKey = nu public static void Add(string typeName, Type type) { userTypeAccelerators[typeName] = type; - if (s_allTypeAccelerators != null) + if (s_allTypeAccelerators is not null) { s_allTypeAccelerators[typeName] = type; } @@ -935,7 +935,7 @@ public static void Add(string typeName, Type type) public static bool Remove(string typeName) { userTypeAccelerators.Remove(typeName); - if (s_allTypeAccelerators != null) + if (s_allTypeAccelerators is not null) { s_allTypeAccelerators.Remove(typeName); } diff --git a/src/System.Management.Automation/engine/parser/VariableAnalysis.cs b/src/System.Management.Automation/engine/parser/VariableAnalysis.cs index 7b1ff901f5d..a029a4c7597 100644 --- a/src/System.Management.Automation/engine/parser/VariableAnalysis.cs +++ b/src/System.Management.Automation/engine/parser/VariableAnalysis.cs @@ -98,7 +98,7 @@ internal static Dictionary Visit(IParameterMeta ast.Body.InternalVisit(visitor); forceNoOptimizing = visitor._disableOptimizations; - if (ast.Parameters != null) + if (ast.Parameters is not null) { visitor.VisitParameters(ast.Parameters); } @@ -213,7 +213,7 @@ private void NoteVariable(string variableName, int index, Type type, bool automa public override AstVisitAction VisitDataStatement(DataStatementAst dataStatementAst) { - if (dataStatementAst.Variable != null) + if (dataStatementAst.Variable is not null) { NoteVariable(dataStatementAst.Variable, VariableAnalysis.Unanalyzed, null); } @@ -273,7 +273,7 @@ public override AstVisitAction VisitUsingExpression(UsingExpressionAst usingExpr public override AstVisitAction VisitCommand(CommandAst commandAst) { var commandName = commandAst.CommandElements[0] as StringConstantExpressionAst; - if (commandName != null && s_hashOfPessimizingCmdlets.Contains(commandName.Value)) + if (commandName is not null && s_hashOfPessimizingCmdlets.Contains(commandName.Value)) { // TODO: psuedo-bind the command invocation to figure out the variable and only force that variable to be unoptimized _disableOptimizations = true; @@ -582,7 +582,7 @@ private Tuple> AnalyzeImpl(IParameterMetadataProvi _variables = FindAllVariablesVisitor.Visit(ast, disableOptimizations, scriptCmdlet, out _localsAllocated, out _disableOptimizations); Init(); - if (ast.Parameters != null) + if (ast.Parameters is not null) { foreach (var parameter in ast.Parameters) { @@ -671,7 +671,7 @@ private Tuple> FinishAnalysis(bool scriptCmdlet = foreach (var pred in block._predecessors) { // VisitData can be null when the pred occurs because of a continue statement. - if (pred._visitData != null) + if (pred._visitData is not null) { predCount += 1; bitArray.And((BitArray)pred._visitData); @@ -731,7 +731,7 @@ orderby details.LocalTupleIndex // Automatic variables assign the type directly, not relying on any analysis. For // all other variables, we don't determine the type of the local until we're done // with the analysis. - Diagnostics.Assert(details.Type != null, "Type should be resolved already"); + Diagnostics.Assert(details.Type is not null, "Type should be resolved already"); } var tupleType = MutableTuple.MakeTupleType((from l in orderedLocals select l.Type).ToArray()); @@ -750,7 +750,7 @@ private static bool MustBeBoxed(Type type) private static void FixTupleIndex(Ast ast, int newIndex) { var variableAst = ast as VariableExpressionAst; - if (variableAst != null) + if (variableAst is not null) { if (variableAst.TupleIndex != ForceDynamic) { @@ -760,7 +760,7 @@ private static void FixTupleIndex(Ast ast, int newIndex) else { var dataStatementAst = ast as DataStatementAst; - if (dataStatementAst != null) + if (dataStatementAst is not null) { if (dataStatementAst.TupleIndex != ForceDynamic) { @@ -773,7 +773,7 @@ private static void FixTupleIndex(Ast ast, int newIndex) private static void FixAssigned(Ast ast, VariableAnalysisDetails details) { var variableAst = ast as VariableExpressionAst; - if (variableAst != null && details.Assigned) + if (variableAst is not null && details.Assigned) { variableAst.Assigned = true; } @@ -784,7 +784,7 @@ private void AnalyzeBlock(BitArray assignedBitArray, Block block) foreach (var ast in block._asts) { var variableExpressionAst = ast as VariableExpressionAst; - if (variableExpressionAst != null) + if (variableExpressionAst is not null) { var varPath = variableExpressionAst.VariablePath; if (varPath.IsAnyLocal()) @@ -808,9 +808,9 @@ private void AnalyzeBlock(BitArray assignedBitArray, Block block) } var assignmentTarget = ast as AssignmentTarget; - if (assignmentTarget != null) + if (assignmentTarget is not null) { - if (assignmentTarget._targetAst != null) + if (assignmentTarget._targetAst is not null) { CheckLHSAssign(assignmentTarget._targetAst, assignedBitArray); } @@ -823,7 +823,7 @@ private void AnalyzeBlock(BitArray assignedBitArray, Block block) } var dataStatementAst = ast as DataStatementAst; - if (dataStatementAst != null) + if (dataStatementAst is not null) { var details = CheckLHSAssignVar(dataStatementAst.Variable, assignedBitArray, typeof(object)); dataStatementAst.TupleIndex = details.LocalTupleIndex; @@ -839,14 +839,14 @@ private void CheckLHSAssign(ExpressionAst lhs, BitArray assignedBitArray) { var convertExpr = lhs as ConvertExpressionAst; Type convertType = null; - if (convertExpr != null) + if (convertExpr is not null) { lhs = convertExpr.Child; convertType = convertExpr.StaticType; } var varExpr = lhs as VariableExpressionAst; - Diagnostics.Assert(varExpr != null, "unexpected ast type on lhs"); + Diagnostics.Assert(varExpr is not null, "unexpected ast type on lhs"); var varPath = varExpr.VariablePath; if (varPath.IsAnyLocal()) @@ -885,7 +885,7 @@ private VariableAnalysisDetails CheckLHSAssignVar(string variableName, BitArray : _localsAllocated++; } - if (convertType != null && MustBeBoxed(convertType)) + if (convertType is not null && MustBeBoxed(convertType)) { analysisDetails.LocalTupleIndex = VariableAnalysis.ForceDynamic; } @@ -904,7 +904,7 @@ private VariableAnalysisDetails CheckLHSAssignVar(string variableName, BitArray convertType = typeof(object); } - if (convertType != null && !convertType.Equals(type)) + if (convertType is not null && !convertType.Equals(type)) { if (analysisDetails.Automatic || analysisDetails.PreferenceVariable) { @@ -938,22 +938,22 @@ public object VisitScriptBlock(ScriptBlockAst scriptBlockAst) { _currentBlock = _entryBlock; - if (scriptBlockAst.DynamicParamBlock != null) + if (scriptBlockAst.DynamicParamBlock is not null) { scriptBlockAst.DynamicParamBlock.Accept(this); } - if (scriptBlockAst.BeginBlock != null) + if (scriptBlockAst.BeginBlock is not null) { scriptBlockAst.BeginBlock.Accept(this); } - if (scriptBlockAst.ProcessBlock != null) + if (scriptBlockAst.ProcessBlock is not null) { scriptBlockAst.ProcessBlock.Accept(this); } - if (scriptBlockAst.EndBlock != null) + if (scriptBlockAst.EndBlock is not null) { scriptBlockAst.EndBlock.Accept(this); } @@ -1053,7 +1053,7 @@ public object VisitIfStatement(IfStatementAst ifStmtAst) _currentBlock = nextBlock; } - if (ifStmtAst.ElseClause != null) + if (ifStmtAst.ElseClause is not null) { ifStmtAst.ElseClause.Accept(this); _currentBlock.FlowsTo(afterStmt); @@ -1109,7 +1109,7 @@ public object VisitSwitchStatement(SwitchStatementAst switchStatementAst) Action switchBodyGenerator = () => { - bool hasDefault = (switchStatementAst.Default != null); + bool hasDefault = (switchStatementAst.Default is not null); Block afterStmt = new Block(); int clauseCount = switchStatementAst.Clauses.Count; @@ -1154,7 +1154,7 @@ public object VisitSwitchStatement(SwitchStatementAst switchStatementAst) public object VisitDataStatement(DataStatementAst dataStatementAst) { dataStatementAst.Body.Accept(this); - if (dataStatementAst.Variable != null) + if (dataStatementAst.Variable is not null) { _currentBlock.AddAst(dataStatementAst); } @@ -1183,7 +1183,7 @@ private void GenerateWhileLoop(string loopLabel, var continueBlock = new Block(); - if (continueAction != null) + if (continueAction is not null) { var blockAfterContinue = new Block(); @@ -1207,7 +1207,7 @@ private void GenerateWhileLoop(string loopLabel, // Condition can be null from an uncommon for loop: for() {} - if (generateCondition != null) + if (generateCondition is not null) { generateCondition(); _currentBlock.FlowsTo(breakBlock); @@ -1310,12 +1310,12 @@ public object VisitDoUntilStatement(DoUntilStatementAst doUntilStatementAst) public object VisitForStatement(ForStatementAst forStatementAst) { - if (forStatementAst.Initializer != null) + if (forStatementAst.Initializer is not null) { forStatementAst.Initializer.Accept(this); } - var generateCondition = forStatementAst.Condition != null + var generateCondition = forStatementAst.Condition is not null ? () => forStatementAst.Condition.Accept(this) : (Action)null; @@ -1374,7 +1374,7 @@ public object VisitTryStatement(TryStatementAst tryStatementAst) _currentBlock.FlowsTo(finallyFirstBlock ?? afterTry); } - if (finallyFirstBlock != null) + if (finallyFirstBlock is not null) { lastBlockInTry.FlowsTo(finallyFirstBlock); @@ -1413,13 +1413,13 @@ public object VisitTryStatement(TryStatementAst tryStatementAst) private void BreakOrContinue(ExpressionAst label, Func fieldSelector) { Block targetBlock = null; - if (label != null) + if (label is not null) { label.Accept(this); if (_loopTargets.Count > 0) { var labelStrAst = label as StringConstantExpressionAst; - if (labelStrAst != null) + if (labelStrAst is not null) { targetBlock = (from t in _loopTargets where t.Label.Equals(labelStrAst.Value, StringComparison.OrdinalIgnoreCase) @@ -1461,7 +1461,7 @@ public object VisitContinueStatement(ContinueStatementAst continueStatementAst) private Block ControlFlowStatement(PipelineBaseAst pipelineAst) { - if (pipelineAst != null) + if (pipelineAst is not null) { pipelineAst.Accept(this); } @@ -1497,7 +1497,7 @@ public object VisitThrowStatement(ThrowStatementAst throwStatementAst) private static IEnumerable GetAssignmentTargets(ExpressionAst expressionAst) { var parenExpr = expressionAst as ParenExpressionAst; - if (parenExpr != null) + if (parenExpr is not null) { foreach (var e in GetAssignmentTargets(parenExpr.Pipeline.GetPureExpression())) { @@ -1507,7 +1507,7 @@ private static IEnumerable GetAssignmentTargets(ExpressionAst exp else { var arrayLiteral = expressionAst as ArrayLiteralAst; - if (arrayLiteral != null) + if (arrayLiteral is not null) { foreach (var e in arrayLiteral.Elements.SelectMany(GetAssignmentTargets)) { @@ -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 is not null && convertAst.Type.TypeName.GetReflectionType() is null)) { var varPath = ((VariableExpressionAst)leftAst).VariablePath; if (varPath.IsAnyLocal()) @@ -1635,7 +1635,7 @@ public object VisitCommandExpression(CommandExpressionAst commandExpressionAst) public object VisitCommandParameter(CommandParameterAst commandParameterAst) { - if (commandParameterAst.Argument != null) + if (commandParameterAst.Argument is not null) { commandParameterAst.Argument.Accept(this); } @@ -1768,7 +1768,7 @@ public object VisitInvokeMemberExpression(InvokeMemberExpressionAst invokeMember { invokeMemberExpressionAst.Expression.Accept(this); invokeMemberExpressionAst.Member.Accept(this); - if (invokeMemberExpressionAst.Arguments != null) + if (invokeMemberExpressionAst.Arguments is not null) { foreach (var arg in invokeMemberExpressionAst.Arguments) { diff --git a/src/System.Management.Automation/engine/parser/ast.cs b/src/System.Management.Automation/engine/parser/ast.cs index e4ad627babc..616d549e433 100644 --- a/src/System.Management.Automation/engine/parser/ast.cs +++ b/src/System.Management.Automation/engine/parser/ast.cs @@ -199,7 +199,7 @@ public object SafeGetValue() try { ExecutionContext context = null; - if (System.Management.Automation.Runspaces.Runspace.DefaultRunspace != null) + if (System.Management.Automation.Runspaces.Runspace.DefaultRunspace is not null) { context = System.Management.Automation.Runspaces.Runspace.DefaultRunspace.ExecutionContext; } @@ -271,7 +271,7 @@ internal void SetParents(ReadOnlyCollection> children) // Should be protected AND internal, but C# doesn't support that. internal void SetParent(Ast child) { - if (child.Parent != null) + if (child.Parent is not null) { throw new InvalidOperationException(ParserStrings.AstIsReused); } @@ -298,14 +298,14 @@ internal bool IsInWorkflow() Ast current = this; bool stopScanning = false; - while (current != null && !stopScanning) + while (current is not null && !stopScanning) { ScriptBlockAst scriptBlock = current as ScriptBlockAst; - if (scriptBlock != null) + if (scriptBlock is not null) { // See if this uses the workflow keyword FunctionDefinitionAst functionDefinition = scriptBlock.Parent as FunctionDefinitionAst; - if ((functionDefinition != null)) + if ((functionDefinition is not null)) { stopScanning = true; if (functionDefinition.IsWorkflow) { return true; } @@ -313,7 +313,7 @@ internal bool IsInWorkflow() } CommandAst commandAst = current as CommandAst; - if (commandAst != null && + if (commandAst is not null && string.Equals(TokenKind.InlineScript.Text(), commandAst.GetCommandName(), StringComparison.OrdinalIgnoreCase) && this != commandAst) { @@ -336,7 +336,7 @@ internal static ConfigurationDefinitionAst GetAncestorConfigurationDefinitionAst { ConfigurationDefinitionAst configAst = null; keywordAst = GetAncestorAst(ast); - configAst = (keywordAst != null) ? GetAncestorAst(keywordAst) : GetAncestorAst(ast); + configAst = (keywordAst is not null) ? GetAncestorAst(keywordAst) : GetAncestorAst(ast); return configAst; } @@ -344,10 +344,10 @@ internal static HashtableAst GetAncestorHashtableAst(Ast ast, out Ast lastChildO { HashtableAst hashtableAst = null; lastChildOfHashtable = null; - while (ast != null) + while (ast is not null) { hashtableAst = ast as HashtableAst; - if (hashtableAst != null) + if (hashtableAst is not null) break; lastChildOfHashtable = ast; ast = ast.Parent; @@ -360,16 +360,16 @@ internal static TypeDefinitionAst GetAncestorTypeDefinitionAst(Ast ast) { TypeDefinitionAst typeDefinitionAst = null; - while (ast != null) + while (ast is not null) { typeDefinitionAst = ast as TypeDefinitionAst; - if (typeDefinitionAst != null) + if (typeDefinitionAst is not null) break; // Nested function isn't really a member of the type so stop looking // Anonymous script blocks are though var functionDefinitionAst = ast as FunctionDefinitionAst; - if (functionDefinitionAst != null && !(functionDefinitionAst.Parent is FunctionMemberAst)) + if (functionDefinitionAst is not null && !(functionDefinitionAst.Parent is FunctionMemberAst)) break; ast = ast.Parent; } @@ -386,10 +386,10 @@ internal static T GetAncestorAst(Ast ast) where T : Ast { T targetAst = null; var parent = ast; - while (parent != null) + while (parent is not null) { targetAst = parent as T; - if (targetAst != null) + if (targetAst is not null) break; parent = parent.Parent; } @@ -439,7 +439,7 @@ public class ErrorStatementAst : PipelineBaseAst internal ErrorStatementAst(IScriptExtent extent, IEnumerable nestedAsts = null) : base(extent) { - if (nestedAsts != null && nestedAsts.Any()) + if (nestedAsts is not null && nestedAsts.Any()) { NestedAst = new ReadOnlyCollection(nestedAsts.ToArray()); SetParents(NestedAst); @@ -455,7 +455,7 @@ internal ErrorStatementAst(IScriptExtent extent, Token kind, IEnumerable ne } Kind = kind; - if (nestedAsts != null && nestedAsts.Any()) + if (nestedAsts is not null && nestedAsts.Any()) { NestedAst = new ReadOnlyCollection(nestedAsts.ToArray()); SetParents(NestedAst); @@ -471,7 +471,7 @@ internal ErrorStatementAst(IScriptExtent extent, Token kind, IEnumerable>(StringComparer.OrdinalIgnoreCase); foreach (KeyValuePair> entry in flags) @@ -480,20 +480,20 @@ internal ErrorStatementAst(IScriptExtent extent, Token kind, IEnumerable(conditions.ToArray()); SetParents(Conditions); } - if (bodies != null && bodies.Any()) + if (bodies is not null && bodies.Any()) { Bodies = new ReadOnlyCollection(bodies.ToArray()); SetParents(Bodies); @@ -543,13 +543,13 @@ public override Ast Copy() var newNestedAst = CopyElements(this.NestedAst); return new ErrorStatementAst(this.Extent, newNestedAst); } - else if (Flags != null || Conditions != null || Bodies != null) + else if (Flags is not null || Conditions is not null || Bodies is not null) { var newConditions = CopyElements(this.Conditions); var newBodies = CopyElements(this.Bodies); Dictionary> newFlags = null; - if (this.Flags != null) + if (this.Flags is not null) { newFlags = new Dictionary>(StringComparer.OrdinalIgnoreCase); foreach (KeyValuePair> entry in this.Flags) @@ -580,7 +580,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) var action = visitor.VisitErrorStatement(this); if (action == AstVisitAction.SkipChildren) return visitor.CheckForPostAction(this, AstVisitAction.Continue); - if (action == AstVisitAction.Continue && NestedAst != null) + if (action == AstVisitAction.Continue && NestedAst is not null) { for (int index = 0; index < NestedAst.Count; index++) { @@ -590,7 +590,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) } } - if (action == AstVisitAction.Continue && Flags != null) + if (action == AstVisitAction.Continue && Flags is not null) { foreach (var tuple in Flags.Values) { @@ -602,7 +602,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) } } - if (action == AstVisitAction.Continue && Conditions != null) + if (action == AstVisitAction.Continue && Conditions is not null) { for (int index = 0; index < Conditions.Count; index++) { @@ -612,7 +612,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) } } - if (action == AstVisitAction.Continue && Bodies != null) + if (action == AstVisitAction.Continue && Bodies is not null) { for (int index = 0; index < Bodies.Count; index++) { @@ -636,7 +636,7 @@ public class ErrorExpressionAst : ExpressionAst internal ErrorExpressionAst(IScriptExtent extent, IEnumerable nestedAsts = null) : base(extent) { - if (nestedAsts != null && nestedAsts.Any()) + if (nestedAsts is not null && nestedAsts.Any()) { NestedAst = new ReadOnlyCollection(nestedAsts.ToArray()); SetParents(NestedAst); @@ -671,7 +671,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) var action = visitor.VisitErrorExpression(this); if (action == AstVisitAction.SkipChildren) return visitor.CheckForPostAction(this, AstVisitAction.Continue); - if (action == AstVisitAction.Continue && NestedAst != null) + if (action == AstVisitAction.Continue && NestedAst is not null) { for (int index = 0; index < NestedAst.Count; index++) { @@ -801,7 +801,7 @@ public ScriptBlockAst(IScriptExtent extent, { SetUsingStatements(usingStatements); - if (attributes != null) + if (attributes is not null) { this.Attributes = new ReadOnlyCollection(attributes.ToArray()); SetParents(Attributes); @@ -811,31 +811,31 @@ public ScriptBlockAst(IScriptExtent extent, this.Attributes = s_emptyAttributeList; } - if (paramBlock != null) + if (paramBlock is not null) { this.ParamBlock = paramBlock; SetParent(paramBlock); } - if (beginBlock != null) + if (beginBlock is not null) { this.BeginBlock = beginBlock; SetParent(beginBlock); } - if (processBlock != null) + if (processBlock is not null) { this.ProcessBlock = processBlock; SetParent(processBlock); } - if (endBlock != null) + if (endBlock is not null) { this.EndBlock = endBlock; SetParent(endBlock); } - if (dynamicParamBlock != null) + if (dynamicParamBlock is not null) { this.DynamicParamBlock = dynamicParamBlock; SetParent(dynamicParamBlock); @@ -1013,7 +1013,7 @@ public ScriptBlockAst(IScriptExtent extent, IEnumerable using { SetUsingStatements(usingStatements); - if (attributes != null) + if (attributes is not null) { this.Attributes = new ReadOnlyCollection(attributes.ToArray()); SetParents(Attributes); @@ -1028,7 +1028,7 @@ public ScriptBlockAst(IScriptExtent extent, IEnumerable using throw PSTraceSource.NewArgumentNullException(nameof(statements)); } - if (paramBlock != null) + if (paramBlock is not null) { this.ParamBlock = paramBlock; SetParent(paramBlock); @@ -1049,7 +1049,7 @@ public ScriptBlockAst(IScriptExtent extent, IEnumerable using private void SetUsingStatements(IEnumerable usingStatements) { - if (usingStatements != null) + if (usingStatements is not null) { this.UsingStatements = new ReadOnlyCollection(usingStatements.ToArray()); SetParents(UsingStatements); @@ -1113,7 +1113,7 @@ public CommentHelpInfo GetHelpContent() { Dictionary scriptBlockTokenCache = new Dictionary(); var commentTokens = HelpCommentsParser.GetHelpCommentTokens(this, scriptBlockTokenCache); - if (commentTokens != null) + if (commentTokens is not null) { return HelpCommentsParser.GetHelpContents(commentTokens.Item1, commentTokens.Item2); } @@ -1156,7 +1156,7 @@ private ScriptBlockAst GetRootScriptBlockAst() { ScriptBlockAst rootScriptBlockAst = this; ScriptBlockAst parent; - while ((parent = Ast.GetAncestorAst(rootScriptBlockAst.Parent)) != null) + while ((parent = Ast.GetAncestorAst(rootScriptBlockAst.Parent)) is not null) { rootScriptBlockAst = parent; } @@ -1189,7 +1189,7 @@ public override Ast Copy() internal string ToStringForSerialization() { string result = this.ToString(); - if (Parent != null) + if (Parent is not null) { // Parent is FunctionDefinitionAst or ScriptBlockExpressionAst // The extent includes curlies which we want to exclude. @@ -1203,7 +1203,7 @@ internal string ToStringForSerialization() internal string ToStringForSerialization(Tuple, string> usingVariablesTuple, int initialStartOffset, int initialEndOffset) { - Diagnostics.Assert(usingVariablesTuple.Item1 != null && usingVariablesTuple.Item1.Count > 0 && !string.IsNullOrEmpty(usingVariablesTuple.Item2), + Diagnostics.Assert(usingVariablesTuple.Item1 is not null && usingVariablesTuple.Item1.Count > 0 && !string.IsNullOrEmpty(usingVariablesTuple.Item2), "Caller makes sure the value passed in is not null or empty"); Diagnostics.Assert(initialStartOffset < initialEndOffset && initialStartOffset >= this.Extent.StartOffset && initialEndOffset <= this.Extent.EndOffset, "Caller makes sure the section is within the ScriptBlockAst"); @@ -1215,7 +1215,7 @@ internal string ToStringForSerialization(Tuple, stri // -- UsingVariable // -- ParamBlockAst var astElements = new List(usingVars); - if (ParamBlock != null) + if (ParamBlock is not null) { astElements.Add(ParamBlock); } @@ -1238,7 +1238,7 @@ internal string ToStringForSerialization(Tuple, stri if (astStartOffset >= endOffset) { break; } var varAst = ast as VariableExpressionAst; - if (varAst != null) + if (varAst is not null) { string varName = varAst.VariablePath.UserPath; string varSign = varAst.Splatted ? "@" : "$"; @@ -1251,7 +1251,7 @@ internal string ToStringForSerialization(Tuple, stri else { var paramAst = ast as ParamBlockAst; - Diagnostics.Assert(paramAst != null, "The elements in astElements are either ParamBlockAst or VariableExpressionAst"); + Diagnostics.Assert(paramAst is not null, "The elements in astElements are either ParamBlockAst or VariableExpressionAst"); int currentOffset; if (paramAst.Parameters.Count == 0) @@ -1274,7 +1274,7 @@ internal string ToStringForSerialization(Tuple, stri newScript.Append(script.AsSpan(startOffset, endOffset - startOffset)); string result = newScript.ToString(); - if (Parent != null && initialStartOffset == this.Extent.StartOffset && initialEndOffset == this.Extent.EndOffset) + if (Parent is not null && initialStartOffset == this.Extent.StartOffset && initialEndOffset == this.Extent.EndOffset) { // Parent is FunctionDefinitionAst or ScriptBlockExpressionAst // The extent includes curlies which we want to exclude. @@ -1318,7 +1318,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) return visitor.CheckForPostAction(this, AstVisitAction.Continue); var visitor2 = visitor as AstVisitor2; - if (visitor2 != null) + if (visitor2 is not null) { if (action == AstVisitAction.Continue) { @@ -1345,15 +1345,15 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) } } - if (action == AstVisitAction.Continue && ParamBlock != null) + if (action == AstVisitAction.Continue && ParamBlock is not null) action = ParamBlock.InternalVisit(visitor); - if (action == AstVisitAction.Continue && DynamicParamBlock != null) + if (action == AstVisitAction.Continue && DynamicParamBlock is not null) action = DynamicParamBlock.InternalVisit(visitor); - if (action == AstVisitAction.Continue && BeginBlock != null) + if (action == AstVisitAction.Continue && BeginBlock is not null) action = BeginBlock.InternalVisit(visitor); - if (action == AstVisitAction.Continue && ProcessBlock != null) + if (action == AstVisitAction.Continue && ProcessBlock is not null) action = ProcessBlock.InternalVisit(visitor); - if (action == AstVisitAction.Continue && EndBlock != null) + if (action == AstVisitAction.Continue && EndBlock is not null) action = EndBlock.InternalVisit(visitor); return visitor.CheckForPostAction(this, action); } @@ -1364,12 +1364,12 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) bool IParameterMetadataProvider.HasAnyScriptBlockAttributes() { - return Attributes.Count > 0 || ParamBlock != null && ParamBlock.Attributes.Count > 0; + return Attributes.Count > 0 || ParamBlock is not null && ParamBlock.Attributes.Count > 0; } RuntimeDefinedParameterDictionary IParameterMetadataProvider.GetParameterMetadata(bool automaticPositions, ref bool usesCmdletBinding) { - if (ParamBlock != null) + if (ParamBlock is not null) { return Compiler.GetParameterMetaData(ParamBlock.Parameters, automaticPositions, ref usesCmdletBinding); } @@ -1385,7 +1385,7 @@ IEnumerable IParameterMetadataProvider.GetScriptBlockAttributes() yield return Compiler.GetAttribute(attributeAst); } - if (ParamBlock != null) + if (ParamBlock is not null) { for (int index = 0; index < ParamBlock.Attributes.Count; index++) { @@ -1401,16 +1401,16 @@ IEnumerable IParameterMetadataProvider.GetExperimentalAtt { AttributeAst attributeAst = Attributes[index]; ExperimentalAttribute expAttr = GetExpAttributeHelper(attributeAst); - if (expAttr != null) { yield return expAttr; } + if (expAttr is not null) { yield return expAttr; } } - if (ParamBlock != null) + if (ParamBlock is not null) { for (int index = 0; index < ParamBlock.Attributes.Count; index++) { var attributeAst = ParamBlock.Attributes[index]; var expAttr = GetExpAttributeHelper(attributeAst); - if (expAttr != null) { yield return expAttr; } + if (expAttr is not null) { yield return expAttr; } } } @@ -1437,7 +1437,7 @@ ExperimentalAttribute GetExpAttributeHelper(AttributeAst attributeAst) } } - if (potentialExpAttr != null) + if (potentialExpAttr is not null) { try { @@ -1455,7 +1455,7 @@ ExperimentalAttribute GetExpAttributeHelper(AttributeAst attributeAst) ReadOnlyCollection IParameterMetadataProvider.Parameters { - get { return (ParamBlock != null) ? this.ParamBlock.Parameters : null; } + get { return (ParamBlock is not null) ? this.ParamBlock.Parameters : null; } } ScriptBlockAst IParameterMetadataProvider.Body { get { return this; } } @@ -1520,7 +1520,7 @@ private string GetWithInputHandlingForInvokeCommandImpl(Tuple" var sb = new StringBuilder(); - if (ParamBlock != null) + if (ParamBlock is not null) { string paramText = (usingVariablesTuple is null) ? ParamBlock.ToString() @@ -1543,7 +1543,7 @@ bool IParameterMetadataProvider.UsesCmdletBinding() { bool usesCmdletBinding = false; - if (ParamBlock != null) + if (ParamBlock is not null) { usesCmdletBinding = this.ParamBlock.Attributes.Any(attribute => typeof(CmdletBindingAttribute) == attribute.TypeName.GetReflectionAttributeType()); if (!usesCmdletBinding) @@ -1559,7 +1559,7 @@ bool IParameterMetadataProvider.UsesCmdletBinding() internal PipelineAst GetSimplePipeline(bool allowMultiplePipelines, out string errorId, out string errorMsg) { - if (BeginBlock != null || ProcessBlock != null || DynamicParamBlock != null) + if (BeginBlock is not null || ProcessBlock is not null || DynamicParamBlock is not null) { errorId = "CanConvertOneClauseOnly"; errorMsg = AutomationExceptions.CanConvertOneClauseOnly; @@ -1573,7 +1573,7 @@ internal PipelineAst GetSimplePipeline(bool allowMultiplePipelines, out string e return null; } - if (EndBlock.Traps != null && EndBlock.Traps.Count > 0) + if (EndBlock.Traps is not null && EndBlock.Traps.Count > 0) { errorId = "CantConvertScriptBlockWithTrap"; errorMsg = AutomationExceptions.CantConvertScriptBlockWithTrap; @@ -1625,7 +1625,7 @@ public class ParamBlockAst : Ast public ParamBlockAst(IScriptExtent extent, IEnumerable attributes, IEnumerable parameters) : base(extent) { - if (attributes != null) + if (attributes is not null) { this.Attributes = new ReadOnlyCollection(attributes.ToArray()); SetParents(Attributes); @@ -1635,7 +1635,7 @@ public ParamBlockAst(IScriptExtent extent, IEnumerable attributes, this.Attributes = s_emptyAttributeList; } - if (parameters != null) + if (parameters is not null) { this.Parameters = new ReadOnlyCollection(parameters.ToArray()); SetParents(Parameters); @@ -1708,7 +1708,7 @@ internal static bool UsesCmdletBinding(IEnumerable parameters) bool usesCmdletBinding = false; foreach (var parameter in parameters) { - usesCmdletBinding = parameter.Attributes.Any(attribute => (attribute.TypeName.GetReflectionAttributeType() != null) && + usesCmdletBinding = parameter.Attributes.Any(attribute => (attribute.TypeName.GetReflectionAttributeType() is not null) && attribute.TypeName.GetReflectionAttributeType() == typeof(ParameterAttribute)); if (usesCmdletBinding) { @@ -1781,7 +1781,7 @@ public NamedBlockAst(IScriptExtent extent, TokenKind blockName, StatementBlockAs SetParents(statements); var traps = statementBlock.Traps; - if (traps != null && traps.Count > 0) + if (traps is not null && traps.Count > 0) { this.Traps = traps; for (int index = 0; index < traps.Count; index++) @@ -1796,7 +1796,7 @@ public NamedBlockAst(IScriptExtent extent, TokenKind blockName, StatementBlockAs if (!unnamed) { var statementsExtent = statementBlock.Extent as InternalScriptExtent; - if (statementsExtent != null) + if (statementsExtent is not null) { this.OpenCurlyExtent = new InternalScriptExtent(statementsExtent.PositionHelper, statementsExtent.StartOffset, statementsExtent.StartOffset + 1); this.CloseCurlyExtent = new InternalScriptExtent(statementsExtent.PositionHelper, statementsExtent.EndOffset - 1, statementsExtent.EndOffset); @@ -1841,7 +1841,7 @@ public override Ast Copy() var newStatements = CopyElements(this.Statements); var statementBlockExtent = this.Extent; - if (this.OpenCurlyExtent != null && this.CloseCurlyExtent != null) + if (this.OpenCurlyExtent is not null && this.CloseCurlyExtent is not null) { // For explicitly named block, the Extent of the StatementBlockAst is not // the same as the Extent of the NamedBlockAst. In this case, reconstruct @@ -2027,7 +2027,7 @@ public AttributeAst(IScriptExtent extent, IEnumerable namedArguments) : base(extent, typeName) { - if (positionalArguments != null) + if (positionalArguments is not null) { this.PositionalArguments = new ReadOnlyCollection(positionalArguments.ToArray()); SetParents(PositionalArguments); @@ -2037,7 +2037,7 @@ public AttributeAst(IScriptExtent extent, this.PositionalArguments = s_emptyPositionalArguments; } - if (namedArguments != null) + if (namedArguments is not null) { this.NamedArguments = new ReadOnlyCollection(namedArguments.ToArray()); SetParents(NamedArguments); @@ -2201,7 +2201,7 @@ public ParameterAst(IScriptExtent extent, throw PSTraceSource.NewArgumentNullException(nameof(name)); } - if (attributes != null) + if (attributes is not null) { this.Attributes = new ReadOnlyCollection(attributes.ToArray()); SetParents(Attributes); @@ -2213,7 +2213,7 @@ public ParameterAst(IScriptExtent extent, this.Name = name; SetParent(name); - if (defaultValue != null) + if (defaultValue is not null) { this.DefaultValue = defaultValue; SetParent(defaultValue); @@ -2245,7 +2245,7 @@ public Type StaticType { Type type = null; var typeConstraint = Attributes.OfType().FirstOrDefault(); - if (typeConstraint != null) + if (typeConstraint is not null) { type = typeConstraint.TypeName.GetReflectionType(); } @@ -2268,7 +2268,7 @@ public override Ast Copy() internal string GetTooltip() { var typeConstraint = Attributes.OfType().FirstOrDefault(); - var type = typeConstraint != null ? typeConstraint.TypeName.FullName : "object"; + var type = typeConstraint is not null ? typeConstraint.TypeName.FullName : "object"; return type + " " + Name.VariablePath.UserPath; } @@ -2354,7 +2354,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) action = Name.InternalVisit(visitor); } - if (action == AstVisitAction.Continue && DefaultValue != null) + if (action == AstVisitAction.Continue && DefaultValue is not null) { action = DefaultValue.InternalVisit(visitor); } @@ -2391,7 +2391,7 @@ public class StatementBlockAst : Ast public StatementBlockAst(IScriptExtent extent, IEnumerable statements, IEnumerable traps) : base(extent) { - if (statements != null) + if (statements is not null) { this.Statements = new ReadOnlyCollection(statements.ToArray()); SetParents(Statements); @@ -2401,7 +2401,7 @@ public StatementBlockAst(IScriptExtent extent, IEnumerable stateme this.Statements = s_emptyStatementCollection; } - if (traps != null && traps.Any()) + if (traps is not null && traps.Any()) { this.Traps = new ReadOnlyCollection(traps.ToArray()); SetParents(Traps); @@ -2451,7 +2451,7 @@ internal static AstVisitAction InternalVisit(AstVisitor visitor, if (action == AstVisitAction.SkipChildren) return AstVisitAction.Continue; - if (action == AstVisitAction.Continue && traps != null) + if (action == AstVisitAction.Continue && traps is not null) { for (int index = 0; index < traps.Count; index++) { @@ -2461,7 +2461,7 @@ internal static AstVisitAction InternalVisit(AstVisitor visitor, } } - if (action == AstVisitAction.Continue && statements != null) + if (action == AstVisitAction.Continue && statements is not null) { for (int index = 0; index < statements.Count; index++) { @@ -2546,7 +2546,7 @@ public TypeDefinitionAst(IScriptExtent extent, string name, IEnumerable(attributes.ToArray()); SetParents(Attributes); @@ -2556,7 +2556,7 @@ public TypeDefinitionAst(IScriptExtent extent, string name, IEnumerable(members.ToArray()); SetParents(Members); @@ -2566,7 +2566,7 @@ public TypeDefinitionAst(IScriptExtent extent, string name, IEnumerable(baseTypes.ToArray()); SetParents(BaseTypes); @@ -2656,14 +2656,14 @@ public override Ast Copy() internal override object Accept(ICustomAstVisitor visitor) { var visitor2 = visitor as ICustomAstVisitor2; - return visitor2 != null ? visitor2.VisitTypeDefinition(this) : null; + return visitor2 is not null ? visitor2.VisitTypeDefinition(this) : null; } internal override AstVisitAction InternalVisit(AstVisitor visitor) { var action = AstVisitAction.Continue; var visitor2 = visitor as AstVisitor2; - if (visitor2 != null) + if (visitor2 is not null) { action = visitor2.VisitTypeDefinition(this); if (action == AstVisitAction.SkipChildren) @@ -2673,7 +2673,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) // REVIEW: should old visitors completely skip the attributes and // bodies of methods, or should they get a chance to see them. If // we want to skip them, the code below needs to move up into the - // above test 'visitor2 != null'. + // above test 'visitor2 is not null'. if (action == AstVisitAction.Continue) { for (int index = 0; index < Attributes.Count; index++) @@ -2891,7 +2891,7 @@ public UsingStatementAst(IScriptExtent extent, StringConstantExpressionAst alias /// public override Ast Copy() { - var copy = Alias != null + var copy = Alias is not null ? new UsingStatementAst(Extent, UsingStatementKind, Name, Alias) : new UsingStatementAst(Extent, UsingStatementKind, Name); copy.ModuleInfo = ModuleInfo; @@ -2904,33 +2904,33 @@ public override Ast Copy() internal override object Accept(ICustomAstVisitor visitor) { var visitor2 = visitor as ICustomAstVisitor2; - return visitor2 != null ? visitor2.VisitUsingStatement(this) : null; + return visitor2 is not null ? visitor2.VisitUsingStatement(this) : null; } internal override AstVisitAction InternalVisit(AstVisitor visitor) { var action = AstVisitAction.Continue; var visitor2 = visitor as AstVisitor2; - if (visitor2 != null) + if (visitor2 is not null) { action = visitor2.VisitUsingStatement(this); if (action != AstVisitAction.Continue) return visitor.CheckForPostAction(this, action); } - if (Name != null) + if (Name is not null) action = Name.InternalVisit(visitor); if (action != AstVisitAction.Continue) return visitor.CheckForPostAction(this, action); - if (ModuleSpecification != null) + if (ModuleSpecification is not null) action = ModuleSpecification.InternalVisit(visitor); if (action != AstVisitAction.Continue) return visitor.CheckForPostAction(this, action); - if (Alias != null) + if (Alias is not null) action = Alias.InternalVisit(visitor); return visitor.CheckForPostAction(this, action); @@ -3038,13 +3038,13 @@ public PropertyMemberAst(IScriptExtent extent, string name, TypeConstraintAst pr } Name = name; - if (propertyType != null) + if (propertyType is not null) { PropertyType = propertyType; SetParent(PropertyType); } - if (attributes != null) + if (attributes is not null) { this.Attributes = new ReadOnlyCollection(attributes.ToArray()); SetParents(Attributes); @@ -3057,7 +3057,7 @@ public PropertyMemberAst(IScriptExtent extent, string name, TypeConstraintAst pr PropertyAttributes = propertyAttributes; InitialValue = initialValue; - if (InitialValue != null) + if (InitialValue is not null) { SetParent(InitialValue); } @@ -3121,7 +3121,7 @@ public override Ast Copy() internal override string GetTooltip() { - var type = PropertyType != null ? PropertyType.TypeName.FullName : "object"; + var type = PropertyType is not null ? PropertyType.TypeName.FullName : "object"; return IsStatic ? "static " + type + " " + Name : type + " " + Name; @@ -3132,20 +3132,20 @@ internal override string GetTooltip() internal override object Accept(ICustomAstVisitor visitor) { var visitor2 = visitor as ICustomAstVisitor2; - return visitor2 != null ? visitor2.VisitPropertyMember(this) : null; + return visitor2 is not null ? visitor2.VisitPropertyMember(this) : null; } internal override AstVisitAction InternalVisit(AstVisitor visitor) { var action = AstVisitAction.Continue; var visitor2 = visitor as AstVisitor2; - if (visitor2 != null) + if (visitor2 is not null) { action = visitor2.VisitPropertyMember(this); if (action == AstVisitAction.SkipChildren) return visitor.CheckForPostAction(this, AstVisitAction.Continue); - if (action == AstVisitAction.Continue && PropertyType != null) + if (action == AstVisitAction.Continue && PropertyType is not null) action = PropertyType.InternalVisit(visitor); if (action == AstVisitAction.Continue) @@ -3158,7 +3158,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) } } - if (action == AstVisitAction.Continue && InitialValue != null) + if (action == AstVisitAction.Continue && InitialValue is not null) action = InitialValue.InternalVisit(visitor); } @@ -3225,13 +3225,13 @@ public FunctionMemberAst(IScriptExtent extent, FunctionDefinitionAst functionDef throw PSTraceSource.NewArgumentException(nameof(methodAttributes)); } - if (returnType != null) + if (returnType is not null) { ReturnType = returnType; SetParent(returnType); } - if (attributes != null) + if (attributes is not null) { this.Attributes = new ReadOnlyCollection(attributes.ToArray()); SetParents(Attributes); @@ -3352,14 +3352,14 @@ internal override string GetTooltip() internal override object Accept(ICustomAstVisitor visitor) { var visitor2 = visitor as ICustomAstVisitor2; - return visitor2 != null ? visitor2.VisitFunctionMember(this) : null; + return visitor2 is not null ? visitor2.VisitFunctionMember(this) : null; } internal override AstVisitAction InternalVisit(AstVisitor visitor) { var action = AstVisitAction.Continue; var visitor2 = visitor as AstVisitor2; - if (visitor2 != null) + if (visitor2 is not null) { action = visitor2.VisitFunctionMember(this); if (action == AstVisitAction.SkipChildren) @@ -3374,7 +3374,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) } } - if (action == AstVisitAction.Continue && ReturnType != null) + if (action == AstVisitAction.Continue && ReturnType is not null) action = ReturnType.InternalVisit(visitor); if (action == AstVisitAction.Continue) @@ -3610,7 +3610,7 @@ public FunctionDefinitionAst(IScriptExtent extent, this.IsWorkflow = isWorkflow; this.Name = name; - if (parameters != null && parameters.Any()) + if (parameters is not null && parameters.Any()) { this.Parameters = new ReadOnlyCollection(parameters.ToArray()); SetParents(Parameters); @@ -3676,7 +3676,7 @@ public CommentHelpInfo GetHelpContent() { Dictionary scriptBlockTokenCache = new Dictionary(); var commentTokens = HelpCommentsParser.GetHelpCommentTokens(this, scriptBlockTokenCache); - if (commentTokens != null) + if (commentTokens is not null) { return HelpCommentsParser.GetHelpContents(commentTokens.Item1, commentTokens.Item2); } @@ -3702,7 +3702,7 @@ public CommentHelpInfo GetHelpContent(Dictionary scriptBlockTokenC } var commentTokens = HelpCommentsParser.GetHelpCommentTokens(this, scriptBlockTokenCache); - if (commentTokens != null) + if (commentTokens is not null) { return HelpCommentsParser.GetHelpContents(commentTokens.Item1, commentTokens.Item2); } @@ -3723,14 +3723,14 @@ public override Ast Copy() internal string GetParamTextFromParameterList(Tuple, string> usingVariablesTuple = null) { - Diagnostics.Assert(Parameters != null, "Caller makes sure that Parameters is not null before calling this method."); + Diagnostics.Assert(Parameters is not null, "Caller makes sure that Parameters is not null before calling this method."); string additionalNewUsingParams = null; IEnumerator orderedUsingVars = null; - if (usingVariablesTuple != null) + if (usingVariablesTuple is not null) { Diagnostics.Assert( - usingVariablesTuple.Item1 != null && usingVariablesTuple.Item1.Count > 0 && !string.IsNullOrEmpty(usingVariablesTuple.Item2), + usingVariablesTuple.Item1 is not null && usingVariablesTuple.Item1.Count > 0 && !string.IsNullOrEmpty(usingVariablesTuple.Item2), "Caller makes sure the value passed in is not null or empty."); orderedUsingVars = usingVariablesTuple.Item1.OrderBy(varAst => varAst.Extent.StartOffset).GetEnumerator(); additionalNewUsingParams = usingVariablesTuple.Item2; @@ -3739,7 +3739,7 @@ internal string GetParamTextFromParameterList(Tuple, var sb = new StringBuilder("param("); string separator = string.Empty; - if (additionalNewUsingParams != null) + if (additionalNewUsingParams is not null) { // Add the $using variable parameters if necessary sb.Append(additionalNewUsingParams); @@ -3750,7 +3750,7 @@ internal string GetParamTextFromParameterList(Tuple, { var param = Parameters[i]; sb.Append(separator); - sb.Append(orderedUsingVars != null + sb.Append(orderedUsingVars is not null ? param.GetParamTextWithDollarUsingHandling(orderedUsingVars) : param.ToString()); separator = ", "; @@ -3776,7 +3776,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) return visitor.CheckForPostAction(this, AstVisitAction.Continue); if (action == AstVisitAction.Continue) { - if (Parameters != null) + if (Parameters is not null) { for (int index = 0; index < Parameters.Count; index++) { @@ -3804,12 +3804,12 @@ bool IParameterMetadataProvider.HasAnyScriptBlockAttributes() RuntimeDefinedParameterDictionary IParameterMetadataProvider.GetParameterMetadata(bool automaticPositions, ref bool usesCmdletBinding) { - if (Parameters != null) + if (Parameters is not null) { return Compiler.GetParameterMetaData(Parameters, automaticPositions, ref usesCmdletBinding); } - if (Body.ParamBlock != null) + if (Body.ParamBlock is not null) { return Compiler.GetParameterMetaData(Body.ParamBlock.Parameters, automaticPositions, ref usesCmdletBinding); } @@ -3829,7 +3829,7 @@ IEnumerable IParameterMetadataProvider.GetExperimentalAtt ReadOnlyCollection IParameterMetadataProvider.Parameters { - get { return Parameters ?? (Body.ParamBlock != null ? Body.ParamBlock.Parameters : null); } + get { return Parameters ?? (Body.ParamBlock is not null ? Body.ParamBlock.Parameters : null); } } PowerShell IParameterMetadataProvider.GetPowerShell(ExecutionContext context, Dictionary variables, bool isTrustedInput, @@ -3863,11 +3863,11 @@ Tuple IParameterMetadataProvider.GetWithInputHandlingForInvokeCo bool IParameterMetadataProvider.UsesCmdletBinding() { bool usesCmdletBinding = false; - if (Parameters != null) + if (Parameters is not null) { usesCmdletBinding = ParamBlockAst.UsesCmdletBinding(Parameters); } - else if (Body.ParamBlock != null) + else if (Body.ParamBlock is not null) { usesCmdletBinding = ((IParameterMetadataProvider)Body).UsesCmdletBinding(); } @@ -3907,7 +3907,7 @@ public IfStatementAst(IScriptExtent extent, IEnumerable clauses, State this.Clauses = new ReadOnlyCollection(clauses.ToArray()); SetParents(Clauses); - if (elseClause != null) + if (elseClause is not null) { this.ElseClause = elseClause; SetParent(elseClause); @@ -3970,7 +3970,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) } } - if (action == AstVisitAction.Continue && ElseClause != null) + if (action == AstVisitAction.Continue && ElseClause is not null) { action = ElseClause.InternalVisit(visitor); } @@ -4015,7 +4015,7 @@ public DataStatementAst(IScriptExtent extent, } this.Variable = variableName; - if (commandsAllowed != null && commandsAllowed.Any()) + if (commandsAllowed is not null && commandsAllowed.Any()) { this.CommandsAllowed = new ReadOnlyCollection(commandsAllowed.ToArray()); SetParents(CommandsAllowed); @@ -4108,7 +4108,7 @@ protected LabeledStatementAst(IScriptExtent extent, string label, PipelineBaseAs } this.Label = label; - if (condition != null) + if (condition is not null) { this.Condition = condition; SetParent(condition); @@ -4244,7 +4244,7 @@ public ForEachStatementAst(IScriptExtent extent, : this(extent, label, flags, variable, expression, body) { this.ThrottleLimit = throttleLimit; - if (throttleLimit != null) + if (throttleLimit is not null) { SetParent(throttleLimit); } @@ -4274,7 +4274,7 @@ public override Ast Copy() var newExpression = CopyElement(this.Condition); var newBody = CopyElement(this.Body); - if (this.ThrottleLimit != null) + if (this.ThrottleLimit is not null) { var newThrottleLimit = CopyElement(this.ThrottleLimit); return new ForEachStatementAst(this.Extent, this.Label, this.Flags, newThrottleLimit, @@ -4333,13 +4333,13 @@ public ForStatementAst(IScriptExtent extent, StatementBlockAst body) : base(extent, label, condition, body) { - if (initializer != null) + if (initializer is not null) { this.Initializer = initializer; SetParent(initializer); } - if (iterator != null) + if (iterator is not null) { this.Iterator = iterator; SetParent(iterator); @@ -4381,11 +4381,11 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) var action = visitor.VisitForStatement(this); if (action == AstVisitAction.SkipChildren) return visitor.CheckForPostAction(this, AstVisitAction.Continue); - if (action == AstVisitAction.Continue && Initializer != null) + if (action == AstVisitAction.Continue && Initializer is not null) action = Initializer.InternalVisit(visitor); - if (action == AstVisitAction.Continue && Condition != null) + if (action == AstVisitAction.Continue && Condition is not null) action = Condition.InternalVisit(visitor); - if (action == AstVisitAction.Continue && Iterator != null) + if (action == AstVisitAction.Continue && Iterator is not null) action = Iterator.InternalVisit(visitor); if (action == AstVisitAction.Continue) action = Body.InternalVisit(visitor); @@ -4652,9 +4652,9 @@ public SwitchStatementAst(IScriptExtent extent, this.Flags = flags; this.Clauses = new ReadOnlyCollection( - (clauses != null && clauses.Any()) ? clauses.ToArray() : s_emptyClauseArray); + (clauses is not null && clauses.Any()) ? clauses.ToArray() : s_emptyClauseArray); SetParents(Clauses); - if (@default != null) + if (@default is not null) { this.Default = @default; SetParent(@default); @@ -4729,7 +4729,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) } } - if (action == AstVisitAction.Continue && Default != null) + if (action == AstVisitAction.Continue && Default is not null) action = Default.InternalVisit(visitor); return visitor.CheckForPostAction(this, action); } @@ -4766,7 +4766,7 @@ public CatchClauseAst(IScriptExtent extent, IEnumerable catch throw PSTraceSource.NewArgumentNullException(nameof(body)); } - if (catchTypes != null) + if (catchTypes is not null) { this.CatchTypes = new ReadOnlyCollection(catchTypes.ToArray()); SetParents(CatchTypes); @@ -4877,7 +4877,7 @@ public TryStatementAst(IScriptExtent extent, this.Body = body; SetParent(body); - if (catchClauses != null) + if (catchClauses is not null) { this.CatchClauses = new ReadOnlyCollection(catchClauses.ToArray()); SetParents(CatchClauses); @@ -4887,7 +4887,7 @@ public TryStatementAst(IScriptExtent extent, this.CatchClauses = s_emptyCatchClauses; } - if (@finally != null) + if (@finally is not null) { this.Finally = @finally; SetParent(@finally); @@ -4946,7 +4946,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) } } - if (action == AstVisitAction.Continue && Finally != null) + if (action == AstVisitAction.Continue && Finally is not null) action = Finally.InternalVisit(visitor); return visitor.CheckForPostAction(this, action); } @@ -4978,7 +4978,7 @@ public TrapStatementAst(IScriptExtent extent, TypeConstraintAst trapType, Statem throw PSTraceSource.NewArgumentNullException(nameof(body)); } - if (trapType != null) + if (trapType is not null) { this.TrapType = trapType; SetParent(trapType); @@ -5020,7 +5020,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) var action = visitor.VisitTrap(this); if (action == AstVisitAction.SkipChildren) return visitor.CheckForPostAction(this, AstVisitAction.Continue); - if (action == AstVisitAction.Continue && TrapType != null) + if (action == AstVisitAction.Continue && TrapType is not null) action = TrapType.InternalVisit(visitor); if (action == AstVisitAction.Continue) action = Body.InternalVisit(visitor); @@ -5050,7 +5050,7 @@ public class BreakStatementAst : StatementAst public BreakStatementAst(IScriptExtent extent, ExpressionAst label) : base(extent) { - if (label != null) + if (label is not null) { this.Label = label; SetParent(label); @@ -5083,7 +5083,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) var action = visitor.VisitBreakStatement(this); if (action == AstVisitAction.SkipChildren) return visitor.CheckForPostAction(this, AstVisitAction.Continue); - if (action == AstVisitAction.Continue && Label != null) + if (action == AstVisitAction.Continue && Label is not null) action = Label.InternalVisit(visitor); return visitor.CheckForPostAction(this, action); } @@ -5107,7 +5107,7 @@ public class ContinueStatementAst : StatementAst public ContinueStatementAst(IScriptExtent extent, ExpressionAst label) : base(extent) { - if (label != null) + if (label is not null) { this.Label = label; SetParent(label); @@ -5140,7 +5140,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) var action = visitor.VisitContinueStatement(this); if (action == AstVisitAction.SkipChildren) return visitor.CheckForPostAction(this, AstVisitAction.Continue); - if (action == AstVisitAction.Continue && Label != null) + if (action == AstVisitAction.Continue && Label is not null) action = Label.InternalVisit(visitor); return visitor.CheckForPostAction(this, action); } @@ -5164,7 +5164,7 @@ public class ReturnStatementAst : StatementAst public ReturnStatementAst(IScriptExtent extent, PipelineBaseAst pipeline) : base(extent) { - if (pipeline != null) + if (pipeline is not null) { this.Pipeline = pipeline; SetParent(pipeline); @@ -5197,7 +5197,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) var action = visitor.VisitReturnStatement(this); if (action == AstVisitAction.SkipChildren) return visitor.CheckForPostAction(this, AstVisitAction.Continue); - if (action == AstVisitAction.Continue && Pipeline != null) + if (action == AstVisitAction.Continue && Pipeline is not null) action = Pipeline.InternalVisit(visitor); return visitor.CheckForPostAction(this, action); } @@ -5221,7 +5221,7 @@ public class ExitStatementAst : StatementAst public ExitStatementAst(IScriptExtent extent, PipelineBaseAst pipeline) : base(extent) { - if (pipeline != null) + if (pipeline is not null) { this.Pipeline = pipeline; SetParent(pipeline); @@ -5254,7 +5254,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) var action = visitor.VisitExitStatement(this); if (action == AstVisitAction.SkipChildren) return visitor.CheckForPostAction(this, AstVisitAction.Continue); - if (action == AstVisitAction.Continue && Pipeline != null) + if (action == AstVisitAction.Continue && Pipeline is not null) action = Pipeline.InternalVisit(visitor); return visitor.CheckForPostAction(this, action); } @@ -5278,7 +5278,7 @@ public class ThrowStatementAst : StatementAst public ThrowStatementAst(IScriptExtent extent, PipelineBaseAst pipeline) : base(extent) { - if (pipeline != null) + if (pipeline is not null) { this.Pipeline = pipeline; SetParent(pipeline); @@ -5306,11 +5306,11 @@ public bool IsRethrow { get { - if (Pipeline != null) + if (Pipeline is not null) return false; var parent = Parent; - while (parent != null) + while (parent is not null) { if (parent is CatchClauseAst) { @@ -5345,7 +5345,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) var action = visitor.VisitThrowStatement(this); if (action == AstVisitAction.SkipChildren) return visitor.CheckForPostAction(this, AstVisitAction.Continue); - if (action == AstVisitAction.Continue && Pipeline != null) + if (action == AstVisitAction.Continue && Pipeline is not null) action = Pipeline.InternalVisit(visitor); return visitor.CheckForPostAction(this, action); } @@ -5609,7 +5609,7 @@ public override ExpressionAst GetPureExpression() } CommandExpressionAst expr = PipelineElements[0] as CommandExpressionAst; - if (expr != null && expr.Redirections.Count == 0) + if (expr is not null && expr.Redirections.Count == 0) { return expr.Expression; } @@ -5715,7 +5715,7 @@ public CommandParameterAst(IScriptExtent extent, string parameterName, Expressio } this.ParameterName = parameterName; - if (argument != null) + if (argument is not null) { this.Argument = argument; SetParent(argument); @@ -5763,7 +5763,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) var action = visitor.VisitCommandParameter(this); if (action == AstVisitAction.SkipChildren) return visitor.CheckForPostAction(this, AstVisitAction.Continue); - if (Argument != null && action == AstVisitAction.Continue) + if (Argument is not null && action == AstVisitAction.Continue) { action = Argument.InternalVisit(visitor); } @@ -5795,7 +5795,7 @@ public abstract class CommandBaseAst : StatementAst protected CommandBaseAst(IScriptExtent extent, IEnumerable redirections) : base(extent) { - if (redirections != null) + if (redirections is not null) { this.Redirections = new ReadOnlyCollection(redirections.ToArray()); SetParents(Redirections); @@ -5879,7 +5879,7 @@ public CommandAst(IScriptExtent extent, public string GetCommandName() { var name = CommandElements[0] as StringConstantExpressionAst; - return name != null ? name.Value : null; + return name is not null ? name.Value : null; } /// @@ -6237,13 +6237,13 @@ public AssignmentStatementAst(IScriptExtent extent, ExpressionAst left, TokenKin // If the assignment is just an expression and the expression is not backgrounded then // remove the pipeline wrapping the expression. var pipelineAst = right as PipelineAst; - if (pipelineAst != null && !pipelineAst.Background) + if (pipelineAst is not null && !pipelineAst.Background) { if (pipelineAst.PipelineElements.Count == 1) { var commandExpressionAst = pipelineAst.PipelineElements[0] as CommandExpressionAst; - if (commandExpressionAst != null) + if (commandExpressionAst is not null) { right = commandExpressionAst; right.ClearParent(); @@ -6298,7 +6298,7 @@ public override Ast Copy() public IEnumerable GetAssignmentTargets() { var arrayExpression = Left as ArrayLiteralAst; - if (arrayExpression != null) + if (arrayExpression is not null) { foreach (var element in arrayExpression.Elements) { @@ -6431,14 +6431,14 @@ public override Ast Copy() internal override object Accept(ICustomAstVisitor visitor) { var visitor2 = visitor as ICustomAstVisitor2; - return visitor2 != null ? visitor2.VisitConfigurationDefinition(this) : null; + return visitor2 is not null ? visitor2.VisitConfigurationDefinition(this) : null; } internal override AstVisitAction InternalVisit(AstVisitor visitor) { var action = AstVisitAction.Continue; var visitor2 = visitor as AstVisitor2; - if (visitor2 != null) + if (visitor2 is not null) { action = visitor2.VisitConfigurationDefinition(this); if (action == AstVisitAction.SkipChildren) @@ -6565,7 +6565,7 @@ internal PipelineAst GenerateSetItemPipelineAst() // $toBody.Remove(""ConfigurationData"") // $ConfigurationData = $psboundparameters[""ConfigurationData""] // $Outputpath = $psboundparameters[""Outputpath""] - if (Body.ScriptBlock.ParamBlock != null) + if (Body.ScriptBlock.ParamBlock is not null) { paramAsts.AddRange(Body.ScriptBlock.ParamBlock.Parameters.Select(parameterAst => (ParameterAst)parameterAst.Copy())); } @@ -6674,21 +6674,21 @@ private static bool IsImportCommand(StatementAst stmt, List(resourceNameEvaluated); } - if (moduleNames != null) + if (moduleNames is not null) { object moduleNameEvaluated; IsConstantValueVisitor.IsConstant(moduleNames.Value, out moduleNameEvaluated, true, true); moduleNamesTyped = LanguagePrimitives.ConvertTo(moduleNameEvaluated); } - if (moduleVersion != null) + if (moduleVersion is not null) { object moduleVersionEvaluated; IsConstantValueVisitor.IsConstant(moduleVersion.Value, out moduleVersionEvaluated, true, true); @@ -6704,7 +6704,7 @@ private static bool IsImportCommand(StatementAst stmt, List only in the case, if -ModuleName specified. // Override ModuleName versions. - if (moduleNamesTyped != null && moduleNamesTyped.Length == 1) + if (moduleNamesTyped is not null && moduleNamesTyped.Length == 1) { for (int i = 0; i < moduleNamesTyped.Length; i++) { @@ -6748,7 +6748,7 @@ private static IEnumerable ConfigurationBuildInParameters Token[] tokens; ParseError[] errors; var sba = Parser.ParseInput(ConfigurationBuildInParametersStr, out tokens, out errors); - if (sba != null) + if (sba is not null) { foreach (var parameterAst in sba.ParamBlock.Parameters) { @@ -6774,7 +6774,7 @@ private static IEnumerable ConfigurationBuildInParameterAttribAsts Token[] tokens; ParseError[] errors; var sba = Parser.ParseInput(ConfigurationBuildInParametersStr, out tokens, out errors); - if (sba != null) + if (sba is not null) { if (s_configurationBuildInParameters is null) { @@ -6816,7 +6816,7 @@ private static IEnumerable ConfigurationExtraParameterStatements $toBody.Remove(""ConfigurationData"") $ConfigurationData = $psboundparameters[""ConfigurationData""] $Outputpath = $psboundparameters[""Outputpath""]", out tokens, out errors); - if (sba != null) + if (sba is not null) { foreach (var statementAst in sba.EndBlock.Statements) { @@ -6898,14 +6898,14 @@ public override Ast Copy() internal override object Accept(ICustomAstVisitor visitor) { var visitor2 = visitor as ICustomAstVisitor2; - return visitor2 != null ? visitor2.VisitDynamicKeywordStatement(this) : null; + return visitor2 is not null ? visitor2.VisitDynamicKeywordStatement(this) : null; } internal override AstVisitAction InternalVisit(AstVisitor visitor) { var action = AstVisitAction.Continue; var visitor2 = visitor as AstVisitor2; - if (visitor2 != null) + if (visitor2 is not null) { action = visitor2.VisitDynamicKeywordStatement(this); if (action == AstVisitAction.SkipChildren) @@ -6955,7 +6955,7 @@ internal DynamicKeyword Keyword internal PipelineAst GenerateCommandCallPipelineAst() { - if (_commandCallPipelineAst != null) + if (_commandCallPipelineAst is not null) return _commandCallPipelineAst; ///////////////////////////////////////////////////////////////////////// @@ -7021,7 +7021,7 @@ internal PipelineAst GenerateCommandCallPipelineAst() // in the hash literal expression and map them to parameters. // We've already checked to make sure that they're all valid names. // - if (hashtable != null) + if (hashtable is not null) { bool isHashtableValid = true; // @@ -7226,7 +7226,7 @@ internal virtual bool ShouldPreserveOutputInCaseOfException() } var parenExpressionAst = pipelineAst.Parent as ParenExpressionAst; - if (parenExpressionAst != null) + if (parenExpressionAst is not null) { return parenExpressionAst.ShouldPreserveOutputInCaseOfException(); } @@ -7687,7 +7687,7 @@ private ISupportsAssignment GetActualAssignableAst() { ExpressionAst child = this; var childAttributeAst = child as AttributedExpressionAst; - while (childAttributeAst != null) + while (childAttributeAst is not null) { child = childAttributeAst.Child; childAttributeAst = child as AttributedExpressionAst; @@ -7701,7 +7701,7 @@ private List GetAttributes() { var attributes = new List(); var childAttributeAst = this; - while (childAttributeAst != null) + while (childAttributeAst is not null) { attributes.Add(childAttributeAst.Attribute); childAttributeAst = childAttributeAst.Child as AttributedExpressionAst; @@ -7810,7 +7810,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) IAssignableValue ISupportsAssignment.GetAssignableValue() { var varExpr = Child as VariableExpressionAst; - if (varExpr != null && varExpr.TupleIndex >= 0) + if (varExpr is not null && varExpr.TupleIndex >= 0) { // In the common case of a single cast on the lhs of an assignment, we may have saved the type of the // variable in the mutable tuple, so conversions will get generated elsewhere, and we can just use @@ -7966,7 +7966,7 @@ public class InvokeMemberExpressionAst : MemberExpressionAst, ISupportsAssignmen public InvokeMemberExpressionAst(IScriptExtent extent, ExpressionAst expression, CommandElementAst method, IEnumerable arguments, bool @static) : base(extent, expression, method, @static) { - if (arguments != null && arguments.Any()) + if (arguments is not null && arguments.Any()) { this.Arguments = new ReadOnlyCollection(arguments.ToArray()); SetParents(Arguments); @@ -8034,7 +8034,7 @@ internal AstVisitAction InternalVisitChildren(AstVisitor visitor) var action = Expression.InternalVisit(visitor); if (action == AstVisitAction.Continue) action = Member.InternalVisit(visitor); - if (action == AstVisitAction.Continue && Arguments != null) + if (action == AstVisitAction.Continue && Arguments is not null) { for (int index = 0; index < Arguments.Count; index++) { @@ -8090,7 +8090,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) { AstVisitAction action = AstVisitAction.Continue; var visitor2 = visitor as AstVisitor2; - if (visitor2 != null) + if (visitor2 is not null) { action = visitor2.VisitBaseCtorInvokeMemberExpression(this); if (action == AstVisitAction.SkipChildren) @@ -8105,7 +8105,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) internal override object Accept(ICustomAstVisitor visitor) { var visitor2 = visitor as ICustomAstVisitor2; - return visitor2 != null ? visitor2.VisitBaseCtorInvokeMemberExpression(this) : null; + return visitor2 is not null ? visitor2.VisitBaseCtorInvokeMemberExpression(this) : null; } } @@ -8232,7 +8232,7 @@ public TypeName(IScriptExtent extent, string name, string assembly) /// /// Returns the full name of the type. /// - public string FullName { get { return AssemblyName != null ? _name + "," + AssemblyName : _name; } } + public string FullName { get { return AssemblyName is not null ? _name + "," + AssemblyName : _name; } } /// /// Returns the name of the type, w/o any assembly name if one was specified. @@ -8277,7 +8277,7 @@ internal bool HasDefaultCtor() foreach (var member in _typeDefinitionAst.Members) { var function = member as FunctionMemberAst; - if (function != null) + if (function is not null) { if (function.IsConstructor) { @@ -8307,8 +8307,8 @@ public Type GetReflectionType() if (_type is null) { Exception e; - Type type = _typeDefinitionAst != null ? _typeDefinitionAst.Type : TypeResolver.ResolveTypeName(this, out e); - if (type != null) + Type type = _typeDefinitionAst is not null ? _typeDefinitionAst.Type : TypeResolver.ResolveTypeName(this, out e); + if (type is not null) { try { @@ -8318,7 +8318,7 @@ public Type GetReflectionType() { // If the value of 'type' comes from typeBuilder.AsType(), then the value of 'type.GetTypeInfo()' // is actually the TypeBuilder instance itself. This is the same on both FullCLR and CoreCLR. - Diagnostics.Assert(_typeDefinitionAst != null, "_typeDefinitionAst can never be null"); + Diagnostics.Assert(_typeDefinitionAst is not null, "_typeDefinitionAst can never be null"); return type; } @@ -8344,7 +8344,7 @@ public Type GetReflectionAttributeType() { var attrTypeName = new TypeName(_extent, FullName + "Attribute"); result = attrTypeName.GetReflectionType(); - if (result != null && !typeof(Attribute).IsAssignableFrom(result)) + if (result is not null && !typeof(Attribute).IsAssignableFrom(result)) { result = null; } @@ -8503,7 +8503,7 @@ public string FullName sb.Append(']'); var assemblyName = TypeName.AssemblyName; - if (assemblyName != null) + if (assemblyName is not null) { sb.Append(','); sb.Append(assemblyName); @@ -8583,7 +8583,7 @@ public Type GetReflectionType() { Type generic = GetGenericType(TypeName.GetReflectionType()); - if (generic != null && generic.ContainsGenericParameters) + if (generic is not null && generic.ContainsGenericParameters) { var argumentList = new List(); foreach (var arg in GenericArguments) @@ -8669,7 +8669,7 @@ public Type GetReflectionAttributeType() } } - if (generic != null && generic.ContainsGenericParameters) + if (generic is not null && generic.ContainsGenericParameters) { type = generic.MakeGenericType((from arg in GenericArguments select arg.GetReflectionType()).ToArray()); Interlocked.CompareExchange(ref _cachedType, type, null); @@ -8786,7 +8786,7 @@ private string GetName(bool includeAssemblyName) if (includeAssemblyName) { var assemblyName = ElementType.AssemblyName; - if (assemblyName != null) + if (assemblyName is not null) { sb.Append(','); sb.Append(assemblyName); @@ -8866,7 +8866,7 @@ public Type GetReflectionType() if (_cachedType is null) { Type elementType = ElementType.GetReflectionType(); - if (elementType != null) + if (elementType is not null) { Type type = Rank == 1 ? elementType.MakeArrayType() : elementType.MakeArrayType(Rank); try @@ -9203,7 +9203,7 @@ internal bool IsSafeVariableReference(HashSet validVariables, ref bool u if (this.VariablePath.IsAnyLocal()) { var varName = this.VariablePath.UnqualifiedPath; - if (((validVariables != null) && validVariables.Contains(varName)) || + if (((validVariables is not null) && validVariables.Contains(varName)) || varName.Equals(SpecialVariables.Args, StringComparison.OrdinalIgnoreCase)) { ok = true; @@ -9366,7 +9366,7 @@ public override Ast Copy() /// public override Type StaticType { - get { return Value != null ? Value.GetType() : typeof(object); } + get { return Value is not null ? Value.GetType() : typeof(object); } } #region Visitors @@ -9554,7 +9554,7 @@ public ExpandableStringExpressionAst(IScriptExtent extent, var ast = Language.Parser.ScanString(value); var expandableStringAst = ast as ExpandableStringExpressionAst; - if (expandableStringAst != null) + if (expandableStringAst is not null) { this.FormatExpression = expandableStringAst.FormatExpression; this.NestedExpressions = expandableStringAst.NestedExpressions; @@ -9596,7 +9596,7 @@ private ExpandableStringExpressionAst(IScriptExtent extent, string value, string StringConstantType type, IEnumerable nestedExpressions) : base(extent) { - Diagnostics.Assert(nestedExpressions != null && nestedExpressions.Any(), "Must specify non-empty expressions."); + Diagnostics.Assert(nestedExpressions is not null && nestedExpressions.Any(), "Must specify non-empty expressions."); this.FormatExpression = formatString; this.Value = value; @@ -9656,7 +9656,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) var action = visitor.VisitExpandableStringExpression(this); if (action == AstVisitAction.SkipChildren) return visitor.CheckForPostAction(this, AstVisitAction.Continue); - if (action == AstVisitAction.Continue && NestedExpressions != null) + if (action == AstVisitAction.Continue && NestedExpressions is not null) { for (int index = 0; index < NestedExpressions.Count; index++) { @@ -9840,7 +9840,7 @@ public class HashtableAst : ExpressionAst public HashtableAst(IScriptExtent extent, IEnumerable keyValuePairs) : base(extent) { - if (keyValuePairs != null) + if (keyValuePairs is not null) { this.KeyValuePairs = new ReadOnlyCollection(keyValuePairs.ToArray()); SetParents(KeyValuePairs); @@ -10193,10 +10193,10 @@ private static VariableExpressionAst ExtractUsingVariableImpl(ExpressionAst expr var usingExpr = expression as UsingExpressionAst; VariableExpressionAst variableExpr; - if (usingExpr != null) + if (usingExpr is not null) { variableExpr = usingExpr.SubExpression as VariableExpressionAst; - if (variableExpr != null) + if (variableExpr is not null) { return variableExpr; } @@ -10205,10 +10205,10 @@ private static VariableExpressionAst ExtractUsingVariableImpl(ExpressionAst expr } var indexExpr = expression as IndexExpressionAst; - if (indexExpr != null) + if (indexExpr is not null) { variableExpr = indexExpr.Target as VariableExpressionAst; - if (variableExpr != null) + if (variableExpr is not null) { return variableExpr; } @@ -10217,10 +10217,10 @@ private static VariableExpressionAst ExtractUsingVariableImpl(ExpressionAst expr } var memberExpr = expression as MemberExpressionAst; - if (memberExpr != null) + if (memberExpr is not null) { variableExpr = memberExpr.Expression as VariableExpressionAst; - if (variableExpr != null) + if (variableExpr is not null) { return variableExpr; } diff --git a/src/System.Management.Automation/engine/parser/token.cs b/src/System.Management.Automation/engine/parser/token.cs index 3f78e299a88..8415ad3047b 100644 --- a/src/System.Management.Automation/engine/parser/token.cs +++ b/src/System.Management.Automation/engine/parser/token.cs @@ -1402,7 +1402,7 @@ public class StringExpandableToken : StringToken internal StringExpandableToken(InternalScriptExtent scriptExtent, TokenKind tokenKind, string value, string formatString, List nestedTokens, TokenFlags flags) : base(scriptExtent, tokenKind, flags, value) { - if (nestedTokens != null && nestedTokens.Count > 0) + if (nestedTokens is not null && nestedTokens.Count > 0) { _nestedTokens = new ReadOnlyCollection(nestedTokens.ToArray()); } @@ -1413,7 +1413,7 @@ internal StringExpandableToken(InternalScriptExtent scriptExtent, TokenKind toke internal static void ToDebugString(ReadOnlyCollection nestedTokens, StringBuilder sb, int indent) { - Diagnostics.Assert(nestedTokens != null, "caller to verify"); + Diagnostics.Assert(nestedTokens is not null, "caller to verify"); foreach (Token token in nestedTokens) { @@ -1442,7 +1442,7 @@ internal override string ToDebugString(int indent) StringBuilder sb = new StringBuilder(); sb.Append(base.ToDebugString(indent)); - if (_nestedTokens != null) + if (_nestedTokens is not null) { ToDebugString(_nestedTokens, sb, indent); } diff --git a/src/System.Management.Automation/engine/parser/tokenizer.cs b/src/System.Management.Automation/engine/parser/tokenizer.cs index bbfb5e4c075..96983ddc8ba 100644 --- a/src/System.Management.Automation/engine/parser/tokenizer.cs +++ b/src/System.Management.Automation/engine/parser/tokenizer.cs @@ -363,7 +363,7 @@ internal static class DynamicKeywordExtension internal static bool IsMetaDSCResource(this DynamicKeyword keyword) { string implementingModule = keyword.ImplementingModule; - if (implementingModule != null) + if (implementingModule is not null) { return implementingModule.Equals(DscClassCache.DefaultModuleInfoForMetaConfigResource.Item1, StringComparison.OrdinalIgnoreCase); } @@ -805,7 +805,7 @@ internal TokenizerState StartNestedScan(UnscannedSubExprToken nestedText) _script = nestedText.Value; _tokenStart = 0; _skippedCharOffsets = nestedText.SkippedCharOffsets; - TokenList = (TokenList != null) ? new List() : null; + TokenList = (TokenList is not null) ? new List() : null; return ts; } @@ -983,7 +983,7 @@ private void ScanNewline(char c) NormalizeCRLF(c); // Memory optimization: only create the token if it will be stored - if (TokenList != null) + if (TokenList is not null) { NewToken(TokenKind.NewLine); } @@ -994,7 +994,7 @@ private void ScanSemicolon() _tokenStart = _currentIndex - 1; // Memory optimization: only create the token if it will be stored - if (TokenList != null) + if (TokenList is not null) { NewToken(TokenKind.Semi); } @@ -1006,7 +1006,7 @@ private void ScanLineContinuation(char c) NormalizeCRLF(c); // Memory optimization: only create the token if it will be stored - if (TokenList != null) + if (TokenList is not null) { NewToken(TokenKind.LineContinuation); } @@ -1029,7 +1029,7 @@ internal void Resync(Token token) internal void Resync(int start) { int adjustment = _nestedTokensAdjustment; - if (_skippedCharOffsets != null) + if (_skippedCharOffsets is not null) { for (int i = _nestedTokensAdjustment; i < start - 1 && i < _skippedCharOffsets.Length; ++i) { @@ -1050,18 +1050,18 @@ internal void Resync(int start) _currentIndex = 0; } - if (FirstToken != null && _currentIndex <= ((InternalScriptExtent)FirstToken.Extent).StartOffset) + if (FirstToken is not null && _currentIndex <= ((InternalScriptExtent)FirstToken.Extent).StartOffset) { FirstToken = null; } - if (TokenList != null && TokenList.Count > 0) + if (TokenList is not null && TokenList.Count > 0) { // If we were saving tokens, remove all tokens from token to the end of the saved tokens. RemoveTokensFromListDuringResync(TokenList, start); } - if (RequiresTokens != null && RequiresTokens.Count > 0) + if (RequiresTokens is not null && RequiresTokens.Count > 0) { RemoveTokensFromListDuringResync(RequiresTokens, start); } @@ -1172,7 +1172,7 @@ internal InternalScriptExtent CurrentExtent() { int start = _tokenStart + _nestedTokensAdjustment; int end = _currentIndex + _nestedTokensAdjustment; - if (_skippedCharOffsets != null) + if (_skippedCharOffsets is not null) { int i = _nestedTokensAdjustment; for (; i < start && i < _skippedCharOffsets.Length; ++i) @@ -1208,7 +1208,7 @@ private Token NewCommentToken() private T SaveToken(T token) where T : Token { - if (TokenList != null) + if (TokenList is not null) { TokenList.Add(token); } @@ -1263,7 +1263,7 @@ private StringToken NewStringLiteralToken(string value, TokenKind tokenKind, Tok private StringToken NewStringExpandableToken(string value, string formatString, TokenKind tokenKind, List nestedTokens, TokenFlags flags) { - if (nestedTokens != null && nestedTokens.Count == 0) + if (nestedTokens is not null && nestedTokens.Count == 0) { nestedTokens = null; } @@ -1916,7 +1916,7 @@ internal ScriptRequirements GetScriptRequirements() string snapinName = null; Version snapinVersion = null; - if (commandAst != null) + if (commandAst is not null) { var commandName = commandAst.GetCommandName(); if (!string.Equals(commandName, "requires", StringComparison.OrdinalIgnoreCase)) @@ -1931,7 +1931,7 @@ internal ScriptRequirements GetScriptRequirements() { var parameter = commandAst.CommandElements[i] as CommandParameterAst; - if (parameter != null && + if (parameter is not null && PSSnapinToken.StartsWith(parameter.ParameterName, StringComparison.OrdinalIgnoreCase)) { snapinSpecified = true; @@ -1947,7 +1947,7 @@ internal ScriptRequirements GetScriptRequirements() for (int i = 1; i < commandAst.CommandElements.Count; i++) { var parameter = commandAst.CommandElements[i] as CommandParameterAst; - if (parameter != null) + if (parameter is not null) { HandleRequiresParameter(parameter, commandAst.CommandElements, snapinSpecified, ref i, ref snapinName, ref snapinVersion, @@ -1961,7 +1961,7 @@ internal ScriptRequirements GetScriptRequirements() } } - if (snapinName != null) + if (snapinName is not null) { Diagnostics.Assert(PSSnapInInfo.IsPSSnapinIdValid(snapinName), "we shouldn't set snapinName if it wasn't valid"); requiredSnapins.Add(new PSSnapInSpecification(snapinName) { Version = snapinVersion }); @@ -1973,16 +1973,16 @@ internal ScriptRequirements GetScriptRequirements() { RequiredApplicationId = requiredShellId, RequiredPSVersion = requiredVersion, - RequiredPSEditions = requiredEditions != null + RequiredPSEditions = requiredEditions is not null ? new ReadOnlyCollection(requiredEditions) : ScriptRequirements.EmptyEditionCollection, - RequiresPSSnapIns = requiredSnapins != null + RequiresPSSnapIns = requiredSnapins is not null ? new ReadOnlyCollection(requiredSnapins) : ScriptRequirements.EmptySnapinCollection, - RequiredAssemblies = requiredAssemblies != null + RequiredAssemblies = requiredAssemblies is not null ? new ReadOnlyCollection(requiredAssemblies) : ScriptRequirements.EmptyAssemblyCollection, - RequiredModules = requiredModules != null + RequiredModules = requiredModules is not null ? new ReadOnlyCollection(requiredModules) : ScriptRequirements.EmptyModuleCollection, IsElevationRequired = requiresElevation @@ -2015,7 +2015,7 @@ private void HandleRequiresParameter(CommandParameterAst parameter, if (elevationToken.StartsWith(parameter.ParameterName, StringComparison.OrdinalIgnoreCase)) { requiresElevation = true; - if (argumentAst != null) + if (argumentAst is not null) { ReportError(parameter.Extent, nameof(ParserStrings.ParameterCannotHaveArgument), @@ -2046,7 +2046,7 @@ private void HandleRequiresParameter(CommandParameterAst parameter, if (shellIDToken.StartsWith(parameter.ParameterName, StringComparison.OrdinalIgnoreCase)) { - if (requiredShellId != null) + if (requiredShellId is not null) { ReportError(parameter.Extent, nameof(ParameterBinderStrings.ParameterAlreadyBound), @@ -2078,7 +2078,7 @@ private void HandleRequiresParameter(CommandParameterAst parameter, return; } - if (snapinName != null) + if (snapinName is not null) { ReportError(parameter.Extent, nameof(ParameterBinderStrings.ParameterAlreadyBound), @@ -2100,7 +2100,7 @@ private void HandleRequiresParameter(CommandParameterAst parameter, } else if (editionToken.StartsWith(parameter.ParameterName, StringComparison.OrdinalIgnoreCase)) { - if (requiredEditions != null) + if (requiredEditions is not null) { ReportError(parameter.Extent, nameof(ParameterBinderStrings.ParameterAlreadyBound), @@ -2136,7 +2136,7 @@ private void HandleRequiresParameter(CommandParameterAst parameter, if (snapinSpecified) { - if (snapinVersion != null) + if (snapinVersion is not null) { ReportError(parameter.Extent, nameof(ParameterBinderStrings.ParameterAlreadyBound), @@ -2150,7 +2150,7 @@ private void HandleRequiresParameter(CommandParameterAst parameter, } else { - if (requiredVersion != null && !requiredVersion.Equals(version)) + if (requiredVersion is not null && !requiredVersion.Equals(version)) { ReportError(parameter.Extent, nameof(ParameterBinderStrings.ParameterAlreadyBound), @@ -2554,7 +2554,7 @@ private bool ScanDollarInStringExpandable(StringBuilder sb, StringBuilder format Mode = oldTokenizerMode; } - if (nestedToken != null) + if (nestedToken is not null) { sb.Append(_script, dollarIndex, _currentIndex - dollarIndex); formatSb.Append('{'); @@ -4457,7 +4457,7 @@ private Token ScanIdentifier(char firstChar) } } - if (sb != null) + if (sb is not null) Release(sb); return NewToken(TokenKind.Identifier); } diff --git a/src/System.Management.Automation/engine/pipeline.cs b/src/System.Management.Automation/engine/pipeline.cs index f82c012bafe..e85ad0154cc 100644 --- a/src/System.Management.Automation/engine/pipeline.cs +++ b/src/System.Management.Automation/engine/pipeline.cs @@ -179,7 +179,7 @@ private string GetCommand(InvocationInfo invocationInfo) if (invocationInfo is null) return string.Empty; - if (invocationInfo.MyCommand != null) + if (invocationInfo.MyCommand is not null) { return invocationInfo.MyCommand.Name; } @@ -190,7 +190,7 @@ private string GetCommand(InvocationInfo invocationInfo) private string GetCommand(Exception exception) { IContainsErrorRecord icer = exception as IContainsErrorRecord; - if (icer != null && icer.ErrorRecord != null) + if (icer is not null && icer.ErrorRecord is not null) return GetCommand(icer.ErrorRecord.InvocationInfo); return string.Empty; @@ -199,13 +199,13 @@ private string GetCommand(Exception exception) private void Log(string logElement, InvocationInfo invocation, PipelineExecutionStatus pipelineExecutionStatus) { System.Management.Automation.Host.PSHostUserInterface hostInterface = null; - if (this.LocalPipeline != null) + if (this.LocalPipeline is not null) { hostInterface = this.LocalPipeline.Runspace.GetExecutionContext.EngineHostInterface.UI; } // Acknowledge command completion - if (hostInterface != null) + if (hostInterface is not null) { if (pipelineExecutionStatus == PipelineExecutionStatus.Complete) { @@ -222,7 +222,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 (hostInterface != null) + if (hostInterface is not null) { hostInterface.TranscribeCommand(logElement, invocation); } @@ -258,7 +258,7 @@ private bool NeedToLog() { MshCommandRuntime cmdRuntime = commandProcessor.Command.commandRuntime as MshCommandRuntime; - if (cmdRuntime != null && cmdRuntime.LogPipelineExecutionDetail) + if (cmdRuntime is not null && cmdRuntime.LogPipelineExecutionDetail) return true; } @@ -381,7 +381,7 @@ internal int AddCommand(CommandProcessorBase commandProcessor, int readFromComma throw PSTraceSource.NewInvalidOperationException(); } - if (UpstreamPipe.DownstreamCmdlet != null) + if (UpstreamPipe.DownstreamCmdlet is not null) { throw PSTraceSource.NewInvalidOperationException( PipelineStrings.PipeAlreadyTaken); @@ -406,9 +406,9 @@ internal int AddCommand(CommandProcessorBase commandProcessor, int readFromComma throw PSTraceSource.NewInvalidOperationException(); } // check whether the error output is already claimed - if (prevcommandProcessor.CommandRuntime.ErrorOutputPipe.DownstreamCmdlet != null) + if (prevcommandProcessor.CommandRuntime.ErrorOutputPipe.DownstreamCmdlet is not null) continue; - if (prevcommandProcessor.CommandRuntime.ErrorOutputPipe.ExternalWriter != null) + if (prevcommandProcessor.CommandRuntime.ErrorOutputPipe.ExternalWriter is not null) continue; // Set the upstream cmdlet's error output to go down @@ -502,7 +502,7 @@ internal Array SynchronousExecuteEnumerate(object input) CommandProcessorBase firstCommandProcessor = _commands[0]; // Add any input to the first command. - if (ExternalInput != null) + if (ExternalInput is not null) { firstCommandProcessor.CommandRuntime.InputPipe.ExternalReader = ExternalInput; @@ -513,7 +513,7 @@ internal Array SynchronousExecuteEnumerate(object input) catch (PipelineStoppedException) { StopUpstreamCommandsException stopUpstreamCommandsException = - _firstTerminatingError != null + _firstTerminatingError is not null ? _firstTerminatingError.SourceException as StopUpstreamCommandsException : null; if (stopUpstreamCommandsException is null) @@ -532,7 +532,7 @@ internal Array SynchronousExecuteEnumerate(object input) // By this point, we are sure all commandProcessors hosted by the current pipelineProcess are done execution, // so if there are any redirection pipelineProcessors associated with any of those commandProcessors, we should // call DoComplete on them. - if (_redirectionPipes != null) + if (_redirectionPipes is not null) { foreach (PipelineProcessor redirectPipelineProcessor in _redirectionPipes) { @@ -556,7 +556,7 @@ internal Array SynchronousExecuteEnumerate(object input) // The error we want to report is the first terminating error // which occurred during pipeline execution, regardless // of whether other errors occurred afterward. - if (_firstTerminatingError != null) + if (_firstTerminatingError is not null) { toRethrowInfo = _firstTerminatingError; } @@ -581,7 +581,7 @@ internal Array SynchronousExecuteEnumerate(object input) // The only reason we should get here is if // an exception should be rethrown. - Diagnostics.Assert(toRethrowInfo != null, "Alternate protocol path failure"); + Diagnostics.Assert(toRethrowInfo is not null, "Alternate protocol path failure"); toRethrowInfo.Throw(); return null; // UNREACHABLE } @@ -591,7 +591,7 @@ private void DoCompleteCore(CommandProcessorBase commandRequestingUpstreamComman // Call DoComplete() for all the commands. DoComplete() will internally call Complete() MshCommandRuntime lastCommandRuntime = null; - if (_commands != null) + if (_commands is not null) { for (int i = 0; i < _commands.Count; i++) { @@ -609,7 +609,7 @@ private void DoCompleteCore(CommandProcessorBase commandRequestingUpstreamComman continue; // do not call DoComplete/EndProcessing on the command that initiated stopping } - if (commandRequestingUpstreamCommandsToStop != null) + if (commandRequestingUpstreamCommandsToStop is not null) { continue; // do not call DoComplete/EndProcessing on commands that were stopped upstream } @@ -621,7 +621,7 @@ private void DoCompleteCore(CommandProcessorBase commandRequestingUpstreamComman catch (PipelineStoppedException) { StopUpstreamCommandsException stopUpstreamCommandsException = - _firstTerminatingError != null + _firstTerminatingError is not null ? _firstTerminatingError.SourceException as StopUpstreamCommandsException : null; if (stopUpstreamCommandsException is null) @@ -656,7 +656,7 @@ private void DoCompleteCore(CommandProcessorBase commandRequestingUpstreamComman } // Log the pipeline completion. - if (lastCommandRuntime != null) + if (lastCommandRuntime is not null) { // Only log the pipeline completion if this wasn't a nested pipeline, as // pipeline state in transcription is associated with the toplevel pipeline @@ -667,7 +667,7 @@ private void DoCompleteCore(CommandProcessorBase commandRequestingUpstreamComman } // If a terminating error occurred, report it now. - if (_firstTerminatingError != null) + if (_firstTerminatingError is not null) { this.LogExecutionException(_firstTerminatingError.SourceException); _firstTerminatingError.Throw(); @@ -713,7 +713,7 @@ internal Array DoComplete() // The error we want to report is the first terminating error // which occurred during pipeline execution, regardless // of whether other errors occurred afterward. - if (_firstTerminatingError != null) + if (_firstTerminatingError is not null) { toRethrowInfo = _firstTerminatingError; } @@ -738,7 +738,7 @@ internal Array DoComplete() // The only reason we should get here is if // an exception should be rethrown. - Diagnostics.Assert(toRethrowInfo != null, "Alternate protocol path failure"); + Diagnostics.Assert(toRethrowInfo is not null, "Alternate protocol path failure"); toRethrowInfo.Throw(); return null; // UNREACHABLE } @@ -758,7 +758,7 @@ internal void StartStepping(bool expectInput) Start(expectInput); // If a terminating error occurred, report it now. - if (_firstTerminatingError != null) + if (_firstTerminatingError is not null) { _firstTerminatingError.Throw(); } @@ -770,7 +770,7 @@ internal void StartStepping(bool expectInput) // The error we want to report is the first terminating error // which occurred during pipeline execution, regardless // of whether other errors occurred afterward. - if (_firstTerminatingError != null) + if (_firstTerminatingError is not null) { _firstTerminatingError.Throw(); } @@ -871,7 +871,7 @@ internal Array Step(object input) Inject(input, enumerate: false); // If a terminating error occurred, report it now. - if (_firstTerminatingError != null) + if (_firstTerminatingError is not null) { _firstTerminatingError.Throw(); } @@ -885,7 +885,7 @@ internal Array Step(object input) // The error we want to report is the first terminating error // which occurred during pipeline execution, regardless // of whether other errors occurred afterward. - if (_firstTerminatingError != null) + if (_firstTerminatingError is not null) { _firstTerminatingError.Throw(); } @@ -974,7 +974,7 @@ private void Start(bool incomingStream) throw PSTraceSource.NewInvalidOperationException(); } - if (ExternalSuccessOutput != null) + if (ExternalSuccessOutput is not null) { LastCommandProcessor.CommandRuntime.OutputPipe.ExternalWriter = ExternalSuccessOutput; @@ -1078,7 +1078,7 @@ private void Start(bool incomingStream) /// private void SetExternalErrorOutput() { - if (ExternalErrorOutput != null) + if (ExternalErrorOutput is not null) { for (int i = 0; i < _commands.Count; i++) { @@ -1160,7 +1160,7 @@ private void Inject(object input, bool enumerate) { IEnumerator enumerator = LanguagePrimitives.GetEnumerator(input); - if (enumerator != null) + if (enumerator is not null) { firstcommandProcessor.CommandRuntime.InputPipe = new Pipe(enumerator); } @@ -1249,7 +1249,7 @@ private Array RetrieveResults() /// The pipeline to write success objects to. internal void LinkPipelineSuccessOutput(Pipe pipeToUse) { - Dbg.Assert(pipeToUse != null, "Caller should verify pipeToUse != null"); + Dbg.Assert(pipeToUse is not null, "Caller should verify pipeToUse is not null"); CommandProcessorBase LastCommandProcessor = _commands[_commands.Count - 1]; if (LastCommandProcessor is null @@ -1265,7 +1265,7 @@ internal void LinkPipelineSuccessOutput(Pipe pipeToUse) internal void LinkPipelineErrorOutput(Pipe pipeToUse) { - Dbg.Assert(pipeToUse != null, "Caller should verify pipeToUse != null"); + Dbg.Assert(pipeToUse is not null, "Caller should verify pipeToUse is not null"); for (int i = 0; i < _commands.Count; i++) { @@ -1302,12 +1302,12 @@ private void DisposeCommands() LogToEventLog(); - if (_commands != null) + if (_commands is not null) { for (int i = 0; i < _commands.Count; i++) { CommandProcessorBase commandProcessor = _commands[i]; - if (commandProcessor != null) + if (commandProcessor is not null) { #pragma warning disable 56500 // If Dispose throws an exception, record it as a @@ -1324,12 +1324,12 @@ private void DisposeCommands() catch (Exception e) // Catch-all OK, 3rd party callout. { InvocationInfo myInvocation = null; - if (commandProcessor.Command != null) + if (commandProcessor.Command is not null) myInvocation = commandProcessor.Command.MyInvocation; ProviderInvocationException pie = e as ProviderInvocationException; - if (pie != null) + if (pie is not null) { e = new CmdletProviderInvocationException( pie, @@ -1359,7 +1359,7 @@ private void DisposeCommands() _commands = null; // Now dispose any pipes that were used for redirection... - if (_redirectionPipes != null) + if (_redirectionPipes is not null) { foreach (PipelineProcessor redirPipe in _redirectionPipes) { @@ -1369,7 +1369,7 @@ private void DisposeCommands() // exceptions... try { - if (redirPipe != null) + if (redirPipe is not null) { redirPipe.Dispose(); } @@ -1407,11 +1407,11 @@ internal bool RecordFailure(Exception e, InternalCommand command) // before hitting the error, therefore we check whether // firstTerminatingError is PipelineStoppedException. else if ((!(_firstTerminatingError.SourceException is PipelineStoppedException)) - && command != null && command.Context != null) + && command is not null && command.Context is not null) { Exception ex = e; while ((ex is TargetInvocationException || ex is CmdletInvocationException) - && (ex.InnerException != null)) + && (ex.InnerException is not null)) { ex = ex.InnerException; } @@ -1556,7 +1556,7 @@ internal bool ExecutionStarted /// internal bool Stopping { - get { return _localPipeline != null && _localPipeline.IsStopping; } + get { return _localPipeline is not null && _localPipeline.IsStopping; } } private LocalPipeline _localPipeline; diff --git a/src/System.Management.Automation/engine/regex.cs b/src/System.Management.Automation/engine/regex.cs index 5700cf7e464..43bd4464f01 100644 --- a/src/System.Management.Automation/engine/regex.cs +++ b/src/System.Management.Automation/engine/regex.cs @@ -162,7 +162,7 @@ StringComparison GetStringComparison() return stringComparison; } - if (_isMatch != null) + if (_isMatch is not null) { return; } @@ -202,7 +202,7 @@ StringComparison GetStringComparison() public bool IsMatch(string input) { Init(); - return input != null && _isMatch(input); + return input is not null && _isMatch(input); } /// @@ -1154,7 +1154,7 @@ private class BracketExpressionElement : QuestionMarkElement public BracketExpressionElement(Regex regex) { - Dbg.Assert(regex != null, "Caller should verify regex != null"); + Dbg.Assert(regex is not null, "Caller should verify regex is not null"); _regex = regex; } diff --git a/src/System.Management.Automation/engine/remoting/client/ClientMethodExecutor.cs b/src/System.Management.Automation/engine/remoting/client/ClientMethodExecutor.cs index 700c5d59ace..e0fb80304e5 100644 --- a/src/System.Management.Automation/engine/remoting/client/ClientMethodExecutor.cs +++ b/src/System.Management.Automation/engine/remoting/client/ClientMethodExecutor.cs @@ -56,8 +56,8 @@ internal RemoteHostCall RemoteHostCall /// private ClientMethodExecutor(BaseClientTransportManager transportManager, PSHost clientHost, Guid clientRunspacePoolId, Guid clientPowerShellId, RemoteHostCall remoteHostCall) { - Dbg.Assert(transportManager != null, "Expected transportManager != null"); - Dbg.Assert(remoteHostCall != null, "Expected remoteHostCall != null"); + Dbg.Assert(transportManager is not null, "Expected transportManager is not null"); + Dbg.Assert(remoteHostCall is not null, "Expected remoteHostCall is not null"); _transportManager = transportManager; _remoteHostCall = remoteHostCall; _clientHost = clientHost; @@ -92,13 +92,13 @@ internal static void Dispatch( // Check client host to see if SetShouldExit should be allowed bool hostAllowSetShouldExit = false; - if (clientHost != null) + if (clientHost is not null) { PSObject hostPrivateData = clientHost.PrivateData as PSObject; - if (hostPrivateData != null) + if (hostPrivateData is not null) { PSNoteProperty allowSetShouldExit = hostPrivateData.Properties["AllowSetShouldExitFromRemote"] as PSNoteProperty; - hostAllowSetShouldExit = (allowSetShouldExit != null && allowSetShouldExit.Value is bool) ? + hostAllowSetShouldExit = (allowSetShouldExit is not null && allowSetShouldExit.Value is bool) ? (bool)allowSetShouldExit.Value : false; } } @@ -118,7 +118,7 @@ internal static void Dispatch( // Cmdlet case: queue up the executor in the pipeline stream. if (isMethodExecutorStreamEnabled) { - Dbg.Assert(methodExecutorStream != null, "method executor stream can't be null when enabled"); + Dbg.Assert(methodExecutorStream is not null, "method executor stream can't be null when enabled"); methodExecutorStream.Write(methodExecutor); } @@ -161,7 +161,7 @@ internal void Execute(PSDataCollectionStream errorStream) { try { - if (_clientHost.UI != null) + if (_clientHost.UI is not null) { _clientHost.UI.WriteErrorLine(errorRecord.ToString()); } @@ -230,7 +230,7 @@ internal void ExecuteVoid(Action writeErrorAction) // Catch-all OK, 3rd party callout. // Extract inner exception. - if (exception.InnerException != null) + if (exception.InnerException is not null) { exception = exception.InnerException; } diff --git a/src/System.Management.Automation/engine/remoting/client/ClientRemotePowerShell.cs b/src/System.Management.Automation/engine/remoting/client/ClientRemotePowerShell.cs index 6e6c56002a9..de41574adf1 100644 --- a/src/System.Management.Automation/engine/remoting/client/ClientRemotePowerShell.cs +++ b/src/System.Management.Automation/engine/remoting/client/ClientRemotePowerShell.cs @@ -105,7 +105,7 @@ internal ObjectStreamBase InputStream { inputstream = value; - if (inputstream != null && (inputstream.IsOpen || inputstream.Count > 0)) + if (inputstream is not null && (inputstream.IsOpen || inputstream.Count > 0)) { noInput = false; } @@ -166,7 +166,7 @@ internal void UnblockCollections() outputstream.Close(); errorstream.Close(); - if (inputstream != null) + if (inputstream is not null) { inputstream.Close(); } @@ -323,7 +323,7 @@ internal void ConnectAsync(ConnectCommandInfo connectCmdInfo) else { // First add this command DS handler to the remote runspace pool list. - Dbg.Assert(this.shell.RunspacePool != null, "Invalid runspace pool for this powershell object."); + Dbg.Assert(this.shell.RunspacePool is not null, "Invalid runspace pool for this powershell object."); this.shell.RunspacePool.RemoteRunspacePoolInternal.AddRemotePowerShellDSHandler( this.InstanceId, this.dataStructureHandler); @@ -424,7 +424,7 @@ private void HandleInvocationStateInfoReceived(object sender, if (stateInfo.State == PSInvocationState.Failed) { PSRemotingTransportException remotingTransportException = stateInfo.Reason as PSRemotingTransportException; - terminateSession = (remotingTransportException != null) && + terminateSession = (remotingTransportException is not null) && (remotingTransportException.ErrorCode == System.Management.Automation.Remoting.Client.WSManNativeApi.ERROR_WSMAN_TARGETSESSION_DOESNOTEXIST); } @@ -468,7 +468,7 @@ private void HandleInvocationStateInfoReceived(object sender, private void CheckAndCloseRunspaceAfterStop(Exception ex) { PSRemotingTransportException transportException = ex as PSRemotingTransportException; - if (transportException != null && + if (transportException is not null && (transportException.ErrorCode == System.Management.Automation.Remoting.Client.WSManNativeApi.ERROR_WSMAN_SENDDATA_CANNOT_CONNECT || transportException.ErrorCode == System.Management.Automation.Remoting.Client.WSManNativeApi.ERROR_WSMAN_SENDDATA_CANNOT_COMPLETE || transportException.ErrorCode == System.Management.Automation.Remoting.Client.WSManNativeApi.ERROR_WSMAN_TARGETSESSION_DOESNOTEXIST)) @@ -569,7 +569,7 @@ private void HandleHostCallReceived(object sender, RemoteDataEventArgs prerequisiteCalls = eventArgs.Data.PerformSecurityChecksOnHostMessage(computerName); - if (HostCallReceived != null) + if (HostCallReceived is not null) { // raise events for all prerequisite calls if (prerequisiteCalls.Count > 0) @@ -645,7 +645,7 @@ private void HandleCloseCompleted(object sender, EventArgs args) // If RemoteSessionStateEventArgs are provided then use them to set the // session close reason when setting finished state. RemoteSessionStateEventArgs sessionEventArgs = args as RemoteSessionStateEventArgs; - Exception closeReason = (sessionEventArgs != null) ? sessionEventArgs.SessionStateInfo.Reason : null; + Exception closeReason = (sessionEventArgs is not null) ? sessionEventArgs.SessionStateInfo.Reason : null; PSInvocationState finishedState = (shell.InvocationStateInfo.State == PSInvocationState.Disconnected) ? PSInvocationState.Failed : PSInvocationState.Stopped; @@ -859,7 +859,7 @@ private void HandleRobustConnectionNotification( // Update connection status. _connectionRetryStatus = connectionRetryStatusArgs.Notification; - if (warningRecord != null) + if (warningRecord is not null) { RemotingWarningRecord remotingWarningRecord = new RemotingWarningRecord( warningRecord, @@ -885,7 +885,7 @@ private void HandleRobustConnectionNotification( { } } - if (errorRecord != null) + if (errorRecord is not null) { RemotingErrorRecord remotingErrorRecord = new RemotingErrorRecord( errorRecord, diff --git a/src/System.Management.Automation/engine/remoting/client/Job.cs b/src/System.Management.Automation/engine/remoting/client/Job.cs index fef63d2ed34..1d4f0992626 100644 --- a/src/System.Management.Automation/engine/remoting/client/Job.cs +++ b/src/System.Management.Automation/engine/remoting/client/Job.cs @@ -506,7 +506,7 @@ internal static string GetCommandTextFromInvocationInfo(InvocationInfo invocatio } IScriptExtent scriptExtent = invocationInfo.ScriptPosition; - if ((scriptExtent != null) && (scriptExtent.StartScriptPosition != null) && !string.IsNullOrWhiteSpace(scriptExtent.StartScriptPosition.Line)) + if ((scriptExtent is not null) && (scriptExtent.StartScriptPosition is not null) && !string.IsNullOrWhiteSpace(scriptExtent.StartScriptPosition.Line)) { Dbg.Assert(scriptExtent.StartScriptPosition.ColumnNumber > 0, "Column numbers start at 1"); Dbg.Assert(scriptExtent.StartScriptPosition.ColumnNumber <= scriptExtent.StartScriptPosition.Line.Length, "Column numbers are not greater than the length of a line"); @@ -575,7 +575,7 @@ public WaitHandle Finished { lock (this.syncObject) { - if (_finished != null) + if (_finished is not null) { return _finished; } @@ -740,7 +740,7 @@ private void WriteError(Cmdlet cmdlet, ErrorRecord errorRecord) if (this.PropagateThrows) { Exception e = GetExceptionFromErrorRecord(errorRecord); - if (e != null) + if (e is not null) throw e; } @@ -773,7 +773,7 @@ internal virtual void WriteError(ErrorRecord errorRecord) if (PropagateThrows) { Exception exception = GetExceptionFromErrorRecord(errorRecord); - if (exception != null) + if (exception is not null) { Results.Add(new PSStreamObject(PSStreamObjectType.Exception, exception)); return; @@ -815,7 +815,7 @@ internal virtual void WriteDebug(string message) internal virtual void WriteProgress(ProgressRecord progressRecord) { - if ((progressRecord.ParentActivityId == (-1)) && (_parentActivityId != null)) + if ((progressRecord.ParentActivityId == (-1)) && (_parentActivityId is not null)) { progressRecord = new ProgressRecord(progressRecord) { ParentActivityId = _parentActivityId.Value }; } @@ -834,7 +834,7 @@ internal virtual void WriteInformation(InformationRecord informationRecord) internal void SetParentActivityIdGetter(Func parentActivityIdGetter) { - Dbg.Assert(parentActivityIdGetter != null, "Caller should verify parentActivityIdGetter != null"); + Dbg.Assert(parentActivityIdGetter is not null, "Caller should verify parentActivityIdGetter is not null"); _parentActivityId = new Lazy(parentActivityIdGetter); } @@ -904,7 +904,7 @@ private void InvokeCmdletMethodAndIgnoreResults(Action invokeCmdletMetho private T InvokeCmdletMethodAndWaitForResults(Func invokeCmdletMethodAndReturnResult, out Exception exceptionThrownOnCmdletThread) { - Dbg.Assert(invokeCmdletMethodAndReturnResult != null, "Caller should verify invokeCmdletMethodAndReturnResult != null"); + Dbg.Assert(invokeCmdletMethodAndReturnResult is not null, "Caller should verify invokeCmdletMethodAndReturnResult is not null"); T methodResult = default(T); Exception closureSafeExceptionThrownOnCmdletThread = null; @@ -1448,7 +1448,7 @@ internal void SetJobState(JobState state, Exception reason) { lock (syncObject) { - if (_finished != null) + if (_finished is not null) { _finished.Set(); } @@ -1649,7 +1649,7 @@ protected virtual void Dispose(bool disposing) // release the WaitHandle lock (syncObject) { - if (_finished != null) + if (_finished is not null) { _finished.Dispose(); _finished = null; @@ -1692,7 +1692,7 @@ internal bool MonitorOutputProcessing internal void SetMonitorOutputProcessing(IOutputProcessingState outputProcessingState) { - if (outputProcessingState != null) + if (outputProcessingState is not null) { outputProcessingState.OutputProcessingStateChanged += HandleOutputProcessingStateChanged; } @@ -1700,7 +1700,7 @@ internal void SetMonitorOutputProcessing(IOutputProcessingState outputProcessing internal void RemoveMonitorOutputProcessing(IOutputProcessingState outputProcessingState) { - if (outputProcessingState != null) + if (outputProcessingState is not null) { outputProcessingState.OutputProcessingStateChanged -= HandleOutputProcessingStateChanged; } @@ -2006,7 +2006,7 @@ internal void ConnectJob(Guid runspaceInstanceId) { List connectJobOperations = new List(); PSRemotingChildJob childJob = FindDisconnectedChildJob(runspaceInstanceId); - if (childJob != null) + if (childJob is not null) { connectJobOperations.Add(new ConnectJobOperation(childJob)); } @@ -2134,7 +2134,7 @@ internal PowerShell GetAssociatedPowerShellObject(Guid runspaceInstanceId) { PowerShell ps = null; PSRemotingChildJob childJob = FindDisconnectedChildJob(runspaceInstanceId); - if (childJob != null) + if (childJob is not null) { ps = childJob.GetPowerShell(); } @@ -2302,7 +2302,7 @@ internal bool HideComputerName foreach (Job job in this.ChildJobs) { PSRemotingChildJob rJob = job as PSRemotingChildJob; - if (rJob != null) + if (rJob is not null) { rJob.HideComputerName = value; } @@ -2775,7 +2775,7 @@ internal PSRemotingChildJob(string remoteCommand, ExecutionCmdletHelper helper, _throttleManager = throttleManager; RemoteRunspace remoteRS = Runspace as RemoteRunspace; - if ((remoteRS != null) && (remoteRS.RunspaceStateInfo.State == RunspaceState.BeforeOpen)) + if ((remoteRS is not null) && (remoteRS.RunspaceStateInfo.State == RunspaceState.BeforeOpen)) { remoteRS.URIRedirectionReported += HandleURIDirectionReported; } @@ -2922,7 +2922,7 @@ public override string Location { get { - return (Runspace != null) ? Runspace.ConnectionInfo.ComputerName : string.Empty; + return (Runspace is not null) ? Runspace.ConnectionInfo.ComputerName : string.Empty; } } @@ -2951,7 +2951,7 @@ internal bool HideComputerName foreach (Job job in this.ChildJobs) { PSRemotingChildJob rJob = job as PSRemotingChildJob; - if (rJob != null) + if (rJob is not null) { rJob.HideComputerName = value; } @@ -2977,7 +2977,7 @@ internal override bool CanDisconnect get { RemoteRunspace remoteRS = Runspace as RemoteRunspace; - return (remoteRS != null) ? remoteRS.CanDisconnect : false; + return (remoteRS is not null) ? remoteRS.CanDisconnect : false; } } @@ -2997,7 +2997,7 @@ public Debugger Debugger lock (this.SyncObject) { if ((_jobDebugger is null) && - (Runspace.Debugger != null)) + (Runspace.Debugger is not null)) { _jobDebugger = new RemotingJobDebugger(Runspace.Debugger, Runspace, this.Name); } @@ -3042,18 +3042,18 @@ private void HandleOutputReady(object sender, EventArgs eventArgs) // attach origin information only if it doesn't exist // in case of a second-hop scenario, the origin information // will already be added at the second hop machine - if (dataObject != null) + if (dataObject is not null) { // if the server has already added some properties, which we do not // want to trust, we simply replace them with the server's // identity we know of - if (dataObject.Properties[RemotingConstants.ComputerNameNoteProperty] != null) + if (dataObject.Properties[RemotingConstants.ComputerNameNoteProperty] is not null) { dataObject.Properties.Remove(RemotingConstants.ComputerNameNoteProperty); } - if (dataObject.Properties[RemotingConstants.RunspaceIdNoteProperty] != null) + if (dataObject.Properties[RemotingConstants.RunspaceIdNoteProperty] is not null) { dataObject.Properties.Remove(RemotingConstants.RunspaceIdNoteProperty); } @@ -3091,7 +3091,7 @@ private void HandleErrorReady(object sender, EventArgs eventArgs) foreach (object errorData in error) { ErrorRecord er = errorData as ErrorRecord; - if (er != null) + if (er is not null) { OriginInfo originInfo = new OriginInfo(reader.ComputerName, reader.RunspaceId); @@ -3127,7 +3127,7 @@ private void HandleHostCalls(object sender, EventArgs eventArgs) { ObjectStream hostCallsStream = sender as ObjectStream; - if (hostCallsStream != null) + if (hostCallsStream is not null) { Collection hostCallMethodExecutors = hostCallsStream.NonBlockingRead(hostCallsStream.Count); @@ -3156,7 +3156,7 @@ private void HandleHostCalls(object sender, EventArgs eventArgs) /// protected virtual void HandlePipelineStateChanged(object sender, PipelineStateEventArgs e) { - if ((Runspace != null) && (e.PipelineStateInfo.State != PipelineState.Running)) + if ((Runspace is not null) && (e.PipelineStateInfo.State != PipelineState.Running)) { // since we got state changed event..we dont need to listen on // URI redirections anymore @@ -3228,7 +3228,7 @@ protected virtual void HandleOperationComplete(object sender, OperationStateEven // operations are completed and this means that status of job is not updated // untill Operation Complete. ExecutionCmdletHelper helper = sender as ExecutionCmdletHelper; - Dbg.Assert(helper != null, "Sender of OperationComplete has to be ExecutionCmdletHelper"); + Dbg.Assert(helper is not null, "Sender of OperationComplete has to be ExecutionCmdletHelper"); DeterminedAndSetJobState(helper); } @@ -3293,18 +3293,18 @@ protected void ProcessJobFailure(ExecutionCmdletHelper helper, out Exception fai // 3. Runspace.OpenAsync or Pipeline.InvokeAsync threw exception // They are in Helper.InternalException - Dbg.Assert(helper != null, "helper is null"); + Dbg.Assert(helper is not null, "helper is null"); RemotePipeline pipeline = helper.Pipeline as RemotePipeline; - Dbg.Assert(pipeline != null, "pipeline is null"); + Dbg.Assert(pipeline is not null, "pipeline is null"); RemoteRunspace runspace = pipeline.GetRunspace() as RemoteRunspace; - Dbg.Assert(runspace != null, "runspace is null"); + Dbg.Assert(runspace is not null, "runspace is null"); failureException = null; failureErrorRecord = null; - if (helper.InternalException != null) + if (helper.InternalException is not null) { string errorId = "RemotePipelineExecutionFailed"; failureException = helper.InternalException; @@ -3324,7 +3324,7 @@ protected void ProcessJobFailure(ExecutionCmdletHelper helper, out Exception fai } // there is a failure reason available in the runspace else if ((runspace.RunspaceStateInfo.State == RunspaceState.Broken) || - (runspace.RunspaceStateInfo.Reason != null)) + (runspace.RunspaceStateInfo.Reason is not null)) { failureException = runspace.RunspaceStateInfo.Reason; object targetObject = runspace.ConnectionInfo.ComputerName; @@ -3339,10 +3339,10 @@ protected void ProcessJobFailure(ExecutionCmdletHelper helper, out Exception fai string fullyQualifiedErrorId = System.Management.Automation.Remoting.Client.WSManTransportManagerUtils.GetFQEIDFromTransportError( - (transException != null) ? transException.ErrorCode : 0, + (transException is not null) ? transException.ErrorCode : 0, "PSSessionStateBroken"); - if (transException != null) + if (transException is not null) { errorDetails = "[" + runspace.ConnectionInfo.ComputerName + "] "; @@ -3385,22 +3385,22 @@ protected void ProcessJobFailure(ExecutionCmdletHelper helper, out Exception fai } else if ((pipeline.PipelineStateInfo.State == PipelineState.Failed) || ((pipeline.PipelineStateInfo.State == PipelineState.Stopped) && - (pipeline.PipelineStateInfo.Reason != null && !(pipeline.PipelineStateInfo.Reason is PipelineStoppedException)))) + (pipeline.PipelineStateInfo.Reason is not null && !(pipeline.PipelineStateInfo.Reason is PipelineStoppedException)))) { // Pipeline stopped state is also an error condition if the associated exception is not 'PipelineStoppedException'. object targetObject = runspace.ConnectionInfo.ComputerName; failureException = pipeline.PipelineStateInfo.Reason; - if (failureException != null) + if (failureException is not null) { RemoteException rException = failureException as RemoteException; ErrorRecord errorRecord = null; - if (rException != null) + if (rException is not null) { errorRecord = rException.ErrorRecord; // A RemoteException will hide a PipelineStoppedException, which should be ignored. - if (errorRecord != null && + if (errorRecord is not null && errorRecord.FullyQualifiedErrorId.Equals("PipelineStopped", StringComparison.OrdinalIgnoreCase)) { // PipelineStoppedException should not be reported as error. @@ -3541,7 +3541,7 @@ protected void AggregateResultsFromHelper(ExecutionCmdletHelper helper) /// PowerShell instance. private PowerShell GetPipelinePowerShell(RemotePipeline pipeline, Guid instanceId) { - if (pipeline != null) + if (pipeline is not null) { return pipeline.PowerShell; } @@ -3560,7 +3560,7 @@ private void HandleDebugAdded(object sender, DataAddedEventArgs eventArgs) int index = eventArgs.Index; PowerShell powershell = GetPipelinePowerShell(_remotePipeline, eventArgs.PowerShellInstanceId); - if (powershell != null) + if (powershell is not null) { this.Debug.Add(powershell.Streams.Debug[index]); } @@ -3577,7 +3577,7 @@ private void HandleVerboseAdded(object sender, DataAddedEventArgs eventArgs) int index = eventArgs.Index; PowerShell powershell = GetPipelinePowerShell(_remotePipeline, eventArgs.PowerShellInstanceId); - if (powershell != null) + if (powershell is not null) { this.Verbose.Add(powershell.Streams.Verbose[index]); } @@ -3594,7 +3594,7 @@ private void HandleWarningAdded(object sender, DataAddedEventArgs eventArgs) int index = eventArgs.Index; PowerShell powershell = GetPipelinePowerShell(_remotePipeline, eventArgs.PowerShellInstanceId); - if (powershell != null) + if (powershell is not null) { WarningRecord warningRecord = powershell.Streams.Warning[index]; this.Warning.Add(warningRecord); @@ -3613,7 +3613,7 @@ private void HandleProgressAdded(object sender, DataAddedEventArgs eventArgs) int index = eventArgs.Index; PowerShell powershell = GetPipelinePowerShell(_remotePipeline, eventArgs.PowerShellInstanceId); - if (powershell != null) + if (powershell is not null) { this.Progress.Add(powershell.Streams.Progress[index]); } @@ -3630,7 +3630,7 @@ private void HandleInformationAdded(object sender, DataAddedEventArgs eventArgs) int index = eventArgs.Index; PowerShell powershell = GetPipelinePowerShell(_remotePipeline, eventArgs.PowerShellInstanceId); - if (powershell != null) + if (powershell is not null) { InformationRecord informationRecord = powershell.Streams.Information[index]; this.Information.Add(informationRecord); @@ -3682,7 +3682,7 @@ protected void RemoveAggreateCallbacksFromHelper(ExecutionCmdletHelper helper) Dbg.Assert(pipeline is RemotePipeline, "pipeline is RemotePipeline"); RemotePipeline remotePipeline = pipeline as RemotePipeline; remotePipeline.MethodExecutorStream.DataReady -= HandleHostCalls; - if (remotePipeline.PowerShell != null) + if (remotePipeline.PowerShell is not null) { remotePipeline.PowerShell.Streams.Progress.DataAdded -= HandleProgressAdded; remotePipeline.PowerShell.Streams.Warning.DataAdded -= HandleWarningAdded; @@ -3724,7 +3724,7 @@ protected void DeterminedAndSetJobState(ExecutionCmdletHelper helper) // Process the reason in case of failure. ProcessJobFailure(helper, out failureException, out _failureErrorRecord); - if (failureException != null) + if (failureException is not null) { SetJobState(JobState.Failed, failureException); } @@ -3761,7 +3761,7 @@ internal void UnblockJob() SetJobState(JobState.Running, null); - Dbg.Assert(JobUnblocked != null, "Parent job must register for JobUnblocked event from all child jobs"); + Dbg.Assert(JobUnblocked is not null, "Parent job must register for JobUnblocked event from all child jobs"); JobUnblocked.SafeInvoke(this, EventArgs.Empty); } @@ -3783,7 +3783,7 @@ internal virtual PowerShell GetPowerShell(Guid instanceId) internal PowerShell GetPowerShell() { PowerShell ps = null; - if (_remotePipeline != null) + if (_remotePipeline is not null) { ps = _remotePipeline.PowerShell; } @@ -4079,7 +4079,7 @@ public override void SetDebuggerStepMode(bool enabled) internal void CheckStateAndRaiseStopEvent() { RemoteDebugger remoteDebugger = _wrappedDebugger as RemoteDebugger; - if (remoteDebugger != null) + if (remoteDebugger is not null) { remoteDebugger.CheckStateAndRaiseStopEvent(); } @@ -4119,7 +4119,7 @@ private Pipeline DrainAndBlockRemoteOutput() if (!(_runspace is RemoteRunspace)) { return null; } Pipeline runningCmd = _runspace.GetCurrentlyRunningPipeline(); - if (runningCmd != null) + if (runningCmd is not null) { runningCmd.DrainIncomingData(); runningCmd.SuspendIncomingData(); @@ -4132,7 +4132,7 @@ private Pipeline DrainAndBlockRemoteOutput() private void RestoreRemoteOutput(Pipeline runningCmd) { - if (runningCmd != null) + if (runningCmd is not null) { runningCmd.ResumeIncomingData(); } @@ -4202,7 +4202,7 @@ internal PSInvokeExpressionSyncJob(List operations, Throttle ExecutionCmdletHelper helper = operation as ExecutionCmdletHelper; RemoteRunspace remoteRS = helper.Pipeline.Runspace as RemoteRunspace; - if (remoteRS != null) + if (remoteRS is not null) { remoteRS.StateChanged += HandleRunspaceStateChanged; @@ -4251,7 +4251,7 @@ protected override void DoCleanupOnFinished() { // cleanup remote runspace related handlers RemoteRunspace remoteRS = helper.PipelineRunspace as RemoteRunspace; - if (remoteRS != null) + if (remoteRS is not null) { remoteRS.StateChanged -= HandleRunspaceStateChanged; remoteRS.URIRedirectionReported -= HandleURIDirectionReported; @@ -4284,7 +4284,7 @@ protected override void Dispose(bool disposing) protected override void HandleOperationComplete(object sender, OperationStateEventArgs stateEventArgs) { ExecutionCmdletHelper helper = sender as ExecutionCmdletHelper; - Dbg.Assert(helper != null, "Sender of OperationComplete has to be ExecutionCmdletHelper"); + Dbg.Assert(helper is not null, "Sender of OperationComplete has to be ExecutionCmdletHelper"); Exception failureException; // Process the reason in case of failure. @@ -4292,7 +4292,7 @@ protected override void HandleOperationComplete(object sender, OperationStateEve ProcessJobFailure(helper, out failureException, out failureErrorRecord); - if (failureErrorRecord != null) + if (failureErrorRecord is not null) { this.WriteError(failureErrorRecord); } @@ -4429,7 +4429,7 @@ private void HandleRunspaceStateChanged(object sender, RunspaceStateEventArgs e) RemoteRunspace remoteRS = sender as RemoteRunspace; // remote runspace must be connected (or connection failed) // we dont need URI redirection any more..so clear it - if (remoteRS != null) + if (remoteRS is not null) { if (e.RunspaceStateInfo.State != RunspaceState.Opening) { diff --git a/src/System.Management.Automation/engine/remoting/client/Job2.cs b/src/System.Management.Automation/engine/remoting/client/Job2.cs index b9626006897..fa06fcc833e 100644 --- a/src/System.Management.Automation/engine/remoting/client/Job2.cs +++ b/src/System.Management.Automation/engine/remoting/client/Job2.cs @@ -342,7 +342,7 @@ private void RaiseCompletedHandler(int operation, AsyncCompletedEventArgs eventA #pragma warning disable 56500 try { - if (handler != null) + if (handler is not null) { handler(this, eventArgs); } @@ -797,7 +797,7 @@ public override void StartJob() if (ChildJobs.Count == 1) { Job2 child = ChildJobs[0] as Job2; - Dbg.Assert(child != null, "Job is null after initial null check"); + Dbg.Assert(child is not null, "Job is null after initial null check"); #pragma warning disable 56500 try { @@ -827,11 +827,11 @@ public override void StartJob() EventHandler eventHandler = (object sender, AsyncCompletedEventArgs e) => { var childJob = sender as Job2; - Dbg.Assert(childJob != null, + Dbg.Assert(childJob is not null, "StartJobCompleted only available on Job2"); _tracer.WriteMessage(TraceClassName, "StartJob-Handler", Guid.Empty, this, "Finished starting child job asynchronously, child InstanceId: {0}", childJob.InstanceId.ToString()); - if (e.Error != null) + if (e.Error is not null) { ExecutionError.Add( new ErrorRecord(e.Error, @@ -855,7 +855,7 @@ public override void StartJob() foreach (Job2 job in ChildJobs) { - Dbg.Assert(job != null, "Job is null after initial null check"); + Dbg.Assert(job is not null, "Job is null after initial null check"); job.StartJobCompleted += eventHandler; _tracer.WriteMessage(TraceClassName, "StartJob", Guid.Empty, this, @@ -870,7 +870,7 @@ public override void StartJob() completed.WaitOne(); foreach (Job2 job in ChildJobs) { - Dbg.Assert(job != null, "Job is null after initial null check"); + Dbg.Assert(job is not null, "Job is null after initial null check"); job.StartJobCompleted -= eventHandler; } @@ -915,10 +915,10 @@ public override void StartJobAsync() eventHandler = (sender, e) => { var childJob = sender as Job2; - Dbg.Assert(childJob != null, "StartJobCompleted only available on Job2"); + Dbg.Assert(childJob is not null, "StartJobCompleted only available on Job2"); _tracer.WriteMessage(TraceClassName, "StartJobAsync-Handler", Guid.Empty, this, "Finished starting child job asynchronously, child InstanceId: {0}", childJob.InstanceId.ToString()); - if (e.Error != null) + if (e.Error is not null) { ExecutionError.Add(new ErrorRecord(e.Error, "ContainerParentJobStartAsyncError", ErrorCategory.InvalidResult, childJob)); @@ -928,7 +928,7 @@ public override void StartJobAsync() } Interlocked.Increment(ref startedChildJobsCount); - Dbg.Assert(eventHandler != null, "Event handler magically disappeared"); + Dbg.Assert(eventHandler is not null, "Event handler magically disappeared"); childJob.StartJobCompleted -= eventHandler; if (startedChildJobsCount == ChildJobs.Count) @@ -946,7 +946,7 @@ public override void StartJobAsync() foreach (Job2 job in ChildJobs) { - Dbg.Assert(job != null, "Job is null after initial null check"); + Dbg.Assert(job is not null, "Job is null after initial null check"); job.StartJobCompleted += eventHandler; _tracer.WriteMessage(TraceClassName, "StartJobAsync", Guid.Empty, this, @@ -982,7 +982,7 @@ public override void ResumeJob() if (ChildJobs.Count == 1) { Job2 child = ChildJobs[0] as Job2; - Dbg.Assert(child != null, "Job is null after initial null check"); + Dbg.Assert(child is not null, "Job is null after initial null check"); #pragma warning disable 56500 try { @@ -1012,15 +1012,15 @@ public override void ResumeJob() EventHandler eventHandler = null; foreach (Job2 job in ChildJobs) { - Dbg.Assert(job != null, "Job is null after initial null check"); + Dbg.Assert(job is not null, "Job is null after initial null check"); eventHandler = (object sender, AsyncCompletedEventArgs e) => { var childJob = sender as Job2; - Dbg.Assert(childJob != null, "ResumeJobCompleted only available on Job2"); + Dbg.Assert(childJob is not null, "ResumeJobCompleted only available on Job2"); _tracer.WriteMessage(TraceClassName, "ResumeJob-Handler", Guid.Empty, this, "Finished resuming child job asynchronously, child InstanceId: {0}", job.InstanceId.ToString()); - if (e.Error != null) + if (e.Error is not null) { ExecutionError.Add(new ErrorRecord(e.Error, "ContainerParentJobResumeError", ErrorCategory.InvalidResult, job)); @@ -1045,10 +1045,10 @@ public override void ResumeJob() } completed.WaitOne(); - Dbg.Assert(eventHandler != null, "Event handler magically disappeared"); + Dbg.Assert(eventHandler is not null, "Event handler magically disappeared"); foreach (Job2 job in ChildJobs) { - Dbg.Assert(job != null, "Job is null after initial null check"); + Dbg.Assert(job is not null, "Job is null after initial null check"); job.ResumeJobCompleted -= eventHandler; } @@ -1079,16 +1079,16 @@ public override void ResumeJobAsync() var resumedChildJobsCount = 0; foreach (Job2 job in ChildJobs) { - Dbg.Assert(job != null, "Job is null after initial null check"); + Dbg.Assert(job is not null, "Job is null after initial null check"); EventHandler eventHandler = null; eventHandler = (sender, e) => { var childJob = sender as Job2; - Dbg.Assert(childJob != null, "ResumeJobCompleted only available on Job2"); + Dbg.Assert(childJob is not null, "ResumeJobCompleted only available on Job2"); _tracer.WriteMessage(TraceClassName, "ResumeJobAsync-Handler", Guid.Empty, this, "Finished resuming child job asynchronously, child InstanceId: {0}", job.InstanceId.ToString()); - if (e.Error != null) + if (e.Error is not null) { ExecutionError.Add(new ErrorRecord(e.Error, "ContainerParentJobResumeAsyncError", ErrorCategory.InvalidResult, job)); @@ -1098,7 +1098,7 @@ public override void ResumeJobAsync() } Interlocked.Increment(ref resumedChildJobsCount); - Dbg.Assert(eventHandler != null, "Event handler magically disappeared"); + Dbg.Assert(eventHandler is not null, "Event handler magically disappeared"); childJob.ResumeJobCompleted -= eventHandler; if (resumedChildJobsCount == ChildJobs.Count) { @@ -1222,7 +1222,7 @@ public override void UnblockJob() if (ChildJobs.Count == 1) { Job2 child = ChildJobs[0] as Job2; - Dbg.Assert(child != null, "Job is null after initial null check"); + Dbg.Assert(child is not null, "Job is null after initial null check"); #pragma warning disable 56500 try { @@ -1251,15 +1251,15 @@ public override void UnblockJob() EventHandler eventHandler = null; foreach (Job2 job in ChildJobs) { - Dbg.Assert(job != null, "Job is null after initial null check"); + Dbg.Assert(job is not null, "Job is null after initial null check"); eventHandler = (object sender, AsyncCompletedEventArgs e) => { var childJob = sender as Job2; - Dbg.Assert(childJob != null, "UnblockJobCompleted only available on Job2"); + Dbg.Assert(childJob is not null, "UnblockJobCompleted only available on Job2"); _tracer.WriteMessage(TraceClassName, "UnblockJob-Handler", Guid.Empty, this, "Finished unblock child job asynchronously, child InstanceId: {0}", job.InstanceId.ToString()); - if (e.Error != null) + if (e.Error is not null) { ExecutionError.Add(new ErrorRecord(e.Error, "ContainerParentJobUnblockError", ErrorCategory.InvalidResult, childJob)); @@ -1283,10 +1283,10 @@ public override void UnblockJob() } completed.WaitOne(); - Dbg.Assert(eventHandler != null, "Event handler magically disappeared"); + Dbg.Assert(eventHandler is not null, "Event handler magically disappeared"); foreach (Job2 job in ChildJobs) { - Dbg.Assert(job != null, "Job is null after initial null check"); + Dbg.Assert(job is not null, "Job is null after initial null check"); job.UnblockJobCompleted -= eventHandler; } @@ -1318,16 +1318,16 @@ public override void UnblockJobAsync() int unblockedChildJobsCount = 0; foreach (Job2 job in ChildJobs) { - Dbg.Assert(job != null, "Job is null after initial null check"); + Dbg.Assert(job is not null, "Job is null after initial null check"); EventHandler eventHandler = null; eventHandler = (sender, e) => { var childJob = sender as Job2; - Dbg.Assert(childJob != null, "UnblockJobCompleted only available on Job2"); + Dbg.Assert(childJob is not null, "UnblockJobCompleted only available on Job2"); _tracer.WriteMessage(TraceClassName, "UnblockJobAsync-Handler", Guid.Empty, this, "Finished unblock child job asynchronously, child InstanceId: {0}", job.InstanceId.ToString()); - if (e.Error != null) + if (e.Error is not null) { ExecutionError.Add(new ErrorRecord(e.Error, "ContainerParentJobUnblockError", ErrorCategory.InvalidResult, childJob)); @@ -1337,7 +1337,7 @@ public override void UnblockJobAsync() } Interlocked.Increment(ref unblockedChildJobsCount); - Dbg.Assert(eventHandler != null, "Event handler magically disappeared"); + Dbg.Assert(eventHandler is not null, "Event handler magically disappeared"); childJob.UnblockJobCompleted -= eventHandler; if (unblockedChildJobsCount == ChildJobs.Count) { @@ -1390,7 +1390,7 @@ private void SuspendJobInternal(bool? force, string reason) if (ChildJobs.Count == 1) { Job2 child = ChildJobs[0] as Job2; - Dbg.Assert(child != null, "Job is null after initial null check"); + Dbg.Assert(child is not null, "Job is null after initial null check"); #pragma warning disable 56500 try { @@ -1422,16 +1422,16 @@ private void SuspendJobInternal(bool? force, string reason) EventHandler eventHandler = null; foreach (Job2 job in ChildJobs) { - Dbg.Assert(job != null, "Job is null after initial null check"); + Dbg.Assert(job is not null, "Job is null after initial null check"); eventHandler = (object sender, AsyncCompletedEventArgs e) => { var childJob = sender as Job2; - Dbg.Assert(childJob != null, + Dbg.Assert(childJob is not null, "SuspendJobCompleted only available on Job2"); _tracer.WriteMessage(TraceClassName, "SuspendJob-Handler", Guid.Empty, this, "Finished suspending child job asynchronously, child InstanceId: {0} force: {1}", job.InstanceId.ToString(), force.ToString()); - if (e.Error != null) + if (e.Error is not null) { ExecutionError.Add(new ErrorRecord(e.Error, "ContainerParentJobSuspendError", ErrorCategory.InvalidResult, job)); @@ -1459,10 +1459,10 @@ private void SuspendJobInternal(bool? force, string reason) } completed.WaitOne(); - Dbg.Assert(eventHandler != null, "Event handler magically disappeared"); + Dbg.Assert(eventHandler is not null, "Event handler magically disappeared"); foreach (Job2 job in ChildJobs) { - Dbg.Assert(job != null, "Job is null after initial null check"); + Dbg.Assert(job is not null, "Job is null after initial null check"); job.SuspendJobCompleted -= eventHandler; } @@ -1495,16 +1495,16 @@ private void SuspendJobAsyncInternal(bool? force, string reason) var suspendedChildJobsCount = 0; foreach (Job2 job in ChildJobs) { - Dbg.Assert(job != null, "Job is null after initial null check"); + Dbg.Assert(job is not null, "Job is null after initial null check"); EventHandler eventHandler = null; eventHandler = (sender, e) => { var childJob = sender as Job2; - Dbg.Assert(childJob != null, "SuspendJobCompleted only available on Job2"); + Dbg.Assert(childJob is not null, "SuspendJobCompleted only available on Job2"); _tracer.WriteMessage(TraceClassName, "SuspendJobAsync-Handler", Guid.Empty, this, "Finished suspending child job asynchronously, child InstanceId: {0} force: {1}", job.InstanceId.ToString(), force.ToString()); - if (e.Error != null) + if (e.Error is not null) { ExecutionError.Add(new ErrorRecord(e.Error, "ContainerParentJobSuspendAsyncError", ErrorCategory.InvalidResult, job)); @@ -1514,7 +1514,7 @@ private void SuspendJobAsyncInternal(bool? force, string reason) } Interlocked.Increment(ref suspendedChildJobsCount); - Dbg.Assert(eventHandler != null, "Event handler magically disappeared"); + Dbg.Assert(eventHandler is not null, "Event handler magically disappeared"); childJob.SuspendJobCompleted -= eventHandler; if (suspendedChildJobsCount == ChildJobs.Count) { @@ -1566,7 +1566,7 @@ private void StopJobInternal(bool? force, string reason) if (ChildJobs.Count == 1) { Job2 child = ChildJobs[0] as Job2; - Dbg.Assert(child != null, "Job is null after initial null check"); + Dbg.Assert(child is not null, "Job is null after initial null check"); #pragma warning disable 56500 try { @@ -1599,16 +1599,16 @@ private void StopJobInternal(bool? force, string reason) EventHandler eventHandler = null; foreach (Job2 job in ChildJobs) { - Dbg.Assert(job != null, "Job is null after initial null check"); + Dbg.Assert(job is not null, "Job is null after initial null check"); eventHandler = (object sender, AsyncCompletedEventArgs e) => { var childJob = sender as Job2; - Dbg.Assert(childJob != null, + Dbg.Assert(childJob is not null, "StopJobCompleted only available on Job2"); _tracer.WriteMessage(TraceClassName, "StopJob-Handler", Guid.Empty, this, "Finished stopping child job asynchronously, child InstanceId: {0}", job.InstanceId.ToString()); - if (e.Error != null) + if (e.Error is not null) { ExecutionError.Add(new ErrorRecord(e.Error, "ContainerParentJobStopError", ErrorCategory.InvalidResult, job)); @@ -1636,10 +1636,10 @@ private void StopJobInternal(bool? force, string reason) } completed.WaitOne(); - Dbg.Assert(eventHandler != null, "Event handler magically disappeared"); + Dbg.Assert(eventHandler is not null, "Event handler magically disappeared"); foreach (Job2 job in ChildJobs) { - Dbg.Assert(job != null, "Job is null after initial null check"); + Dbg.Assert(job is not null, "Job is null after initial null check"); job.StopJobCompleted -= eventHandler; } @@ -1673,16 +1673,16 @@ private void StopJobAsyncInternal(bool? force, string reason) int stoppedChildJobsCount = 0; foreach (Job2 job in ChildJobs) { - Dbg.Assert(job != null, "Job is null after initial null check"); + Dbg.Assert(job is not null, "Job is null after initial null check"); EventHandler eventHandler = null; eventHandler = (sender, e) => { var childJob = sender as Job2; - Dbg.Assert(childJob != null, "StopJobCompleted only available on Job2"); + Dbg.Assert(childJob is not null, "StopJobCompleted only available on Job2"); _tracer.WriteMessage(TraceClassName, "StopJobAsync-Handler", Guid.Empty, this, "Finished stopping child job asynchronously, child InstanceId: {0}", job.InstanceId.ToString()); - if (e.Error != null) + if (e.Error is not null) { ExecutionError.Add(new ErrorRecord(e.Error, "ContainerParentJobStopAsyncError", ErrorCategory.InvalidResult, childJob)); @@ -1692,7 +1692,7 @@ private void StopJobAsyncInternal(bool? force, string reason) } Interlocked.Increment(ref stoppedChildJobsCount); - Dbg.Assert(eventHandler != null, "Event handler magically disappeared"); + Dbg.Assert(eventHandler is not null, "Event handler magically disappeared"); childJob.StopJobCompleted -= eventHandler; if (stoppedChildJobsCount == ChildJobs.Count) { @@ -1733,7 +1733,7 @@ private void HandleMyStateChanged(object sender, JobStateEventArgs e) JobRunning.Set(); // Do not create the event if it doesn't already exist. Suspend may never be called. - if (_jobSuspendedOrAborted != null) + if (_jobSuspendedOrAborted is not null) JobSuspendedOrAborted.Reset(); } } @@ -2022,10 +2022,10 @@ protected override void Dispose(bool disposing) job.Dispose(); } - if (_jobRunning != null) + if (_jobRunning is not null) _jobRunning.Dispose(); - if (_jobSuspendedOrAborted != null) + if (_jobSuspendedOrAborted is not null) _jobSuspendedOrAborted.Dispose(); } finally diff --git a/src/System.Management.Automation/engine/remoting/client/JobManager.cs b/src/System.Management.Automation/engine/remoting/client/JobManager.cs index 7adea9a2eb5..7f4ac86a1cf 100644 --- a/src/System.Management.Automation/engine/remoting/client/JobManager.cs +++ b/src/System.Management.Automation/engine/remoting/client/JobManager.cs @@ -78,7 +78,7 @@ internal void RegisterJobSourceAdapter(Type jobSourceAdapterType) { Dbg.Assert(typeof(JobSourceAdapter).IsAssignableFrom(jobSourceAdapterType), "BaseType of any type being registered with the JobManager should be JobSourceAdapter."); Dbg.Assert(jobSourceAdapterType != typeof(JobSourceAdapter), "JobSourceAdapter abstract type itself should never be registered."); - Dbg.Assert(jobSourceAdapterType != null, "JobSourceAdapterType should never be called with null value."); + Dbg.Assert(jobSourceAdapterType is not null, "JobSourceAdapterType should never be called with null value."); object instance = null; ConstructorInfo constructor = jobSourceAdapterType.GetConstructor(Type.EmptyTypes); @@ -120,7 +120,7 @@ internal void RegisterJobSourceAdapter(Type jobSourceAdapterType) throw; } - if (instance != null) + if (instance is not null) { lock (_syncObject) { @@ -327,7 +327,7 @@ private JobSourceAdapter GetJobSourceAdapter(JobDefinition definition) { adapterTypeName = definition.JobSourceAdapterTypeName; } - else if (definition.JobSourceAdapterType != null) + else if (definition.JobSourceAdapterType is not null) { adapterTypeName = definition.JobSourceAdapterType.Name; } @@ -384,7 +384,7 @@ private JobSourceAdapter GetJobSourceAdapter(JobDefinition definition) ex = e; } - if (ex != null) + if (ex is not null) { throw new InvalidOperationException(RemotingErrorIdStrings.JobSourceAdapterNotFound, ex); } @@ -528,7 +528,7 @@ internal bool IsJobFromAdapter(Guid id, string name) { if (sourceAdapter.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) { - return (sourceAdapter.GetJobByInstanceId(id, false) != null); + return (sourceAdapter.GetJobByInstanceId(id, false) is not null); } } } @@ -559,7 +559,7 @@ private List GetFilteredJobs( bool recurse, string[] jobSourceAdapterTypes) { - Diagnostics.Assert(cmdlet != null, "Cmdlet should be passed to JobManager"); + Diagnostics.Assert(cmdlet is not null, "Cmdlet should be passed to JobManager"); List allJobs = new List(); @@ -626,7 +626,7 @@ private bool CheckTypeNames(JobSourceAdapter sourceAdapter, string[] jobSourceAd } string sourceAdapterName = GetAdapterName(sourceAdapter); - Diagnostics.Assert(sourceAdapterName != null, "Source adapter should have name or type."); + Diagnostics.Assert(sourceAdapterName is not null, "Source adapter should have name or type."); // Look for name match allowing wildcards. foreach (string typeName in jobSourceAdapterTypes) @@ -684,7 +684,7 @@ private static List CallJobFilter(JobSourceAdapter sourceAdapter, object f break; } - if (matches != null) + if (matches is not null) { jobs.AddRange(matches); } @@ -726,7 +726,7 @@ internal Job2 GetJobByInstanceId(Guid instanceId, Cmdlet cmdlet, bool writeError private Job2 GetJobThroughId(Guid guid, int id, Cmdlet cmdlet, bool writeErrorOnException, bool writeObject, bool recurse) { - Diagnostics.Assert(cmdlet != null, "Cmdlet should always be passed to JobManager"); + Diagnostics.Assert(cmdlet is not null, "Cmdlet should always be passed to JobManager"); Job2 job = null; lock (_syncObject) { @@ -791,7 +791,7 @@ internal List GetJobToStart( bool writeErrorOnException) { List jobs = new List(); - WildcardPattern typeNamePattern = (definitionType != null) ? + WildcardPattern typeNamePattern = (definitionType is not null) ? WildcardPattern.Get(definitionType, WildcardOptions.IgnoreCase) : null; lock (_syncObject) @@ -800,7 +800,7 @@ internal List GetJobToStart( { try { - if (typeNamePattern != null) + if (typeNamePattern is not null) { string sourceAdapterName = GetAdapterName(sourceAdapter); if (!typeNamePattern.IsMatch(sourceAdapterName)) @@ -810,12 +810,12 @@ internal List GetJobToStart( } Job2 job = sourceAdapter.NewJob(definitionName, definitionPath); - if (job != null) + if (job is not null) { jobs.Add(job); } - if (typeNamePattern != null) + if (typeNamePattern is not null) { // Adapter type found, can quit. break; diff --git a/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs b/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs index a2840335739..bd9363b302d 100644 --- a/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs +++ b/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs @@ -132,7 +132,7 @@ public CommandInfo CommandInfo public JobDefinition(Type jobSourceAdapterType, string command, string name) { JobSourceAdapterType = jobSourceAdapterType; - if (jobSourceAdapterType != null) + if (jobSourceAdapterType is not null) { _jobSourceAdapterTypeName = jobSourceAdapterType.Name; } @@ -279,7 +279,7 @@ public JobInvocationInfo(JobDefinition definition, Dictionary pa { _definition = definition; var convertedCollection = ConvertDictionaryToParameterCollection(parameters); - if (convertedCollection != null) + if (convertedCollection is not null) { Parameters.Add(convertedCollection); } @@ -301,7 +301,7 @@ public JobInvocationInfo(JobDefinition definition, IEnumerable 0) + if (recurse && job.ChildJobs is not null && job.ChildJobs.Count > 0) { Hashtable duplicateDetector = new Hashtable(); duplicateDetector.Add(job.InstanceId, job.InstanceId); diff --git a/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs b/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs index ff8fb949759..edf740231bf 100644 --- a/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs +++ b/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs @@ -236,7 +236,7 @@ internal int MaxRetryConnectionTime { get { - return (DataStructureHandler != null) ? DataStructureHandler.MaxRetryConnectionTime : 0; + return (DataStructureHandler is not null) ? DataStructureHandler.MaxRetryConnectionTime : 0; } } @@ -530,7 +530,7 @@ internal void HandleStateInfoReceived(object sender, RunspacePoolStateInfo newStateInfo = eventArgs.Data; bool raiseEvents = false; - Dbg.Assert(newStateInfo != null, "state information should not be null"); + Dbg.Assert(newStateInfo is not null, "state information should not be null"); if (newStateInfo.State == RunspacePoolState.Opened) { @@ -598,7 +598,7 @@ internal void HandleStateInfoReceived(object sender, internal void HandleRemoteHostCalls(object sender, RemoteDataEventArgs eventArgs) { - if (HostCallReceived != null) + if (HostCallReceived is not null) { HostCallReceived.SafeInvoke(sender, eventArgs); } @@ -729,7 +729,7 @@ internal bool CanDisconnect get { Version remoteProtocolVersionDeclaredByServer = PSRemotingProtocolVersion; - if (remoteProtocolVersionDeclaredByServer != null && DataStructureHandler != null) + if (remoteProtocolVersionDeclaredByServer is not null && DataStructureHandler is not null) { // Disconnect/Connect support is currently only provided by the WSMan transport // that is running PSRP protocol version 2.2 and greater. @@ -752,7 +752,7 @@ internal Version PSRemotingProtocolVersion Version winRMProtocolVersion = null; PSPrimitiveDictionary psPrimitiveDictionary = GetApplicationPrivateData(); - if (psPrimitiveDictionary != null) + if (psPrimitiveDictionary is not null) { PSPrimitiveDictionary.TryPathGet( psPrimitiveDictionary, @@ -771,7 +771,7 @@ internal Version PSRemotingProtocolVersion /// PowerShell. internal void PushRunningPowerShell(PowerShell ps) { - Dbg.Assert(ps != null, "Caller should not pass in null reference."); + Dbg.Assert(ps is not null, "Caller should not pass in null reference."); _runningPowerShells.Push(ps); } @@ -1300,7 +1300,7 @@ internal static RunspacePool[] GetRemoteRunspacePools(RunspaceConnectionInfo con } catch (CmdletInvocationException e) { - if (e.InnerException != null && e.InnerException is InvalidOperationException) + if (e.InnerException is not null && e.InnerException is InvalidOperationException) { // If we cannot successfully retrieve command information then this runspace // object we are building is invalid and must be skipped. @@ -1321,7 +1321,7 @@ internal static RunspacePool[] GetRemoteRunspacePools(RunspaceConnectionInfo con continue; } - string cmdLine = (pspCommandLine != null) ? pspCommandLine.Value.ToString() : string.Empty; + string cmdLine = (pspCommandLine is not null) ? pspCommandLine.Value.ToString() : string.Empty; Guid cmdId = Guid.Parse(pspCommandId.Value.ToString()); connectCmdInfos.Add(new ConnectCommandInfo(cmdId, cmdLine)); @@ -1341,7 +1341,7 @@ internal static RunspacePool[] GetRemoteRunspacePools(RunspaceConnectionInfo con internal static RunspacePool GetRemoteRunspacePool(RunspaceConnectionInfo connectionInfo, Guid sessionId, Guid? commandId, PSHost host, TypeTable typeTable) { List connectCmdInfos = new List(); - if (commandId != null) + if (commandId is not null) { connectCmdInfos.Add(new ConnectCommandInfo(commandId.Value, string.Empty)); } @@ -1363,7 +1363,7 @@ private static void UpdateWSManConnectionInfo( PSPropertyInfo pspProfile = rsInfoObject.Properties["ProfileLoaded"]; PSPropertyInfo pspMaxIdleTimeout = rsInfoObject.Properties["MaxIdleTimeout"]; - if (pspIdleTimeOut != null) + if (pspIdleTimeOut is not null) { int idleTimeout; if (GetTimeIntValue(pspIdleTimeOut.Value as string, out idleTimeout)) @@ -1372,10 +1372,10 @@ private static void UpdateWSManConnectionInfo( } } - if (pspBufferMode != null) + if (pspBufferMode is not null) { string bufferingMode = pspBufferMode.Value as string; - if (bufferingMode != null) + if (bufferingMode is not null) { OutputBufferingMode outputBufferingMode; if (Enum.TryParse(bufferingMode, out outputBufferingMode)) @@ -1386,19 +1386,19 @@ private static void UpdateWSManConnectionInfo( } } - if (pspResourceUri != null) + if (pspResourceUri is not null) { string strShellUri = pspResourceUri.Value as string; - if (strShellUri != null) + if (strShellUri is not null) { wsmanConnectionInfo.ShellUri = strShellUri; } } - if (pspLocale != null) + if (pspLocale is not null) { string localString = pspLocale.Value as string; - if (localString != null) + if (localString is not null) { try { @@ -1409,10 +1409,10 @@ private static void UpdateWSManConnectionInfo( } } - if (pspDataLocale != null) + if (pspDataLocale is not null) { string dataLocalString = pspDataLocale.Value as string; - if (dataLocalString != null) + if (dataLocalString is not null) { try { @@ -1423,37 +1423,37 @@ private static void UpdateWSManConnectionInfo( } } - if (pspCompressionMode != null) + if (pspCompressionMode is not null) { string compressionModeString = pspCompressionMode.Value as string; - if (compressionModeString != null) + if (compressionModeString is not null) { wsmanConnectionInfo.UseCompression = compressionModeString.Equals("NoCompression", StringComparison.OrdinalIgnoreCase) ? false : true; } } - if (pspEncoding != null) + if (pspEncoding is not null) { string encodingString = pspEncoding.Value as string; - if (encodingString != null) + if (encodingString is not null) { wsmanConnectionInfo.UseUTF16 = encodingString.Equals("UTF16", StringComparison.OrdinalIgnoreCase) ? true : false; } } - if (pspProfile != null) + if (pspProfile is not null) { string machineProfileLoadedString = pspProfile.Value as string; - if (machineProfileLoadedString != null) + if (machineProfileLoadedString is not null) { wsmanConnectionInfo.NoMachineProfile = machineProfileLoadedString.Equals("Yes", StringComparison.OrdinalIgnoreCase) ? false : true; } } - if (pspMaxIdleTimeout != null) + if (pspMaxIdleTimeout is not null) { int maxIdleTimeout; if (GetTimeIntValue(pspMaxIdleTimeout.Value as string, out maxIdleTimeout)) @@ -1471,11 +1471,11 @@ private static void ComputeDisconnectedOnExpiresOn( PSPropertyInfo pspIdleTimeOut = rsInfoObject.Properties["IdleTimeOut"]; PSPropertyInfo pspShellInactivity = rsInfoObject.Properties["ShellInactivity"]; - if (pspIdleTimeOut != null && pspShellInactivity != null) + if (pspIdleTimeOut is not null && pspShellInactivity is not null) { string shellInactivityString = pspShellInactivity.Value as string; int idleTimeout; - if ((shellInactivityString != null) && + if ((shellInactivityString is not null) && GetTimeIntValue(pspIdleTimeOut.Value as string, out idleTimeout)) { try @@ -1507,7 +1507,7 @@ private static void ComputeDisconnectedOnExpiresOn( private static bool GetTimeIntValue(string timeString, out int value) { - if (timeString != null) + if (timeString is not null) { string timeoutString = timeString.Replace("PT", string.Empty).Replace("S", string.Empty); try @@ -1595,7 +1595,7 @@ private void HandleSessionDisconnected(object sender, RemoteDataEventArgs /// Arguments describing this event. private void HandleSessionClosed(object sender, RemoteDataEventArgs eventArgs) { - if (eventArgs.Data != null) + if (eventArgs.Data is not null) { _closingReason = eventArgs.Data; } @@ -1711,7 +1711,7 @@ private void SetOpenAsCompleted() { RunspacePoolAsyncResult tempOpenAsyncResult = _openAsyncResult; _openAsyncResult = null; - if (tempOpenAsyncResult != null && !tempOpenAsyncResult.IsCompleted) + if (tempOpenAsyncResult is not null && !tempOpenAsyncResult.IsCompleted) { tempOpenAsyncResult.SetAsCompleted(stateInfo.Reason); } @@ -1725,7 +1725,7 @@ private void SetCloseAsCompleted() // abort all pending calls. DispatchTable.AbortAllCalls(); - if (_closeAsyncResult != null) + if (_closeAsyncResult is not null) { _closeAsyncResult.SetAsCompleted(stateInfo.Reason); _closeAsyncResult = null; @@ -1769,7 +1769,7 @@ private void HandleResponseReceived(object sender, RemoteDataEventArgs private void HandleURIDirectionReported(object sender, RemoteDataEventArgs eventArgs) { WSManConnectionInfo wsmanConnectionInfo = _connectionInfo as WSManConnectionInfo; - if (wsmanConnectionInfo != null) + if (wsmanConnectionInfo is not null) { wsmanConnectionInfo.ConnectionUri = eventArgs.Data; URIRedirectionReported.SafeInvoke(this, eventArgs); @@ -1811,12 +1811,12 @@ private void HandleSessionRCDisconnecting(object sender, RemoteDataEventArgs Event arguments cannot be null."); + Dbg.Assert(info is not null, "State -> Event arguments cannot be null."); // Wait for private application data to arrive from server. try @@ -1993,12 +1993,12 @@ internal static Collection GetRemotePools(WSManConnectionInfo wsmanCon // Add parameters for server connection. powerShell.AddParameter("ComputerName", wsmanConnectionInfo.ComputerName); powerShell.AddParameter("Authentication", ConvertPSAuthToWSManAuth(wsmanConnectionInfo.AuthenticationMechanism)); - if (wsmanConnectionInfo.Credential != null) + if (wsmanConnectionInfo.Credential is not null) { powerShell.AddParameter("Credential", wsmanConnectionInfo.Credential); } - if (wsmanConnectionInfo.CertificateThumbprint != null) + if (wsmanConnectionInfo.CertificateThumbprint is not null) { powerShell.AddParameter("CertificateThumbprint", wsmanConnectionInfo.CertificateThumbprint); } @@ -2053,12 +2053,12 @@ internal static Collection GetRemoteCommands(Guid shellId, WSManConnec // Add parameters for server connection. powerShell.AddParameter("ComputerName", wsmanConnectionInfo.ComputerName); powerShell.AddParameter("Authentication", ConvertPSAuthToWSManAuth(wsmanConnectionInfo.AuthenticationMechanism)); - if (wsmanConnectionInfo.Credential != null) + if (wsmanConnectionInfo.Credential is not null) { powerShell.AddParameter("Credential", wsmanConnectionInfo.Credential); } - if (wsmanConnectionInfo.CertificateThumbprint != null) + if (wsmanConnectionInfo.CertificateThumbprint is not null) { powerShell.AddParameter("CertificateThumbprint", wsmanConnectionInfo.CertificateThumbprint); } @@ -2106,7 +2106,7 @@ private static object GetSessionOptions(WSManConnectionInfo wsmanConnectionInfo) powerShell.AddParameter("ProxyAccessType", "Proxy" + wsmanConnectionInfo.ProxyAccessType.ToString()); powerShell.AddParameter("ProxyAuthentication", wsmanConnectionInfo.ProxyAuthentication.ToString()); - if (wsmanConnectionInfo.ProxyCredential != null) + if (wsmanConnectionInfo.ProxyCredential is not null) { powerShell.AddParameter("ProxyCredential", wsmanConnectionInfo.ProxyCredential); } diff --git a/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs b/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs index 8e478f0b36b..e133dd629c8 100644 --- a/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs +++ b/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs @@ -43,7 +43,7 @@ public RemotingErrorRecord(ErrorRecord errorRecord, OriginInfo originInfo) : thi private RemotingErrorRecord(ErrorRecord errorRecord, OriginInfo originInfo, Exception replaceParentContainsErrorRecordException) : base(errorRecord, replaceParentContainsErrorRecordException) { - if (errorRecord != null) + if (errorRecord is not null) { base.SetInvocationInfo(errorRecord.InvocationInfo); } @@ -128,7 +128,7 @@ public RemotingProgressRecord(ProgressRecord progressRecord, OriginInfo originIn base(Validate(progressRecord).ActivityId, Validate(progressRecord).Activity, Validate(progressRecord).StatusDescription) { _originInfo = originInfo; - if (progressRecord != null) + if (progressRecord is not null) { this.PercentComplete = progressRecord.PercentComplete; this.ParentActivityId = progressRecord.ParentActivityId; diff --git a/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs b/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs index e164e1e5bf3..7c2ea7831bb 100644 --- a/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs +++ b/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs @@ -129,7 +129,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) { case RemotingDataType.RemoteHostCallUsingRunspaceHost: { - Dbg.Assert(RemoteHostCallReceived != null, + Dbg.Assert(RemoteHostCallReceived is not null, "RemoteRunspacePoolInternal should subscribe to all data structure handler events"); RemoteHostCall remoteHostCall = RemoteHostCall.Decode(receivedData.Data); @@ -142,7 +142,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) { RunspacePoolInitInfo initInfo = RemotingDecoder.GetRunspacePoolInitInfo(receivedData.Data); - Dbg.Assert(RSPoolInitInfoReceived != null, + Dbg.Assert(RSPoolInitInfoReceived is not null, "RemoteRunspacePoolInternal should subscribe to all data structure handler events"); RSPoolInitInfoReceived.SafeInvoke(this, new RemoteDataEventArgs(initInfo)); @@ -155,7 +155,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) RunspacePoolStateInfo stateInfo = RemotingDecoder.GetRunspacePoolStateInfo(receivedData.Data); - Dbg.Assert(StateInfoReceived != null, + Dbg.Assert(StateInfoReceived is not null, "RemoteRunspacePoolInternal should subscribe to all data structure handler events"); StateInfoReceived.SafeInvoke(this, new RemoteDataEventArgs(stateInfo)); @@ -168,7 +168,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) case RemotingDataType.ApplicationPrivateData: { PSPrimitiveDictionary applicationPrivateData = RemotingDecoder.GetApplicationPrivateData(receivedData.Data); - Dbg.Assert(ApplicationPrivateDataReceived != null, + Dbg.Assert(ApplicationPrivateDataReceived is not null, "RemoteRunspacePoolInternal should subscribe to all data structure handler events"); ApplicationPrivateDataReceived.SafeInvoke(this, new RemoteDataEventArgs(applicationPrivateData)); @@ -178,7 +178,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) case RemotingDataType.RunspacePoolOperationResponse: { - Dbg.Assert(SetMaxMinRunspacesResponseReceived != null, + Dbg.Assert(SetMaxMinRunspacesResponseReceived is not null, "RemoteRunspacePoolInternal should subscribe to all data structure handler events"); SetMaxMinRunspacesResponseReceived.SafeInvoke(this, new RemoteDataEventArgs(receivedData.Data)); @@ -190,7 +190,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) { PSEventArgs psEventArgs = RemotingDecoder.GetPSEventArgs(receivedData.Data); - Dbg.Assert(PSEventArgsReceived != null, + Dbg.Assert(PSEventArgsReceived is not null, "RemoteRunspacePoolInternal should subscribe to all data structure handler events"); PSEventArgsReceived.SafeInvoke(this, new RemoteDataEventArgs(psEventArgs)); @@ -233,7 +233,7 @@ internal void CreatePowerShellOnServerAndInvoke(ClientRemotePowerShell shell) // Find out if this is an invoke and disconnect operation and if so whether the endpoint // supports disconnect. Throw exception if disconnect is not supported. - bool invokeAndDisconnect = (shell.Settings != null) ? shell.Settings.InvokeAndDisconnect : false; + bool invokeAndDisconnect = (shell.Settings is not null) ? shell.Settings.InvokeAndDisconnect : false; if (invokeAndDisconnect && !EndpointSupportsDisconnect) { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.EndpointDoesNotSupportDisconnect); @@ -275,7 +275,7 @@ internal void DispatchMessageToPowerShell(RemoteDataObject rcvdData) // if a data structure handler does not exist it means // the association has been removed - // discard messages - if (dsHandler != null) + if (dsHandler is not null) { dsHandler.ProcessReceivedData(rcvdData); } @@ -550,7 +550,7 @@ private void HandleClientRemoteSessionStateChanged( // if there is a reason associated, then most likely the // runspace pool has broken, so notify accordingly - if (reason != null) + if (reason is not null) { NotifyAssociatedPowerShells(new RunspacePoolStateInfo(RunspacePoolState.Broken, reason)); } @@ -587,7 +587,7 @@ private void HandleClientRemoteSessionStateChanged( } else { - if (e.SessionStateInfo.Reason != null) + if (e.SessionStateInfo.Reason is not null) { _closingReason = e.SessionStateInfo.Reason; } @@ -899,7 +899,7 @@ internal BaseClientSessionTransportManager TransportManager { get { - if (RemoteSession != null) + if (RemoteSession is not null) { return RemoteSession.SessionDataStructureHandler.TransportManager; } @@ -918,7 +918,7 @@ internal int MaxRetryConnectionTime { get { - if (_transportManager != null && + if (_transportManager is not null && _transportManager is WSManClientSessionTransportManager) { return ((WSManClientSessionTransportManager)(_transportManager)).MaxRetryConnectionTime; @@ -937,7 +937,7 @@ internal bool EndpointSupportsDisconnect get { WSManClientSessionTransportManager wsmanTransportManager = _transportManager as WSManClientSessionTransportManager; - return (wsmanTransportManager != null) ? wsmanTransportManager.SupportsDisconnect : false; + return (wsmanTransportManager is not null) ? wsmanTransportManager.SupportsDisconnect : false; } } @@ -963,7 +963,7 @@ public void Dispose(bool disposing) { if (disposing) { - if (RemoteSession != null) + if (RemoteSession is not null) { ((ClientRemoteSessionImpl)RemoteSession).Dispose(); RemoteSession = null; @@ -1218,7 +1218,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) PSInvocationStateInfo stateInfo = RemotingDecoder.GetPowerShellStateInfo(receivedData.Data); - Dbg.Assert(InvocationStateInfoReceived != null, + Dbg.Assert(InvocationStateInfoReceived is not null, "ClientRemotePowerShell should subscribe to all data structure handler events"); InvocationStateInfoReceived.SafeInvoke(this, new RemoteDataEventArgs(stateInfo)); @@ -1236,7 +1236,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) // not be added in this case. If a remoting cmdlet // is using PowerShell, then it should take care // of adding the origin information - Dbg.Assert(OutputReceived != null, + Dbg.Assert(OutputReceived is not null, "ClientRemotePowerShell should subscribe to all data structure handler events"); OutputReceived.SafeInvoke(this, new RemoteDataEventArgs(outputObject)); @@ -1256,7 +1256,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) // as well. If a remoting cmdlet // is using PowerShell, then it should take care // of adding the origin information - Dbg.Assert(ErrorReceived != null, + Dbg.Assert(ErrorReceived is not null, "ClientRemotePowerShell should subscribe to all data structure handler events"); ErrorReceived.SafeInvoke(this, @@ -1346,7 +1346,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) /// goes into a closed or broken state internal void SetStateToFailed(Exception reason) { - Dbg.Assert(BrokenNotificationFromRunspacePool != null, + Dbg.Assert(BrokenNotificationFromRunspacePool is not null, "ClientRemotePowerShell should subscribe to all data structure handler events"); BrokenNotificationFromRunspacePool.SafeInvoke(this, new RemoteDataEventArgs(reason)); @@ -1359,7 +1359,7 @@ internal void SetStateToFailed(Exception reason) /// set to a stopped state. internal void SetStateToStopped(Exception reason) { - Dbg.Assert(ClosedNotificationFromRunspacePool != null, + Dbg.Assert(ClosedNotificationFromRunspacePool is not null, "ClientRemotePowerShell should subscribe to all data structure handler events"); ClosedNotificationFromRunspacePool.SafeInvoke(this, new RemoteDataEventArgs(reason)); @@ -1375,7 +1375,7 @@ internal void CloseConnectionAsync(Exception sessionCloseReason) // wait for the close to complete and then dispose the transport manager TransportManager.CloseCompleted += delegate (object source, EventArgs args) { - if (CloseCompleted != null) + if (CloseCompleted is not null) { // If the provided event args are empty then call CloseCompleted with // RemoteSessionStateEventArgs containing session closed reason exception. @@ -1412,9 +1412,9 @@ internal void ProcessDisconnect(RunspacePoolStateInfo rsStateInfo) // disconnect may be called on a pipeline that is already disconnected. PSInvocationStateInfo stateInfo = new PSInvocationStateInfo(PSInvocationState.Disconnected, - (rsStateInfo != null) ? rsStateInfo.Reason : null); + (rsStateInfo is not null) ? rsStateInfo.Reason : null); - Dbg.Assert(InvocationStateInfoReceived != null, + Dbg.Assert(InvocationStateInfoReceived is not null, "ClientRemotePowerShell should subscribe to all data structure handler events"); InvocationStateInfoReceived.SafeInvoke(this, new RemoteDataEventArgs(stateInfo)); diff --git a/src/System.Management.Automation/engine/remoting/client/RunspaceRef.cs b/src/System.Management.Automation/engine/remoting/client/RunspaceRef.cs index eb3dcf49492..00129ccc07e 100644 --- a/src/System.Management.Automation/engine/remoting/client/RunspaceRef.cs +++ b/src/System.Management.Automation/engine/remoting/client/RunspaceRef.cs @@ -32,7 +32,7 @@ internal class RunspaceRef /// internal RunspaceRef(Runspace runspace) { - Dbg.Assert(runspace != null, "Expected runspace != null"); + Dbg.Assert(runspace is not null, "Expected runspace is not null"); _runspaceRef = new ObjectRef(runspace); _stopInvoke = false; _localSyncObject = new object(); @@ -93,7 +93,7 @@ private PSCommand ParsePsCommandUsingScriptBlock(string line, bool? useLocalScop // and if we are not in a loopback configuration mode, in which case we always force remote script commands // to be parsed and evaluated on the remote session (not in the current local session). RemoteRunspace remoteRunspace = _runspaceRef.Value as RemoteRunspace; - bool isConfiguredLoopback = (remoteRunspace != null) ? remoteRunspace.IsConfiguredLoopBack : false; + bool isConfiguredLoopback = (remoteRunspace is not null) ? remoteRunspace.IsConfiguredLoopBack : false; bool isTrustedInput = !isConfiguredLoopback && (localRunspace.ExecutionContext.LanguageMode == PSLanguageMode.FullLanguage); // Create PowerShell from ScriptBlock. @@ -192,7 +192,7 @@ internal Pipeline CreatePipeline(string line, bool addToHistory, bool useNestedP } PSCommand psCommand = ParsePsCommandUsingScriptBlock(line, null); - if (psCommand != null) + if (psCommand is not null) { pipeline = useNestedPipelines ? _runspaceRef.Value.CreateNestedPipeline(psCommand.Commands[0].CommandText, addToHistory) : @@ -217,10 +217,10 @@ internal Pipeline CreatePipeline(string line, bool addToHistory, bool useNestedP // Add robust connection callback if this is a pushed runspace. RemotePipeline remotePipeline = pipeline as RemotePipeline; - if (this.IsRunspaceOverridden && remotePipeline != null) + if (this.IsRunspaceOverridden && remotePipeline is not null) { PowerShell shell = remotePipeline.PowerShell; - if (shell.RemotePowerShell != null) + if (shell.RemotePowerShell is not null) { shell.RemotePowerShell.RCConnectionNotification += HandleRCConnectionNotification; } @@ -230,8 +230,8 @@ internal Pipeline CreatePipeline(string line, bool addToHistory, bool useNestedP { RemoteRunspace remoteRunspace = _runspaceRef.Value as RemoteRunspace; PSDataCollection erBuffer = sender as PSDataCollection; - if (remoteRunspace != null && erBuffer != null && - remoteRunspace.RunspacePool.RemoteRunspacePoolInternal.Host != null) + if (remoteRunspace is not null && erBuffer is not null && + remoteRunspace.RunspacePool.RemoteRunspacePoolInternal.Host is not null) { Collection erRecords = erBuffer.ReadAll(); foreach (var er in erRecords) @@ -287,7 +287,7 @@ internal void Override(RemoteRunspace remoteRunspace, object syncObject, out boo try { - if (syncObject != null) + if (syncObject is not null) { lock (syncObject) { @@ -301,7 +301,7 @@ internal void Override(RemoteRunspace remoteRunspace, object syncObject, out boo isRunspacePushed = true; } - if ((remoteRunspace.GetCurrentlyRunningPipeline() != null)) + if ((remoteRunspace.GetCurrentlyRunningPipeline() is not null)) { // Don't execute command if pushed runspace is already running one. return; @@ -382,8 +382,8 @@ private void HandleRCConnectionNotification(object sender, PSConnectionRetryStat private void WriteRCFailedError() { RemoteRunspace remoteRunspace = _runspaceRef.Value as RemoteRunspace; - if (remoteRunspace != null && - remoteRunspace.RunspacePool.RemoteRunspacePoolInternal.Host != null) + if (remoteRunspace is not null && + remoteRunspace.RunspacePool.RemoteRunspacePoolInternal.Host is not null) { remoteRunspace.RunspacePool.RemoteRunspacePoolInternal.Host.UI.WriteErrorLine( StringUtil.Format(RemotingErrorIdStrings.RCAutoDisconnectingError, @@ -397,7 +397,7 @@ private void StartProgressBar( int totalSeconds) { RemoteRunspace remoteRunspace = _runspaceRef.Value as RemoteRunspace; - if (remoteRunspace != null) + if (remoteRunspace is not null) { s_RCProgress.StartProgress( sourceId, diff --git a/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs b/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs index 76c2fd1cf60..6b6b10a7837 100644 --- a/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs +++ b/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs @@ -53,7 +53,7 @@ protected override void Dispose(bool disposing) childJob.Dispose(); } - if (_jobResultsThrottlingSemaphore != null) + if (_jobResultsThrottlingSemaphore is not null) { _jobResultsThrottlingSemaphore.Dispose(); } @@ -337,7 +337,7 @@ internal void DisableFlowControlForPendingJobsQueue() while (_actionsForUnblockingChildAdditions.Count > 0) { Action a = _actionsForUnblockingChildAdditions.Dequeue(); - if (a != null) + if (a is not null) { a(); } @@ -406,14 +406,14 @@ internal void AddChildJobWithoutBlocking(StartableJob childJob, ChildJobFlags fl } else { - if (jobEnqueuedAction != null) + if (jobEnqueuedAction is not null) { jobEnqueuedAction(); } } } - if (newJobStateInfo != null) + if (newJobStateInfo is not null) { this.SetJobState(newJobStateInfo.State, newJobStateInfo.Reason); } @@ -434,7 +434,7 @@ internal void AddChildJobWithoutBlocking(StartableJob childJob, ChildJobFlags fl private void childJob_ResultsAdded(object sender, DataAddedEventArgs e) { - Dbg.Assert(_jobResultsThrottlingSemaphore != null, "JobResultsThrottlingSemaphore should be non-null if childJob_ResultsAdded handled is registered"); + Dbg.Assert(_jobResultsThrottlingSemaphore is not null, "JobResultsThrottlingSemaphore should be non-null if childJob_ResultsAdded handled is registered"); try { long jobResultsUpdatedCount = Interlocked.Increment(ref _jobResultsCurrentCount); @@ -547,7 +547,7 @@ private void StartChildJobIfPossible() } while (false); } - if (readyToRunChildJob != null) + if (readyToRunChildJob is not null) { readyToRunChildJob.StartJob(); } @@ -628,7 +628,7 @@ private void FigureOutIfThrottlingJobIsCompleted() } } - if (finalJobStateInfo != null) + if (finalJobStateInfo is not null) { this.SetJobState(finalJobStateInfo.State, finalJobStateInfo.Reason); this.CloseAllStreams(); @@ -664,7 +664,7 @@ public override void StopJob() } } - if (childJobsToStop != null) + if (childJobsToStop is not null) { this.SetJobState(JobState.Stopping); @@ -688,7 +688,7 @@ public override void StopJob() private void childJob_StateChanged(object sender, JobStateEventArgs e) { - Dbg.Assert(sender != null, "Only our internal implementation of Job should raise this event and it should make sure that sender != null"); + Dbg.Assert(sender is not null, "Only our internal implementation of Job should raise this event and it should make sure that sender is not null"); Dbg.Assert(sender is Job, "Only our internal implementation of Job should raise this event and it should make sure that sender is Job"); var childJob = (Job)sender; @@ -746,7 +746,7 @@ private void childJob_StateChanged(object sender, JobStateEventArgs e) if (_actionsForUnblockingChildAdditions.Count > 0) { Action a = _actionsForUnblockingChildAdditions.Dequeue(); - if (a != null) + if (a is not null) { a(); } @@ -1126,7 +1126,7 @@ private void ForwardResults(Cmdlet cmdlet) { foreach (var result in _aggregatedResults.GetConsumingEnumerable(_throttlingJob._cancellationTokenSource.Token)) { - if (result != null) + if (result is not null) { #if DEBUG // CDXML_CLIXML_TEST testability hook @@ -1140,7 +1140,7 @@ private void ForwardResults(Cmdlet cmdlet) { if (_throttlingJob._cmdletMode) { - Dbg.Assert(_throttlingJob._jobResultsThrottlingSemaphore != null, "JobResultsThrottlingSemaphore should be present in cmdlet mode"); + Dbg.Assert(_throttlingJob._jobResultsThrottlingSemaphore is not null, "JobResultsThrottlingSemaphore should be present in cmdlet mode"); Interlocked.Decrement(ref _throttlingJob._jobResultsCurrentCount); _throttlingJob._jobResultsThrottlingSemaphore.Release(); } @@ -1236,7 +1236,7 @@ public static void ForwardAllResultsToCmdlet(ThrottlingJob throttlingJob, Cmdlet } finally { - if (cancellationTokenRegistration != null) + if (cancellationTokenRegistration is not null) { cancellationTokenRegistration.Dispose(); } @@ -1275,7 +1275,7 @@ internal class ThrottlingJobChildAddedEventArgs : EventArgs internal ThrottlingJobChildAddedEventArgs(Job addedChildJob) { - Dbg.Assert(addedChildJob != null, "Caller should verify addedChildJob != null"); + Dbg.Assert(addedChildJob is not null, "Caller should verify addedChildJob is not null"); AddedChildJob = addedChildJob; } } diff --git a/src/System.Management.Automation/engine/remoting/client/clientremotesession.cs b/src/System.Management.Automation/engine/remoting/client/clientremotesession.cs index 5bc2d7ffefa..6e2f063f241 100644 --- a/src/System.Management.Automation/engine/remoting/client/clientremotesession.cs +++ b/src/System.Management.Automation/engine/remoting/client/clientremotesession.cs @@ -162,7 +162,7 @@ internal RemoteRunspacePoolInternal RemoteRunspacePoolInternal /// internal RemoteRunspacePoolInternal GetRunspacePool(Guid clientRunspacePoolId) { - if (_remoteRunspacePool != null) + if (_remoteRunspacePool is not null) { if (_remoteRunspacePool.InstanceId.Equals(clientRunspacePoolId)) return _remoteRunspacePool; @@ -195,7 +195,7 @@ internal class ClientRemoteSessionImpl : ClientRemoteSession, IDisposable internal ClientRemoteSessionImpl(RemoteRunspacePoolInternal rsPool, URIDirectionReported uriRedirectionHandler) { - Dbg.Assert(rsPool != null, "RunspacePool cannot be null"); + Dbg.Assert(rsPool is not null, "RunspacePool cannot be null"); base.RemoteRunspacePoolInternal = rsPool; Context.RemoteAddress = WSManConnectionInfo.ExtractPropertyAsWsManConnectionInfo(rsPool.ConnectionInfo, "ConnectionUri", null); @@ -498,7 +498,7 @@ private void HandleNegotiationReceived(object sender, RemoteSessionNegotiationEv /// private bool RunClientNegotiationAlgorithm(RemoteSessionCapability serverRemoteSessionCapability) { - Dbg.Assert(serverRemoteSessionCapability != null, "server capability cache must be non-null"); + Dbg.Assert(serverRemoteSessionCapability is not null, "server capability cache must be non-null"); // ProtocolVersion check Version serverProtocolVersion = serverRemoteSessionCapability.ProtocolVersion; @@ -588,7 +588,7 @@ public void Dispose(bool disposing) { if (disposing) { - if (_waitHandleForConfigurationReceived != null) + if (_waitHandleForConfigurationReceived is not null) { _waitHandleForConfigurationReceived.Dispose(); _waitHandleForConfigurationReceived = null; diff --git a/src/System.Management.Automation/engine/remoting/client/clientremotesessionprotocolstatemachine.cs b/src/System.Management.Automation/engine/remoting/client/clientremotesessionprotocolstatemachine.cs index 9e56f65f203..f0b7d2b02ef 100644 --- a/src/System.Management.Automation/engine/remoting/client/clientremotesessionprotocolstatemachine.cs +++ b/src/System.Management.Automation/engine/remoting/client/clientremotesessionprotocolstatemachine.cs @@ -186,7 +186,7 @@ private void SetStateHandler(object sender, RemoteSessionStateMachineEventArgs e case RemoteSessionEvent.NegotiationReceived: { - Dbg.Assert(eventArgs.RemoteSessionCapability != null, + Dbg.Assert(eventArgs.RemoteSessionCapability is not null, "State can be set to NegotiationReceived only when RemoteSessionCapability is not null"); if (eventArgs.RemoteSessionCapability is null) { @@ -253,7 +253,7 @@ private void SetStateHandler(object sender, RemoteSessionStateMachineEventArgs e if (_state == RemoteSessionState.EstablishedAndKeySent) { Timer tmp = Interlocked.Exchange(ref _keyExchangeTimer, null); - if (tmp != null) + if (tmp is not null) { tmp.Dispose(); } @@ -338,7 +338,7 @@ private void HandleKeyExchangeTimeout(object sender) Dbg.Assert(_state == RemoteSessionState.EstablishedAndKeySent, "timeout should only happen when waiting for a key"); Timer tmp = Interlocked.Exchange(ref _keyExchangeTimer, null); - if (tmp != null) + if (tmp is not null) { tmp.Dispose(); } @@ -558,7 +558,7 @@ private void RaiseEventPrivate(RemoteSessionStateMachineEventArgs arg) } EventHandler handler = _stateMachineHandle[(int)State, (int)arg.StateEvent]; - if (handler != null) + if (handler is not null) { s_trace.WriteLine("Before calling state machine event handler: state = {0}, event = {1}, id = {2}", State, arg.StateEvent, _id); diff --git a/src/System.Management.Automation/engine/remoting/client/remotepipeline.cs b/src/System.Management.Automation/engine/remoting/client/remotepipeline.cs index 56a2c88f60f..bde15df9763 100644 --- a/src/System.Management.Automation/engine/remoting/client/remotepipeline.cs +++ b/src/System.Management.Automation/engine/remoting/client/remotepipeline.cs @@ -115,7 +115,7 @@ private RemotePipeline(RemoteRunspace runspace, bool addToHistory, bool isNested internal RemotePipeline(RemoteRunspace runspace, string command, bool addToHistory, bool isNested) : this(runspace, addToHistory, isNested) { - if (command != null) + if (command is not null) { _commands.Add(new Command(command, true)); } @@ -487,7 +487,7 @@ public override Collection Connect() // collect output in. Check to see if the output was collected in a member variable. if (results.Count == 0) { - if (_outputCollection != null && _outputCollection.Count > 0) + if (_outputCollection is not null && _outputCollection.Count > 0) { results = new Collection(_outputCollection); } @@ -533,7 +533,7 @@ public override void Stop() if (CanStopPipeline(out isAlreadyStopping)) { // A pipeline can be stopped before it is started.so protecting against that - if (_powershell != null) + if (_powershell is not null) { IAsyncResult asyncresult = null; try @@ -663,7 +663,7 @@ protected override void Dispose(bool disposing) Stop(); // _pipelineFinishedEvent.Close(); - if (_powershell != null) + if (_powershell is not null) { _powershell.Dispose(); _powershell = null; @@ -777,7 +777,7 @@ private void SetPipelineState(PipelineState state, Exception reason) // to change pipeline state. RunspaceAvailability previousAvailability = _runspace.RunspaceAvailability; - Guid? cmdInstanceId = (_powershell != null) ? _powershell.InstanceId : (Guid?)null; + Guid? cmdInstanceId = (_powershell is not null) ? _powershell.InstanceId : (Guid?)null; _runspace.UpdateRunspaceAvailability(_pipelineStateInfo.State, false, cmdInstanceId); _executionEventQueue.Enqueue( @@ -814,7 +814,7 @@ protected void RaisePipelineStateEvents() stateChanged = this.StateChanged; runspaceHasAvailabilityChangedSubscribers = _runspace.HasAvailabilityChangedSubscribers; - if (stateChanged != null || runspaceHasAvailabilityChangedSubscribers) + if (stateChanged is not null || runspaceHasAvailabilityChangedSubscribers) { tempEventQueue = _executionEventQueue; _executionEventQueue = new Queue(); @@ -828,7 +828,7 @@ protected void RaisePipelineStateEvents() } } - if (tempEventQueue != null) + if (tempEventQueue is not null) { while (tempEventQueue.Count > 0) { @@ -841,7 +841,7 @@ protected void RaisePipelineStateEvents() // Exception raised in the eventhandler are not error in pipeline. // silently ignore them. - if (stateChanged != null) + if (stateChanged is not null) { try { @@ -1060,8 +1060,8 @@ internal void DoConcurrentCheck(bool syncCall) } if (currentPipeline is null && - ((RemoteRunspace)_runspace).RemoteCommand != null && - _connectCmdInfo != null && + ((RemoteRunspace)_runspace).RemoteCommand is not null && + _connectCmdInfo is not null && Guid.Equals(((RemoteRunspace)_runspace).RemoteCommand.CommandId, _connectCmdInfo.CommandId)) { // Connect case. We can add a pipeline to a busy runspace when @@ -1070,7 +1070,7 @@ internal void DoConcurrentCheck(bool syncCall) return; } - if (currentPipeline != null && + if (currentPipeline is not null && ReferenceEquals(currentPipeline, this)) { // Reconnect case. We can add a pipeline to a busy runspace when the diff --git a/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs b/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs index 31f633c9b50..e9e3793828c 100644 --- a/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs +++ b/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs @@ -334,7 +334,7 @@ public override RunspaceAvailability RunspaceAvailability /// internal override bool HasAvailabilityChangedSubscribers { - get { return this.AvailabilityChanged != null; } + get { return this.AvailabilityChanged is not null; } } /// @@ -344,7 +344,7 @@ protected override void OnAvailabilityChanged(RunspaceAvailabilityEventArgs e) { EventHandler eh = this.AvailabilityChanged; - if (eh != null) + if (eh is not null) { try { @@ -592,7 +592,7 @@ public override void Close() // It is possible for the result ASyncResult object to be null if the runspace // pool is already being closed from a server initiated close event. - if (result != null) + if (result is not null) { RunspacePool.EndClose(result); } @@ -642,7 +642,7 @@ protected override void Dispose(bool disposing) // } - if (_remoteDebugger != null) + if (_remoteDebugger is not null) { // Release RunspacePool event forwarding handlers. _remoteDebugger.Dispose(); @@ -709,7 +709,7 @@ public override void ResetRunspaceState() } } - if (invalidOperation != null) + if (invalidOperation is not null) { invalidOperation.Source = "ResetRunspaceState"; throw invalidOperation; @@ -962,7 +962,7 @@ public override RunspaceCapability GetCapabilities() { ContainerConnectionInfo containerConnectionInfo = _connectionInfo as ContainerConnectionInfo; - if ((containerConnectionInfo != null) && + if ((containerConnectionInfo is not null) && (containerConnectionInfo.ContainerProc.RuntimeId == Guid.Empty)) { returnCaps |= RunspaceCapability.NamedPipeTransport; @@ -981,8 +981,8 @@ private void UpdatePoolDisconnectOptions() WSManConnectionInfo runspaceWSManConnectionInfo = RunspacePool.ConnectionInfo as WSManConnectionInfo; WSManConnectionInfo wsManConnectionInfo = ConnectionInfo as WSManConnectionInfo; - Dbg.Assert(runspaceWSManConnectionInfo != null, "Disconnect-Connect feature is currently only supported for WSMan transport"); - Dbg.Assert(wsManConnectionInfo != null, "Disconnect-Connect feature is currently only supported for WSMan transport"); + Dbg.Assert(runspaceWSManConnectionInfo is not null, "Disconnect-Connect feature is currently only supported for WSMan transport"); + Dbg.Assert(wsManConnectionInfo is not null, "Disconnect-Connect feature is currently only supported for WSMan transport"); runspaceWSManConnectionInfo.IdleTimeout = wsManConnectionInfo.IdleTimeout; runspaceWSManConnectionInfo.OutputBufferingMode = wsManConnectionInfo.OutputBufferingMode; @@ -1109,7 +1109,7 @@ public override Pipeline CreateNestedPipeline(string command, bool addToHistory) /// internal void AddToRunningPipelineList(RemotePipeline pipeline) { - Dbg.Assert(pipeline != null, "caller should validate the parameter"); + Dbg.Assert(pipeline is not null, "caller should validate the parameter"); lock (_syncRoot) { @@ -1126,7 +1126,7 @@ internal void AddToRunningPipelineList(RemotePipeline pipeline) _runspaceStateInfo.State, RunspaceState.Opened ); - if (this.ConnectionInfo != null) + if (this.ConnectionInfo is not null) { e.Source = this.ConnectionInfo.ComputerName; } @@ -1151,7 +1151,7 @@ internal void AddToRunningPipelineList(RemotePipeline pipeline) /// internal void RemoveFromRunningPipelineList(RemotePipeline pipeline) { - Dbg.Assert(pipeline != null, "caller should validate the parameter"); + Dbg.Assert(pipeline is not null, "caller should validate the parameter"); lock (_syncRoot) { @@ -1270,9 +1270,9 @@ private void SetDebugModeOnOpen() { IHostSupportsInteractiveSession interactiveHost = RunspacePool.RemoteRunspacePoolInternal.Host as IHostSupportsInteractiveSession; - if (interactiveHost != null && - interactiveHost.Runspace != null && - interactiveHost.Runspace.Debugger != null) + if (interactiveHost is not null && + interactiveHost.Runspace is not null && + interactiveHost.Runspace.Debugger is not null) { hostDebugMode = interactiveHost.Runspace.Debugger.DebugMode; } @@ -1299,7 +1299,7 @@ private bool SetDebugInfo(PSPrimitiveDictionary psApplicationPrivateData) bool breakAll = false; UnhandledBreakpointProcessingMode unhandledBreakpointMode = UnhandledBreakpointProcessingMode.Ignore; - if (psApplicationPrivateData != null) + if (psApplicationPrivateData is not null) { if (psApplicationPrivateData.ContainsKey(RemoteDebugger.DebugModeSetting)) { @@ -1336,7 +1336,7 @@ private bool SetDebugInfo(PSPrimitiveDictionary psApplicationPrivateData) } } - if (debugMode != null) + if (debugMode is not null) { // Server supports remote debugging. Create Debugger object for // this remote runspace. @@ -1439,7 +1439,7 @@ private void RaiseRunspaceStateEvents() stateChanged = this.StateChanged; hasAvailabilityChangedSubscribers = this.HasAvailabilityChangedSubscribers; - if (stateChanged != null || hasAvailabilityChangedSubscribers) + if (stateChanged is not null || hasAvailabilityChangedSubscribers) { tempEventQueue = _runspaceEventQueue; _runspaceEventQueue = new Queue(); @@ -1453,7 +1453,7 @@ private void RaiseRunspaceStateEvents() } } - if (tempEventQueue != null) + if (tempEventQueue is not null) { while (tempEventQueue.Count > 0) { @@ -1466,7 +1466,7 @@ private void RaiseRunspaceStateEvents() // Exception raised by events are not error condition for runspace // object. - if (stateChanged != null) + if (stateChanged is not null) { try { @@ -1577,7 +1577,7 @@ private void HandleHostCallReceived(object sender, RemoteDataEventArgs eventArgs) { WSManConnectionInfo wsmanConnectionInfo = _connectionInfo as WSManConnectionInfo; - if (wsmanConnectionInfo != null) + if (wsmanConnectionInfo is not null) { // change the runspace's uri to the new URI. wsmanConnectionInfo.ConnectionUri = eventArgs.Data; @@ -1614,12 +1614,12 @@ private void HandleRunspacePoolForwardEvent(object sender, PSEventArgs e) private void HandleSessionCreateCompleted(object sender, CreateCompleteEventArgs eventArgs) { // Update connectionInfo with updated information from the transport. - if (eventArgs != null) + if (eventArgs is not null) { _connectionInfo.IdleTimeout = eventArgs.ConnectionInfo.IdleTimeout; _connectionInfo.MaxIdleTimeout = eventArgs.ConnectionInfo.MaxIdleTimeout; WSManConnectionInfo wsmanConnectionInfo = _connectionInfo as WSManConnectionInfo; - if (wsmanConnectionInfo != null) + if (wsmanConnectionInfo is not null) { wsmanConnectionInfo.OutputBufferingMode = ((WSManConnectionInfo)eventArgs.ConnectionInfo).OutputBufferingMode; @@ -1633,7 +1633,7 @@ private void HandleSessionCreateCompleted(object sender, CreateCompleteEventArgs private void UpdateDisconnectExpiresOn() { WSManConnectionInfo wsmanConnectionInfo = RunspacePool.RemoteRunspacePoolInternal.ConnectionInfo as WSManConnectionInfo; - if (wsmanConnectionInfo != null) + if (wsmanConnectionInfo is not null) { this.DisconnectedOn = wsmanConnectionInfo.DisconnectedOn; this.ExpiresOn = wsmanConnectionInfo.ExpiresOn; @@ -1704,7 +1704,7 @@ internal bool IsAnotherInvokeCommandExecuting(InvokeCommandCommand invokeCommand internal void SetCurrentInvokeCommand(InvokeCommandCommand invokeCommand, long localPipelineId) { - Dbg.Assert(invokeCommand != null, "InvokeCommand instance cannot be null, use ClearInvokeCommand() method to reset current command"); + Dbg.Assert(invokeCommand is not null, "InvokeCommand instance cannot be null, use ClearInvokeCommand() method to reset current command"); Dbg.Assert(localPipelineId != 0, "Local pipeline id needs to be supplied - cannot be 0"); _currentInvokeCommand = invokeCommand; @@ -1731,7 +1731,7 @@ internal void AbortOpen() System.Management.Automation.Remoting.Client.NamedPipeClientSessionTransportManager transportManager = RunspacePool.RemoteRunspacePoolInternal.DataStructureHandler.TransportManager as System.Management.Automation.Remoting.Client.NamedPipeClientSessionTransportManager; - if (transportManager != null) + if (transportManager is not null) { transportManager.AbortConnect(); } @@ -1908,9 +1908,9 @@ public override DebuggerCommandResults ProcessCommand(PSCommand command, PSDataC if (item is null) { return; } DebuggerCommand dbgCmd = item.BaseObject as DebuggerCommand; - if (dbgCmd != null) + if (dbgCmd is not null) { - bool executedByDebugger = (dbgCmd.ResumeAction != null || dbgCmd.ExecutedByDebugger); + bool executedByDebugger = (dbgCmd.ResumeAction is not null || dbgCmd.ExecutedByDebugger); results = new DebuggerCommandResults(dbgCmd.ResumeAction, executedByDebugger); } else if (item.BaseObject is DebuggerCommandResults) @@ -1932,14 +1932,14 @@ public override DebuggerCommandResults ProcessCommand(PSCommand command, PSDataC { executionError = true; RemoteException re = e as RemoteException; - if ((re != null) && (re.ErrorRecord != null)) + if ((re is not null) && (re.ErrorRecord is not null)) { // Allow the IncompleteParseException to throw so that the console // can handle here strings and continued parsing. if (re.ErrorRecord.CategoryInfo.Reason == typeof(IncompleteParseException).Name) { throw new IncompleteParseException( - (re.ErrorRecord.Exception != null) ? re.ErrorRecord.Exception.Message : null, + (re.ErrorRecord.Exception is not null) ? re.ErrorRecord.Exception.Message : null, re.ErrorRecord.FullyQualifiedErrorId); } @@ -1949,7 +1949,7 @@ public override DebuggerCommandResults ProcessCommand(PSCommand command, PSDataC (re.ErrorRecord.CategoryInfo.Reason == typeof(RemoteException).Name)) { throw new PSRemotingTransportException( - (re.ErrorRecord.Exception != null) ? re.ErrorRecord.Exception.Message : string.Empty); + (re.ErrorRecord.Exception is not null) ? re.ErrorRecord.Exception.Message : string.Empty); } } @@ -1987,7 +1987,7 @@ public override void StopProcessCommand() CheckForValidateState(); PowerShell ps = _psDebuggerCommand; - if ((ps != null) && + if ((ps is not null) && (ps.InvocationStateInfo.State == PSInvocationState.Running)) { ps.BeginStop(null, null); @@ -2272,7 +2272,7 @@ public override void SetDebuggerAction(DebuggerResumeAction resumeAction) if (ps.ErrorBuffer.Count > 0) { Exception e = ps.ErrorBuffer[0].Exception; - if (e != null) { throw e; } + if (e is not null) { throw e; } } } } @@ -2298,7 +2298,7 @@ public override DebuggerStopEventArgs GetDebuggerStopArgs() if (item is null) { continue; } rtnArgs = item.BaseObject as DebuggerStopEventArgs; - if (rtnArgs != null) { break; } + if (rtnArgs is not null) { break; } } } } @@ -2319,8 +2319,8 @@ public override void SetDebugMode(DebugModes mode) // Only set debug mode on server if no commands are currently // running on remote runspace. - if ((_runspace.GetCurrentlyRunningPipeline() != null) || - (_runspace.RemoteCommand != null)) + if ((_runspace.GetCurrentlyRunningPipeline() is not null) || + (_runspace.RemoteCommand is not null)) { return; } @@ -2458,7 +2458,7 @@ public void Dispose() _runspace.RemoteDebuggerBreakpointUpdated -= HandleForwardedDebuggerBreakpointUpdatedEvent; #if !UNIX - if (_identityToPersonate != null) + if (_identityToPersonate is not null) { _identityToPersonate.Dispose(); _identityToPersonate = null; @@ -2480,7 +2480,7 @@ public void Dispose() internal void CheckStateAndRaiseStopEvent() { DebuggerStopEventArgs stopArgs = GetDebuggerStopArgs(); - if (stopArgs != null) + if (stopArgs is not null) { ProcessDebuggerStopEvent(stopArgs); } @@ -2512,7 +2512,7 @@ internal void SetClientDebugInfo( UnhandledBreakpointProcessingMode unhandledBreakpointMode, Version serverPSVersion) { - if (debugMode != null) + if (debugMode is not null) { _remoteDebugSupported = true; DebugMode = debugMode.Value; @@ -2578,7 +2578,7 @@ internal void SendBreakpointUpdatedEvents() foreach (PSObject obj in breakpoints) { Breakpoint breakpoint = obj.BaseObject as Breakpoint; - if (breakpoint != null) + if (breakpoint is not null) { RaiseBreakpointUpdatedEvent( new BreakpointUpdatedEventArgs(breakpoint, BreakpointUpdateType.Set, _breakpointCount)); @@ -2660,10 +2660,10 @@ private void ProcessDebuggerStopEvent(DebuggerStopEventArgs args) // Attempt to process debugger stop event on original thread if it // is available (i.e., if it is blocked by EndInvoke). PowerShell powershell = _runspace.RunspacePool.RemoteRunspacePoolInternal.GetCurrentRunningPowerShell(); - AsyncResult invokeAsyncResult = (powershell != null) ? powershell.EndInvokeAsyncResult : null; + AsyncResult invokeAsyncResult = (powershell is not null) ? powershell.EndInvokeAsyncResult : null; bool invokedOnBlockedThread = false; - if ((invokeAsyncResult != null) && (!invokeAsyncResult.IsCompleted)) + if ((invokeAsyncResult is not null) && (!invokeAsyncResult.IsCompleted)) { invokedOnBlockedThread = invokeAsyncResult.InvokeCallbackOnThread( ProcessDebuggerStopEventProc, @@ -2701,7 +2701,7 @@ private void ProcessDebuggerStopEventProc(object state) // Raise event and wait for response. DebuggerStopEventArgs args = state as DebuggerStopEventArgs; - if (args != null) + if (args is not null) { if (IsDebuggerStopEventSubscribed()) { @@ -2763,7 +2763,7 @@ private void HandleForwardedDebuggerBreakpointUpdatedEvent(object sender, PSEven Dbg.Assert(e.SourceArgs.Length == 1, "Forwarded debugger breakpoint event args must always contain one SourceArgs item."); BreakpointUpdatedEventArgs bpArgs = e.SourceArgs[0] as BreakpointUpdatedEventArgs; - if (bpArgs != null) + if (bpArgs is not null) { UpdateBreakpointCount(bpArgs.BreakpointCount); base.RaiseBreakpointUpdatedEvent(bpArgs); @@ -2822,7 +2822,7 @@ private void SetRemoteDebug(bool remoteDebug, RunspaceAvailability? availability _runspace.RunspacePool.RemoteRunspacePoolInternal.IsRemoteDebugStop = remoteDebug; } - if (availability != null) + if (availability is not null) { RunspaceAvailability newAvailability = availability.Value; @@ -2884,7 +2884,7 @@ private T InvokeRemoteBreakpointFunction(string functionName, Dictionary 0) { Exception e = ps.ErrorBuffer[0].Exception; - if (e != null) + if (e is not null) { throw e; } @@ -2937,7 +2937,7 @@ internal class RemoteSessionStateProxy : SessionStateProxy internal RemoteSessionStateProxy(RemoteRunspace runspace) { - Dbg.Assert(runspace != null, "Caller should validate the parameter"); + Dbg.Assert(runspace is not null, "Caller should validate the parameter"); _runspace = runspace; } @@ -2972,7 +2972,7 @@ public override void SetVariable(string name, object value) // Verify the runspace has the Set-Variable command. For performance, throw if we got an error // before. - if (_setVariableCommandNotFoundException != null) + if (_setVariableCommandNotFoundException is not null) throw _setVariableCommandNotFoundException; // Since these are implemented as pipelines, we don't need to do our own @@ -3032,7 +3032,7 @@ public override object GetVariable(string name) // Verify the runspace has the Get-Variable command. For performance, throw if we got an error // before. - if (_getVariableCommandNotFoundException != null) + if (_getVariableCommandNotFoundException is not null) throw _getVariableCommandNotFoundException; // Since these are implemented as pipelines, we don't need to do our own @@ -3092,7 +3092,7 @@ public override List Applications { // Verify the runspace has is not in NoLanguage mode. For performance, throw if we got an error // before. - if (_isInNoLanguageModeException != null) + if (_isInNoLanguageModeException is not null) throw _isInNoLanguageModeException; // Since these are implemented as pipelines, we don't need to do our own @@ -3137,7 +3137,7 @@ public override List Scripts { // Verify the runspace has is not in NoLanguage mode. For performance, throw if we got an error // before. - if (_isInNoLanguageModeException != null) + if (_isInNoLanguageModeException is not null) throw _isInNoLanguageModeException; // Since these are implemented as pipelines, we don't need to do our own @@ -3199,7 +3199,7 @@ public override PSLanguageMode LanguageMode { // Verify the runspace has is not in NoLanguage mode. For performance, return our // cached value if we got an error before. - if (_isInNoLanguageModeException != null) + if (_isInNoLanguageModeException is not null) return PSLanguageMode.NoLanguage; // Since these are implemented as pipelines, we don't need to do our own diff --git a/src/System.Management.Automation/engine/remoting/client/remotingprotocolimplementation.cs b/src/System.Management.Automation/engine/remoting/client/remotingprotocolimplementation.cs index 70b97784a3f..7b1826b903a 100644 --- a/src/System.Management.Automation/engine/remoting/client/remotingprotocolimplementation.cs +++ b/src/System.Management.Automation/engine/remoting/client/remotingprotocolimplementation.cs @@ -94,7 +94,7 @@ internal ClientRemoteSessionDSHandlerImpl(ClientRemoteSession session, _transportManager.RobustConnectionNotification += HandleRobustConnectionNotification; WSManConnectionInfo wsmanConnectionInfo = _connectionInfo as WSManConnectionInfo; - if (wsmanConnectionInfo != null) + if (wsmanConnectionInfo is not null) { // only WSMan transport supports redirection @@ -182,7 +182,7 @@ private void HandleRobustConnectionNotification(object sender, ConnectionStatusE break; } - if (eventArgument != null) + if (eventArgument is not null) { StateMachine.RaiseEvent(eventArgument); } @@ -301,7 +301,7 @@ private void HandleStateChanged(object sender, RemoteSessionStateEventArgs arg) if (arg.SessionStateInfo.State == RemoteSessionState.Established) { WSManClientSessionTransportManager tm = _transportManager as WSManClientSessionTransportManager; - if (tm != null) + if (tm is not null) { tm.AdjustForProtocolVariations(_session.ServerProtocolVersion); tm.StartReceivingData(); @@ -434,7 +434,7 @@ private void HandleTransportErrorForRedirection(object sender, TransportErrorOcc /// private void PerformURIRedirectionStep2(System.Uri newURI) { - Dbg.Assert(newURI != null, "Uri cannot be null"); + Dbg.Assert(newURI is not null, "Uri cannot be null"); lock (_syncObject) { // if connection is closed by the user..no need to redirect @@ -444,7 +444,7 @@ private void PerformURIRedirectionStep2(System.Uri newURI) } // raise warning to report the redirection - if (_uriRedirectionHandler != null) + if (_uriRedirectionHandler is not null) { _uriRedirectionHandler(newURI); } @@ -465,10 +465,10 @@ private void PerformURIRedirectionStep2(System.Uri newURI) /// internal void HandleTransportError(object sender, TransportErrorOccuredEventArgs e) { - Dbg.Assert(e != null, "HandleTransportError expects non-null eventargs"); + Dbg.Assert(e is not null, "HandleTransportError expects non-null eventargs"); // handle uri redirections PSRemotingTransportRedirectException redirectException = e.Exception as PSRemotingTransportRedirectException; - if ((redirectException != null) && (_maxUriRedirectionCount > 0)) + if ((redirectException is not null) && (_maxUriRedirectionCount > 0)) { Exception exception = null; @@ -488,7 +488,7 @@ internal void HandleTransportError(object sender, TransportErrorOccuredEventArgs exception = uriFormatException; } // if we are here, there must be an exception constructing a uri - if (exception != null) + if (exception is not null) { PSRemotingTransportException newException = new PSRemotingTransportException(PSRemotingErrorId.RedirectedURINotWellFormatted, RemotingErrorIdStrings.RedirectedURINotWellFormatted, @@ -705,7 +705,7 @@ internal void ProcessNonSessionMessages(RemoteDataObject rcvdData) clientRunspacePoolId = rcvdData.RunspacePoolId; runspacePool = _session.GetRunspacePool(clientRunspacePoolId); - if (runspacePool != null) + if (runspacePool is not null) { // GETBACK runspacePool.DataStructureHandler.ProcessReceivedData(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..7b46ae9ef69 100644 --- a/src/System.Management.Automation/engine/remoting/commands/ConnectPSSession.cs +++ b/src/System.Management.Automation/engine/remoting/commands/ConnectPSSession.cs @@ -504,10 +504,10 @@ internal override void StartOperation() Exception ex = null; try { - if (_queryRunspaces != null) + if (_queryRunspaces is not null) { PSSession newSession = QueryForSession(_session); - if (newSession != null) + if (newSession is not null) { _session.Runspace.StateChanged -= StateCallBackHandler; _oldSession = _session; @@ -538,7 +538,7 @@ internal override void StartOperation() ex = e; } - if (ex != null) + if (ex is not null) { startedSuccessfully = false; WriteConnectFailed(ex, _session); @@ -554,7 +554,7 @@ internal override void StartOperation() internal override void StopOperation() { - if (_queryRunspaces != null) + if (_queryRunspaces is not null) { _queryRunspaces.StopAllOperations(); } @@ -582,7 +582,7 @@ internal PSSession QueryForSession(PSSession session) ex = e; } - if (ex != null) + if (ex is not null) { WriteConnectFailed(ex, session); return null; @@ -625,7 +625,7 @@ private void StateCallBackHandler(object sender, RunspaceStateEventArgs eArgs) if (_queryRunspaces is null) { PSRemotingTransportException transportException = eArgs.RunspaceStateInfo.Reason as PSRemotingTransportException; - if (transportException != null && + if (transportException is not null && transportException.ErrorCode == WSManNativeApi.ERROR_WSMAN_INUSE_CANNOT_RECONNECT) { lock (s_LockObject) @@ -667,12 +667,12 @@ private void WriteConnectedPSSession() // Use temporary variable because we need to preserve _session class variable // for later clean up. PSSession outSession = _session; - if (_queryRunspaces != null) + if (_queryRunspaces is not null) { lock (s_LockObject) { // Pass back the original session if possible. - if (_oldSession != null && + if (_oldSession is not null && _oldSession.InsertRunspace(_session.Runspace as RemoteRunspace)) { outSession = _oldSession; @@ -707,11 +707,11 @@ private void WriteConnectFailed( { string FQEID = "PSSessionConnectFailed"; Exception reason; - if (e != null && !string.IsNullOrEmpty(e.Message)) + if (e is not null && !string.IsNullOrEmpty(e.Message)) { // Update fully qualified error Id if we have a transport error. PSRemotingTransportException transportException = e as PSRemotingTransportException; - if (transportException != null) + if (transportException is not null) { FQEID = WSManTransportManagerUtils.GetFQEIDFromTransportError(transportException.ErrorCode, FQEID); } @@ -797,7 +797,7 @@ private Collection CollectDisconnectedSessions(OverrideParameter over // Get all remote runspaces to disconnect. if (ParameterSetName == DisconnectPSSessionCommand.SessionParameterSet) { - if (Session != null) + if (Session is not null) { foreach (PSSession psSession in Session) { @@ -824,7 +824,7 @@ private Collection CollectDisconnectedSessions(OverrideParameter over break; } - if (entries != null) + if (entries is not null) { foreach (PSSession psSession in entries.Values) { @@ -934,7 +934,7 @@ private Collection GetConnectionObjects() connectionInfo.AppName = ApplicationName; connectionInfo.ShellUri = ConfigurationName; connectionInfo.Port = Port; - if (CertificateThumbprint != null) + if (CertificateThumbprint is not null) { connectionInfo.CertificateThumbprint = CertificateThumbprint; } @@ -957,7 +957,7 @@ private Collection GetConnectionObjects() WSManConnectionInfo connectionInfo = new WSManConnectionInfo(); connectionInfo.ConnectionUri = connectionUri; connectionInfo.ShellUri = ConfigurationName; - if (CertificateThumbprint != null) + if (CertificateThumbprint is not null) { connectionInfo.CertificateThumbprint = CertificateThumbprint; } @@ -996,7 +996,7 @@ private void UpdateConnectionInfo(WSManConnectionInfo connectionInfo) } // Update the connectionInfo object with passed in session options. - if (SessionOption != null) + if (SessionOption is not null) { connectionInfo.SetSessionOptions(SessionOption); } diff --git a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs index 602e7e429af..60e6da33c0b 100644 --- a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs +++ b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs @@ -461,9 +461,9 @@ protected override void BeginProcessing() WSManConfigurationOption wsmanOption = transportOption as WSManConfigurationOption; - if (wsmanOption != null) + if (wsmanOption is not null) { - if (wsmanOption.ProcessIdleTimeoutSec != null && !isUseSharedProcessSpecified) + if (wsmanOption.ProcessIdleTimeoutSec is not null && !isUseSharedProcessSpecified) { PSInvalidOperationException ioe = new PSInvalidOperationException( StringUtil.Format(RemotingErrorIdStrings.InvalidConfigurationXMLAttribute, "ProcessIdleTimeoutSec", @@ -564,9 +564,9 @@ protected override void ProcessRecord() int errorCountBefore = errorList.Count; if (force && - this.Context != null && - this.Context.EngineHostInterface != null && - this.Context.EngineHostInterface.ExternalHost != null && + this.Context is not null && + this.Context.EngineHostInterface is not null && + this.Context.EngineHostInterface.ExternalHost is not null && this.Context.EngineHostInterface.ExternalHost is System.Management.Automation.Remoting.ServerRemoteHost) { WriteWarning(RemotingErrorIdStrings.WinRMForceRestartWarning); @@ -589,8 +589,8 @@ protected override void ProcessRecord() restartServiceTarget, restartServiceAction, restartWSManRequiredForUI, - runAsCredential != null ? runAsCredential.UserName : null, - runAsCredential != null ? runAsCredential.Password : null, + runAsCredential is not null ? runAsCredential.UserName : null, + runAsCredential is not null ? runAsCredential.Password : null, AccessMode, isSddlSpecified, _configTableSDDL, @@ -607,7 +607,7 @@ protected override void ProcessRecord() // If the file no longer exists then re-copy the configuration file to the dest location after // newPluginSb script is run the file no longer exists. - if ((srcConfigFilePath != null) && (destConfigFilePath != null) && + if ((srcConfigFilePath is not null) && (destConfigFilePath is not null) && !File.Exists(destConfigFilePath)) { try @@ -676,7 +676,7 @@ private void DeleteFile(string tmpFileName) e = nse; } - if (e != null) + if (e is not null) { throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.NcsCannotDeleteFileAfterInstall, tmpFileName, @@ -703,7 +703,7 @@ private string ConstructTemporaryFile(string pluginContent) if (File.Exists(tmpFileName)) { FileInfo destfile = new FileInfo(tmpFileName); - if (destfile != null) + if (destfile is not null) { try { @@ -748,7 +748,7 @@ private string ConstructTemporaryFile(string pluginContent) e = ioe; } - if (e != null) + if (e is not null) { throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.NcsCannotDeleteFile, tmpFileName, @@ -782,7 +782,7 @@ private string ConstructTemporaryFile(string pluginContent) e = dnfe; } - if (e != null) + if (e is not null) { throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.NcsCannotWritePluginContent, tmpFileName, @@ -801,7 +801,7 @@ private string ConstructPluginContent(out string srcConfigFilePath, out string d bool assemblyAndTypeTokensSet = false; // DISC endpoint - if (Path != null) + if (Path is not null) { ProviderInfo provider = null; PSDriveInfo drive; @@ -851,7 +851,7 @@ private string ConstructPluginContent(out string srcConfigFilePath, out string d { try { - if (configTable[ConfigFileConstants.Guid] != null) + if (configTable[ConfigFileConstants.Guid] is not null) { sessionGuid = Guid.Parse(configTable[ConfigFileConstants.Guid].ToString()); } @@ -913,7 +913,7 @@ private string ConstructPluginContent(out string srcConfigFilePath, out string d configTable, AccessMode, out error); - if (error != null) + if (error is not null) { WriteError(error); } @@ -1076,7 +1076,7 @@ private string ConstructPluginContent(out string srcConfigFilePath, out string d psVersion = PSVersionInfo.PSVersion; } - if (psVersion != null) + if (psVersion is not null) { initParameters.Append(string.Format(CultureInfo.InvariantCulture, initParamFormat, @@ -1087,7 +1087,7 @@ private string ConstructPluginContent(out string srcConfigFilePath, out string d // Calculate MaxPSVersion from PSVersion MaxPSVersion = PSSessionConfigurationCommandUtilities.CalculateMaxPSVersion(psVersion); - if (MaxPSVersion != null) + if (MaxPSVersion is not null) { initParameters.Append(string.Format(CultureInfo.InvariantCulture, initParamFormat, @@ -1165,7 +1165,7 @@ private string ConstructPluginContent(out string srcConfigFilePath, out string d StringBuilder sessionConfigurationData = new StringBuilder(); - if (modulesToImport != null && modulesToImport.Length > 0) + if (modulesToImport is not null && modulesToImport.Length > 0) { sessionConfigurationData.Append(string.Format(CultureInfo.InvariantCulture, initParamFormat, @@ -1174,7 +1174,7 @@ private string ConstructPluginContent(out string srcConfigFilePath, out string d string.Empty)); } - if (sessionTypeOption != null) + if (sessionTypeOption is not null) { // TODO: This should probably be a terminating exception for Win8 string privateData = this.sessionTypeOption.ConstructPrivateData(); @@ -1332,7 +1332,7 @@ internal static void CollectShouldProcessParameters(PSCmdlet cmdlet, out bool wh // confirm is always true to start with confirm = false; MshCommandRuntime cmdRuntime = cmdlet.CommandRuntime as MshCommandRuntime; - if (cmdRuntime != null) + if (cmdRuntime is not null) { whatIf = cmdRuntime.WhatIf; // take the value of confirm only if it is explicitly set by the user @@ -1395,7 +1395,7 @@ internal static PSCredential CreateGMSAAccountCredentials(string gmsaAccount) internal static Version CalculateMaxPSVersion(Version psVersion) { Version maxPSVersion = null; - if (psVersion != null && psVersion.Major == 2) + if (psVersion is not null && psVersion.Major == 2) { maxPSVersion = new Version(2, 0); } @@ -1408,13 +1408,13 @@ internal static Version CalculateMaxPSVersion(Version psVersion) /// internal static string GetModulePathAsString(object[] modulePath) { - if (modulePath != null && modulePath.Length > 0) + if (modulePath is not null && modulePath.Length > 0) { StringBuilder sb = new StringBuilder(); foreach (object s in modulePath) { var module = s as string; - if (module != null) + if (module is not null) { sb.Append(s); sb.Append(','); @@ -1422,7 +1422,7 @@ internal static string GetModulePathAsString(object[] modulePath) else { var moduleSpec = s as ModuleSpecification; - if (moduleSpec != null) + if (moduleSpec is not null) { // Double escaping on ModuleSpecification string is required to treat it as a single value along with module names/paths in SessionConfigurationData sb.Append(SecurityElement.Escape(SecurityElement.Escape(moduleSpec.ToString()))); @@ -1445,7 +1445,7 @@ internal static string GetModulePathAsString(object[] modulePath) internal static Version ConstructVersionFormatForConfigXml(Version psVersion) { Version result = null; - if (psVersion != null) + if (psVersion is not null) { result = new Version(psVersion.Major, psVersion.Minor); } @@ -1504,7 +1504,7 @@ internal static string ComputeSDDLFromConfiguration( PSSessionConfigurationAccessMode accessMode, out ErrorRecord error) { - Dbg.Assert(configTable != null, "configTable input parameter cannot be null."); + Dbg.Assert(configTable is not null, "configTable input parameter cannot be null."); string sddl = string.Empty; error = null; @@ -1562,7 +1562,7 @@ internal static string ComputeSDDLFromConfiguration( // RequiredGroups string conditionalGroupACE = CreateConditionalACEFromConfig(configTable); - if (conditionalGroupACE != null) + if (conditionalGroupACE is not null) { sddl = UpdateSDDLUsersWithGroupConditional(sddl, conditionalGroupACE); } @@ -1817,7 +1817,7 @@ private static void ParseKeyValue( // @{ Or = 'Group1', @{ And = 'Group2','Group3' } } // (Member_of {SID(Group1)} || (Member_of {SID(Group2)} && Member_of {SID(Group3)})) object[] values = keyValue as object[]; - if (values != null) + if (values is not null) { int count = values.Length; for (int i = 0; i < count;) @@ -1845,7 +1845,7 @@ private static void ParseValues( { // Value to parse can be a single object or an array of objects object[] values = inValue as object[]; - if (values != null) + if (values is not null) { foreach (object value in values) { @@ -1864,7 +1864,7 @@ private static void ParseValue( { // Single value objects can be either a group name or a new logical hash table string groupName = value as string; - if (groupName != null) + if (groupName is not null) { // Resolve group name to SID NTAccount ntAccount = new NTAccount(groupName); @@ -1874,7 +1874,7 @@ private static void ParseValue( else { Hashtable recurseCondition = value as Hashtable; - if (recurseCondition != null) + if (recurseCondition is not null) { // Recurse to handle logical hash table AddCondition(sb, recurseCondition); @@ -2352,16 +2352,16 @@ public object[] ModulesToImport set { List modulesToImportList = new List(); - if (value != null) + if (value is not null) { foreach (var s in value) { var hashtable = s as Hashtable; - if (hashtable != null) + if (hashtable is not null) { var moduleSpec = new ModuleSpecification(hashtable); - if (moduleSpec != null) + if (moduleSpec is not null) { modulesToImportList.Add(moduleSpec); } @@ -2861,7 +2861,7 @@ protected override void ProcessRecord() string csNotFoundMessageFormat = RemotingErrorIdStrings.CustomShellNotFound; object arguments = "*"; - if (Name != null) + if (Name is not null) { arguments = Name; } @@ -3261,7 +3261,7 @@ protected override void BeginProcessing() } // Populate the configTable hash, and get its SDDL if needed - if (Path != null) + if (Path is not null) { ProviderInfo provider = null; PSDriveInfo drive; @@ -3278,7 +3278,7 @@ protected override void BeginProcessing() _configTable, AccessMode, out error); - if (error != null) + if (error is not null) { WriteError(error); } @@ -3405,7 +3405,7 @@ protected override void ProcessRecord() } // Update the PSSC file if there was one - if (_configTable != null) + if (_configTable is not null) { Guid sessionGuid = Guid.Empty; @@ -3563,7 +3563,7 @@ private void SetVirtualAccount() private void SetQuotas() { - if (this.transportOption != null) + if (this.transportOption is not null) { ScriptBlock setQuotasSb = ScriptBlock.Create( string.Format(CultureInfo.InvariantCulture, setSessionConfigurationQuotaSbFormat, CodeGeneration.EscapeSingleQuotedStringContent(Name))); @@ -3639,7 +3639,7 @@ private void SetOptions() setOptionsSb.LanguageMode = PSLanguageMode.FullLanguage; Hashtable optionsTable - = transportOption != null + = transportOption is not null ? transportOption.ConstructOptionsAsHashtable() : new Hashtable(); @@ -3676,7 +3676,7 @@ Hashtable optionsTable private void SetSessionConfigurationTypeOptions() { - if (sessionTypeOption != null) + if (sessionTypeOption is not null) { using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create()) { @@ -3910,7 +3910,7 @@ private PSObject ConstructPropertiesForUpdate() if (unsetModulePath) { // ModulesToImport exist in the pssessionConfigurationData - if (scd.ModulesToImportInternal != null && scd.ModulesToImportInternal.Count != 0) + if (scd.ModulesToImportInternal is not null && scd.ModulesToImportInternal.Count != 0) { sessionConfigurationData.Append(string.Format(CultureInfo.InvariantCulture, initParamFormat, @@ -3950,7 +3950,7 @@ private PSObject ConstructPropertiesForUpdate() } // DISC endpoint - if (Path != null) + if (Path is not null) { ProviderInfo provider = null; PSDriveInfo drive; @@ -4353,7 +4353,7 @@ protected override void BeginProcessing() /// protected override void ProcessRecord() { - if (Name != null) + if (Name is not null) { foreach (string shell in Name) { @@ -4592,7 +4592,7 @@ protected override void BeginProcessing() /// protected override void ProcessRecord() { - if (Name != null) + if (Name is not null) { foreach (string shell in Name) { @@ -5321,7 +5321,7 @@ protected override void BeginProcessing() { string configFilePath = null; PSPropertyInfo configFilePathProperty = foundConfiguration.Properties["ConfigFilePath"]; - if (configFilePathProperty != null) + if (configFilePathProperty is not null) { configFilePath = configFilePathProperty.Value as string; } diff --git a/src/System.Management.Automation/engine/remoting/commands/DebugJob.cs b/src/System.Management.Automation/engine/remoting/commands/DebugJob.cs index 01f3824c26c..0fee41ee669 100644 --- a/src/System.Management.Automation/engine/remoting/commands/DebugJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/DebugJob.cs @@ -197,14 +197,14 @@ protected override void StopProcessing() { // Cancel job debugging. Debugger debugger = _debugger; - if ((debugger != null) && (_job != null)) + if ((debugger is not null) && (_job is not null)) { debugger.StopDebugJob(_job); } // Unblock the data collection. PSDataCollection debugCollection = _debugCollection; - if (debugCollection != null) + if (debugCollection is not null) { debugCollection.Complete(); } @@ -261,7 +261,7 @@ private void WaitAndReceiveJobOutput() // or this command is cancelled. foreach (var streamItem in _debugCollection) { - if (streamItem != null) + if (streamItem is not null) { streamItem.WriteStreamObject(this); } @@ -298,7 +298,7 @@ private void HandleResultsDataAdding(object sender, DataAddingEventArgs dataAddi if (_debugCollection.IsOpen) { PSStreamObject streamObject = dataAddingArgs.ItemAdded as PSStreamObject; - if (streamObject != null) + if (streamObject is not null) { try { @@ -431,7 +431,7 @@ private Job GetJobById(int id) } if ((jobs1.Count > 1) || - (jobs1.Count == 1) && (job2 != null)) + (jobs1.Count == 1) && (job2 is not null)) { ThrowTerminatingError( new ErrorRecord( @@ -460,7 +460,7 @@ private Job GetJobByInstanceId(Guid instanceId) // Search jobs in job manager. Job2 job2 = JobManager.GetJobByInstanceId(instanceId, this, false, false, false); - if (job2 != null) + if (job2 is not null) { return job2; } diff --git a/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs b/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs index 3099417ac33..615f185bd18 100644 --- a/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs +++ b/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs @@ -223,7 +223,7 @@ protected override void ProcessRecord() if (psSession.Runspace.RunspaceStateInfo.State == RunspaceState.Opened) { // Update the connectionInfo object with passed in session options. - if (_sessionOption != null) + if (_sessionOption is not null) { psSession.Runspace.ConnectionInfo.SetSessionOptions(_sessionOption); } @@ -371,7 +371,7 @@ private string GetLocalhostWithNetworkAccessEnabled(Dictionary { WSManConnectionInfo wsManConnectionInfo = psSession.Runspace.ConnectionInfo as WSManConnectionInfo; - if ((wsManConnectionInfo != null) && (wsManConnectionInfo.IsLocalhostAndNetworkAccess)) + if ((wsManConnectionInfo is not null) && (wsManConnectionInfo.IsLocalhostAndNetworkAccess)) { sb.Append(psSession.Name + ", "); } @@ -495,7 +495,7 @@ private void WriteDisconnectFailed(Exception e = null) { string msg; - if (e != null && !string.IsNullOrWhiteSpace(e.Message)) + if (e is not null && !string.IsNullOrWhiteSpace(e.Message)) { msg = StringUtil.Format(RemotingErrorIdStrings.RunspaceDisconnectFailedWithReason, _remoteSession.InstanceId, e.Message); } diff --git a/src/System.Management.Automation/engine/remoting/commands/EnterPSHostProcessCommand.cs b/src/System.Management.Automation/engine/remoting/commands/EnterPSHostProcessCommand.cs index 6bd3650b0f0..bfb176c18f7 100644 --- a/src/System.Management.Automation/engine/remoting/commands/EnterPSHostProcessCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/EnterPSHostProcessCommand.cs @@ -212,7 +212,7 @@ protected override void EndProcessing() protected override void StopProcessing() { RemoteRunspace connectingRunspace = _connectingRemoteRunspace; - if (connectingRunspace != null) + if (connectingRunspace is not null) { connectingRunspace.AbortOpen(); } @@ -250,9 +250,9 @@ private Runspace CreateNamedPipeRunspace(NamedPipeConnectionInfo connectionInfo) catch (RuntimeException e) { // Unwrap inner exception for original error message, if any. - string errorMessage = (e.InnerException != null) ? (e.InnerException.Message ?? string.Empty) : string.Empty; + string errorMessage = (e.InnerException is not null) ? (e.InnerException.Message ?? string.Empty) : string.Empty; - if (connectionInfo.CustomPipeName != null) + if (connectionInfo.CustomPipeName is not null) { ThrowTerminatingError( new ErrorRecord( @@ -653,7 +653,7 @@ internal static IReadOnlyCollection GetAppDomainNamesFromProc if (int.TryParse(idString, out id)) { // Filter on provided proc Ids. - if (procIds != null) + if (procIds is not null) { bool found = false; foreach (int procId in procIds) diff --git a/src/System.Management.Automation/engine/remoting/commands/GetJob.cs b/src/System.Management.Automation/engine/remoting/commands/GetJob.cs index 17ee25c52cf..fcd33cde4c1 100644 --- a/src/System.Management.Automation/engine/remoting/commands/GetJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/GetJob.cs @@ -110,7 +110,7 @@ protected override void ProcessRecord() { List jobList = FindJobs(); - jobList.Sort((x, y) => x != null ? x.Id.CompareTo(y != null ? y.Id : 1) : -1); + jobList.Sort((x, y) => x is not null ? x.Id.CompareTo(y is not null ? y.Id : 1) : -1); WriteObject(jobList, true); } @@ -144,7 +144,7 @@ protected List FindJobs() case SessionIdParameterSet: { - if (Id != null) + if (Id is not null) { jobList.AddRange(FindJobsMatchingBySessionId(true, false, true, false)); } @@ -244,7 +244,7 @@ private List FindChildJobs(List jobList) { foreach (Job job in jobList) { - if (job.ChildJobs != null && job.ChildJobs.Count > 0) + if (job.ChildJobs is not null && job.ChildJobs.Count > 0) { matches.AddRange(job.ChildJobs); } diff --git a/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs b/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs index 6d62ea7438d..ce6bb7d5189 100644 --- a/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs @@ -862,7 +862,7 @@ protected override void BeginProcessing() { // Check to see if this is a steppable pipeline case. RemoteRunspace remoteRunspace = session.Runspace as RemoteRunspace; - if ((remoteRunspace != null) && + if ((remoteRunspace is not null) && (remoteRunspace.RunspaceAvailability == RunspaceAvailability.Busy) && (remoteRunspace.IsAnotherInvokeCommandExecuting(this, localPipelineId))) { @@ -901,7 +901,7 @@ protected override void BeginProcessing() if (ParameterSetName.Equals(InvokeCommandCommand.InProcParameterSet)) { - if (FilePath != null) + if (FilePath is not null) { ScriptBlock = GetScriptBlockFromFile(FilePath, false); } @@ -972,14 +972,14 @@ protected override void BeginProcessing() // of this bug in Win8 where not responding can occur during data piping. // We are reverting to Win7 behavior for {icm | icm} and {proxycommand | proxycommand} // cases. For ICM | % ICM case, we are using remote steppable pipeline. - if ((MyInvocation != null) && (MyInvocation.PipelinePosition == 1) && (MyInvocation.ExpectingInput == false)) + if ((MyInvocation is not null) && (MyInvocation.PipelinePosition == 1) && (MyInvocation.ExpectingInput == false)) { PSPrimitiveDictionary table = (object)runspaceInfo.ApplicationPrivateData[PSVersionInfo.PSVersionTableName] as PSPrimitiveDictionary; - if (table != null) + if (table is not null) { Version version = (object)table[PSVersionInfo.PSRemotingProtocolVersionName] as Version; - if (version != null) + if (version is not null) { // In order to support foreach remoting properly ( icm | % { icm } ), the server must // be using protocol version 2.2. Otherwise, we skip this and assume the old behavior. @@ -1137,7 +1137,7 @@ protected override void ProcessRecord() { _input.Add(InputObject); } - else if (ParameterSetName.Equals(InvokeCommandCommand.InProcParameterSet) && (_steppablePipeline != null)) + else if (ParameterSetName.Equals(InvokeCommandCommand.InProcParameterSet) && (_steppablePipeline is not null)) { _steppablePipeline.Process(InputObject); } @@ -1170,7 +1170,7 @@ protected override void EndProcessing() { if (ParameterSetName.Equals(InvokeCommandCommand.InProcParameterSet)) { - if (_steppablePipeline != null) + if (_steppablePipeline is not null) { _steppablePipeline.End(); } @@ -1189,7 +1189,7 @@ protected override void EndProcessing() else { // runspace and computername parameter sets - if (_job != null) + if (_job is not null) { // The job/command is disconnected immediately after it is invoked. The command // will continue to run on the server but we don't wait and return immediately. @@ -1289,7 +1289,7 @@ protected override void StopProcessing() { // Ensure that any runspace debug processing is ended var hostDebugger = GetHostDebugger(); - if (hostDebugger != null) + if (hostDebugger is not null) { try { @@ -1309,7 +1309,7 @@ protected override void StopProcessing() bool stopjob = false; lock (_jobSyncObject) { - if (_job != null) + if (_job is not null) { stopjob = true; } @@ -1421,7 +1421,7 @@ private void HandleRunspaceDebugStop(object sender, StartRunspaceDebugProcessing operation.RunspaceDebugStop -= HandleRunspaceDebugStop; var hostDebugger = GetHostDebugger(); - if (hostDebugger != null) + if (hostDebugger is not null) { hostDebugger.QueueRunspaceForDebug(args.Runspace); } @@ -1441,7 +1441,7 @@ private void HandleJobStateChanged(object sender, JobStateEventArgs e) // Signal that this job has been disconnected, or has ended. lock (_jobSyncObject) { - if (_disconnectComplete != null) + if (_disconnectComplete is not null) { _disconnectComplete.Set(); } @@ -1459,7 +1459,7 @@ private void AddConnectionRetryHandler(PSInvokeExpressionSyncJob job) Collection powershells = job.GetPowerShells(); foreach (var ps in powershells) { - if (ps.RemotePowerShell != null) + if (ps.RemotePowerShell is not null) { ps.RemotePowerShell.RCConnectionNotification += RCConnectionNotificationHandler; } @@ -1479,7 +1479,7 @@ private void RemoveConnectionRetryHandler(PSInvokeExpressionSyncJob job) Collection powershells = job.GetPowerShells(); foreach (var ps in powershells) { - if (ps.RemotePowerShell != null) + if (ps.RemotePowerShell is not null) { ps.RemotePowerShell.RCConnectionNotification -= RCConnectionNotificationHandler; } @@ -1509,7 +1509,7 @@ private void RCConnectionNotificationHandler(object sender, PSConnectionRetrySta /// private void WaitForDisconnectAndDisposeJob() { - if (_disconnectComplete != null) + if (_disconnectComplete is not null) { _disconnectComplete.WaitOne(); @@ -1545,13 +1545,13 @@ private List GetDisconnectedSessions(PSInvokeExpressionSyncJob job) foreach (System.Management.Automation.PowerShell ps in powershells) { // Get the command information from the PowerShell object. - string commandText = (ps.Commands != null && ps.Commands.Commands.Count > 0) ? + string commandText = (ps.Commands is not null && ps.Commands.Commands.Count > 0) ? ps.Commands.Commands[0].CommandText : string.Empty; ConnectCommandInfo cmdInfo = new ConnectCommandInfo(ps.InstanceId, commandText); // Get the old RunspacePool object that the command was initially run on. RunspacePool oldRunspacePool = null; - if (ps.RunspacePool != null) + if (ps.RunspacePool is not null) { oldRunspacePool = ps.RunspacePool; } @@ -1559,14 +1559,14 @@ private List GetDisconnectedSessions(PSInvokeExpressionSyncJob job) { object rsConnection = ps.GetRunspaceConnection(); RunspacePool rsPool = rsConnection as RunspacePool; - if (rsPool != null) + if (rsPool is not null) { oldRunspacePool = rsPool; } else { RemoteRunspace remoteRs = rsConnection as RemoteRunspace; - if (remoteRs != null) + if (remoteRs is not null) { oldRunspacePool = remoteRs.RunspacePool; } @@ -1576,7 +1576,7 @@ private List GetDisconnectedSessions(PSInvokeExpressionSyncJob job) // Create a new disconnected PSSession object and return to the user. // The user can use this object to connect to the command on the server // and retrieve data. - if (oldRunspacePool != null) + if (oldRunspacePool is not null) { if (oldRunspacePool.RunspacePoolStateInfo.State != RunspacePoolState.Disconnected) { @@ -1685,7 +1685,7 @@ private void WriteJobResults(bool nonblocking) // ensure that the thread blocks. Else // the thread will spin leading to a CPU // usage spike - if (_disconnectComplete != null) + if (_disconnectComplete is not null) { // An auto-disconnect can occur and we need to detect // this condition along with a job results signal. @@ -1723,7 +1723,7 @@ private void WriteJobResults(bool nonblocking) caughtPipelineStoppedException = pse; } - if (caughtPipelineStoppedException != null) + if (caughtPipelineStoppedException is not null) { HandlePipelinesStopped(); throw caughtPipelineStoppedException; @@ -1737,7 +1737,7 @@ private void WriteJobResults(bool nonblocking) // Create a PSRemoting job we can add to the job repository and that // a user can reconnect to (via Receive-PSSession). PSRemotingJob rtnJob = _job.CreateDisconnectedRemotingJob(); - if (rtnJob != null) + if (rtnJob is not null) { rtnJob.PSJobTypeName = RemoteJobType; @@ -1750,11 +1750,11 @@ private void WriteJobResults(bool nonblocking) foreach (var cjob in rtnJob.ChildJobs) { PSRemotingChildJob childJob = cjob as PSRemotingChildJob; - if (childJob != null) + if (childJob is not null) { // Get session for this job. PSSession session = GetPSSession(childJob.Runspace.InstanceId); - if (session != null) + if (session is not null) { // Write network failed, auto-disconnect error WriteNetworkFailedError(session); @@ -1846,7 +1846,7 @@ private void HandlePipelinesStopped() Collection powershells = _job.GetPowerShells(); foreach (System.Management.Automation.PowerShell ps in powershells) { - if (ps.RemotePowerShell != null && + if (ps.RemotePowerShell is not null && ps.RemotePowerShell.ConnectionRetryStatus != PSConnectionRetryStatus.None && ps.RemotePowerShell.ConnectionRetryStatus != PSConnectionRetryStatus.ConnectionRetrySucceeded && ps.RemotePowerShell.ConnectionRetryStatus != PSConnectionRetryStatus.AutoDisconnectSucceeded) @@ -1857,7 +1857,7 @@ private void HandlePipelinesStopped() } if (retryCanceled && - this.Host != null) + this.Host is not null) { // Write warning directly to host since pipeline has been stopped. this.Host.UI.WriteWarningLine(RemotingErrorIdStrings.StopCommandOnRetry); @@ -1890,7 +1890,7 @@ private void WriteStreamObjectsFromCollection(IEnumerable result { foreach (var result in results) { - if (result != null) + if (result is not null) { PreProcessStreamObject(result); result.WriteStreamObject(this); @@ -1963,12 +1963,12 @@ private void PreProcessStreamObject(PSStreamObject streamObject) // In case of PSDirectException, we should output the precise error message // in inner exception instead of the generic one in outer exception. // - if ((errorRecord != null) && - (errorRecord.Exception != null) && - (errorRecord.Exception.InnerException != null)) + if ((errorRecord is not null) && + (errorRecord.Exception is not null) && + (errorRecord.Exception.InnerException is not null)) { PSDirectException ex = errorRecord.Exception.InnerException as PSDirectException; - if (ex != null) + if (ex is not null) { streamObject.Value = new ErrorRecord(errorRecord.Exception.InnerException, errorRecord.FullyQualifiedErrorId, @@ -2048,7 +2048,7 @@ private void Dispose(bool disposing) if (!_asjob) { - if (_job != null) + if (_job is not null) { // job will be null in the "InProcess" case _job.Dispose(); @@ -2069,7 +2069,7 @@ private void Dispose(bool disposing) lock (_jobSyncObject) { - if (_disconnectComplete != null) + if (_disconnectComplete is not null) { _disconnectComplete.Dispose(); _disconnectComplete = null; diff --git a/src/System.Management.Automation/engine/remoting/commands/JobRepository.cs b/src/System.Management.Automation/engine/remoting/commands/JobRepository.cs index e6d395cb56c..a9e563fb7fd 100644 --- a/src/System.Management.Automation/engine/remoting/commands/JobRepository.cs +++ b/src/System.Management.Automation/engine/remoting/commands/JobRepository.cs @@ -182,7 +182,7 @@ internal JobRepository() : base("job") /// Returns jobs guid. protected override Guid GetKey(Job item) { - if (item != null) + if (item is not null) { return item.InstanceId; } diff --git a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs index c4825484c57..56d8173c46e 100644 --- a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs +++ b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs @@ -744,7 +744,7 @@ protected override void ProcessRecord() // Run as virtual account groups if (ShouldGenerateConfigurationSnippet("RunAsVirtualAccountGroups")) { - bool haveVirtualAccountGroups = (RunAsVirtualAccountGroups != null) && (RunAsVirtualAccountGroups.Length > 0); + bool haveVirtualAccountGroups = (RunAsVirtualAccountGroups is not null) && (RunAsVirtualAccountGroups.Length > 0); resultData = (haveVirtualAccountGroups) ? SessionConfigurationUtils.CombineStringArray(RunAsVirtualAccountGroups) : "'Remote Desktop Users', 'Remote Management Users'"; result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.RunAsVirtualAccountGroups, RemotingErrorIdStrings.DISCRunAsVirtualAccountGroupsComment, resultData, streamWriter, !haveVirtualAccountGroups)); @@ -946,7 +946,7 @@ protected override void ProcessRecord() { Hashtable[] funcHash = DISCPowerShellConfiguration.TryGetHashtableArray(_functionDefinitions); - if (funcHash != null) + if (funcHash is not null) { result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.FunctionDefinitions, RemotingErrorIdStrings.DISCFunctionDefinitionsComment, SessionConfigurationUtils.CombineHashtableArray(funcHash, streamWriter), streamWriter, false)); @@ -1008,7 +1008,7 @@ protected override void ProcessRecord() { string varString = _variableDefinitions as string; - if (varString != null) + if (varString is not null) { result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VariableDefinitions, RemotingErrorIdStrings.DISCVariableDefinitionsComment, varString, streamWriter, false)); @@ -1017,7 +1017,7 @@ protected override void ProcessRecord() { Hashtable[] varHash = DISCPowerShellConfiguration.TryGetHashtableArray(_variableDefinitions); - if (varHash != null) + if (varHash is not null) { result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VariableDefinitions, RemotingErrorIdStrings.DISCVariableDefinitionsComment, SessionConfigurationUtils.CombineHashtableArray(varHash, streamWriter), streamWriter, false)); @@ -1693,7 +1693,7 @@ protected override void ProcessRecord() { Hashtable[] funcHash = DISCPowerShellConfiguration.TryGetHashtableArray(_functionDefinitions); - if (funcHash != null) + if (funcHash is not null) { result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.FunctionDefinitions, RemotingErrorIdStrings.DISCFunctionDefinitionsComment, SessionConfigurationUtils.CombineHashtableArray(funcHash, streamWriter), streamWriter, false)); @@ -1752,7 +1752,7 @@ protected override void ProcessRecord() { string varString = _variableDefinitions as string; - if (varString != null) + if (varString is not null) { result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VariableDefinitions, RemotingErrorIdStrings.DISCVariableDefinitionsComment, varString, streamWriter, false)); @@ -1761,7 +1761,7 @@ protected override void ProcessRecord() { Hashtable[] varHash = DISCPowerShellConfiguration.TryGetHashtableArray(_variableDefinitions); - if (varHash != null) + if (varHash is not null) { result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.VariableDefinitions, RemotingErrorIdStrings.DISCVariableDefinitionsComment, SessionConfigurationUtils.CombineHashtableArray(varHash, streamWriter), streamWriter, false)); @@ -1925,7 +1925,7 @@ internal static string WriteLong(long longToEmit) /// internal static string GetVisibilityDefault(object[] values, StreamWriter writer, PSCmdlet caller) { - if ((values != null) && (values.Length > 0)) + if ((values is not null) && (values.Length > 0)) { return CombineHashTableOrStringArray(values, writer, caller); } @@ -1951,28 +1951,28 @@ internal static string CombineHashtable(IDictionary table, StreamWriter writer, sb.AppendFormat("{0," + (4 * (indent + 1)) + "}", string.Empty); sb.Append(QuoteName(key)); sb.Append(" = "); - if ((table[key] as ScriptBlock) != null) + if ((table[key] as ScriptBlock) is not null) { sb.Append(WrapScriptBlock(table[key].ToString())); continue; } IDictionary tableValue = table[key] as IDictionary; - if (tableValue != null) + if (tableValue is not null) { sb.Append(CombineHashtable(tableValue, writer, indent + 1)); continue; } IDictionary[] tableValues = DISCPowerShellConfiguration.TryGetHashtableArray(table[key]); - if (tableValues != null) + if (tableValues is not null) { sb.Append(CombineHashtableArray(tableValues, writer, indent + 1)); continue; } string[] stringValues = DISCPowerShellConfiguration.TryGetStringArray(table[key]); - if (stringValues != null) + if (stringValues is not null) { sb.Append(CombineStringArray(stringValues)); continue; @@ -2013,7 +2013,7 @@ internal static string CombineRequiredGroupsHash(IDictionary table) sb.Append(" = "); object[] values = keyObject as object[]; - if (values != null) + if (values is not null) { for (int i = 0; i < values.Length;) { @@ -2038,14 +2038,14 @@ internal static string CombineRequiredGroupsHash(IDictionary table) private static void WriteRequiredGroup(object value, StringBuilder sb) { string strValue = value as string; - if (strValue != null) + if (strValue is not null) { sb.Append(QuoteName(strValue)); } else { Hashtable subTable = value as Hashtable; - if (subTable != null) + if (subTable is not null) { sb.Append(CombineRequiredGroupsHash(subTable)); } diff --git a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionOptionCommand.cs b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionOptionCommand.cs index 5ad0df8910c..431478f10ed 100644 --- a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionOptionCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionOptionCommand.cs @@ -393,12 +393,12 @@ protected override void BeginProcessing() result.MaximumReceivedDataSizePerCommand = _maxRecvdDataSizePerCommand; result.MaximumReceivedObjectSize = _maxRecvdObjectSize; - if (this.Culture != null) + if (this.Culture is not null) { result.Culture = this.Culture; } - if (this.UICulture != null) + if (this.UICulture is not null) { result.UICulture = this.UICulture; } @@ -422,7 +422,7 @@ protected override void BeginProcessing() result.MaxConnectionRetryCount = MaxConnectionRetryCount; - if (this.ApplicationArguments != null) + if (this.ApplicationArguments is not null) { result.ApplicationArguments = this.ApplicationArguments; } diff --git a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs index b3a794db76b..9d061089b1a 100644 --- a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs +++ b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs @@ -92,7 +92,7 @@ protected void ResolveComputerNames(string[] computerNames, out string[] resolve /// Resolved computer name. protected string ResolveComputerName(string computerName) { - Diagnostics.Assert(computerName != null, "Null ComputerName"); + Diagnostics.Assert(computerName is not null, "Null ComputerName"); if (string.Equals(computerName, ".", StringComparison.OrdinalIgnoreCase)) { @@ -130,7 +130,7 @@ internal string GetMessage(string resourceString, params object[] args) { string message; - if (args != null) + if (args is not null) { message = StringUtil.Format(resourceString, args); } @@ -809,7 +809,7 @@ public virtual Hashtable[] SSHConnection /// internal static void ValidateSpecifiedAuthentication(PSCredential credential, string thumbprint, AuthenticationMechanism authentication) { - if ((credential != null) && (thumbprint != null)) + if ((credential is not null) && (thumbprint is not null)) { string message = PSRemotingErrorInvariants.FormatResourceString( RemotingErrorIdStrings.NewRunspaceAmbiguousAuthentication, @@ -818,7 +818,7 @@ internal static void ValidateSpecifiedAuthentication(PSCredential credential, st throw new InvalidOperationException(message); } - if ((authentication != AuthenticationMechanism.Default) && (thumbprint != null)) + if ((authentication != AuthenticationMechanism.Default) && (thumbprint is not null)) { string message = PSRemotingErrorInvariants.FormatResourceString( RemotingErrorIdStrings.NewRunspaceAmbiguousAuthentication, @@ -828,7 +828,7 @@ internal static void ValidateSpecifiedAuthentication(PSCredential credential, st } if ((authentication == AuthenticationMechanism.NegotiateWithImplicitCredential) && - (credential != null)) + (credential is not null)) { string message = PSRemotingErrorInvariants.FormatResourceString( RemotingErrorIdStrings.NewRunspaceAmbiguousAuthentication, @@ -979,7 +979,7 @@ internal SSHConnection[] ParseSSHConnectionHashTable() /// the validations fail protected void ValidateRemoteRunspacesSpecified() { - Dbg.Assert(Session != null && Session.Length != 0, + Dbg.Assert(Session is not null && Session.Length != 0, "Remote Runspaces specified must not be null or empty"); // Check if there are duplicates in the specified PSSession objects @@ -1015,7 +1015,7 @@ protected void ValidateRemoteRunspacesSpecified() /// internal void UpdateConnectionInfo(WSManConnectionInfo connectionInfo) { - Dbg.Assert(connectionInfo != null, "connectionInfo cannot be null."); + Dbg.Assert(connectionInfo is not null, "connectionInfo cannot be null."); connectionInfo.SetSessionOptions(this.SessionOption); @@ -1119,7 +1119,7 @@ protected override void BeginProcessing() // Validate KeyFilePath parameter. if ((ParameterSetName == PSRemotingBaseCmdlet.SSHHostParameterSet) && - (this.KeyFilePath != null)) + (this.KeyFilePath is not null)) { // Resolve the key file path when set. this.KeyFilePath = PathResolver.ResolveProviderAndPath(this.KeyFilePath, true, this, false, RemotingErrorIdStrings.FilePathNotFromFileSystemProvider); @@ -1387,7 +1387,7 @@ protected virtual void CreateHelpersForSpecifiedComputerNames() connectionInfo.Port = Port; connectionInfo.AppName = ApplicationName; connectionInfo.ShellUri = ConfigurationName; - if (CertificateThumbprint != null) + if (CertificateThumbprint is not null) { connectionInfo.CertificateThumbprint = CertificateThumbprint; } @@ -1405,7 +1405,7 @@ protected virtual void CreateHelpersForSpecifiedComputerNames() // Use the provided session name or create one for this remote runspace so that // it can be easily identified if it becomes disconnected and is queried on the server. int rsId = PSSession.GenerateRunspaceId(); - string rsName = (DisconnectedSessionName != null && DisconnectedSessionName.Length > i) ? + string rsName = (DisconnectedSessionName is not null && DisconnectedSessionName.Length > i) ? DisconnectedSessionName[i] : PSSession.GenerateRunspaceName(out rsId); remoteRunspace = new RemoteRunspace(Utils.GetTypeTableFromExecutionContextTLS(), connectionInfo, @@ -1525,7 +1525,7 @@ protected void CreateHelpersForSpecifiedUris() connectionInfo.ConnectionUri = ConnectionUri[i]; connectionInfo.ShellUri = ConfigurationName; - if (CertificateThumbprint != null) + if (CertificateThumbprint is not null) { connectionInfo.CertificateThumbprint = CertificateThumbprint; } @@ -1544,7 +1544,7 @@ protected void CreateHelpersForSpecifiedUris() Utils.GetTypeTableFromExecutionContextTLS(), this.SessionOption.ApplicationArguments); - Dbg.Assert(remoteRunspace != null, + Dbg.Assert(remoteRunspace is not null, "RemoteRunspace object created using URI is null"); remoteRunspace.Events.ReceivedEvents.PSEventReceived += OnRunspacePSEventReceived; @@ -1909,7 +1909,7 @@ private string GetRemoteServerPsVersion(RemoteRunspace remoteRunspace) PSVersionInfo.PSVersionTableName, PSVersionInfo.PSVersionName); - if (serverPsVersion != null) + if (serverPsVersion is not null) { return serverPsVersion.Major >= 5 ? PSv5OrLater : PSv3Orv4; } @@ -1928,7 +1928,7 @@ private string GetRemoteServerPsVersion(RemoteRunspace remoteRunspace) /// internal void OnRunspacePSEventReceived(object sender, PSEventArgs e) { - if (this.Events != null) + if (this.Events is not null) this.Events.AddForwardedEvent(e); } @@ -2061,7 +2061,7 @@ protected override void BeginProcessing() base.BeginProcessing(); - if (_filePath != null) + if (_filePath is not null) { _scriptBlock = GetScriptBlockFromFile(_filePath, IsLiteralPath); } @@ -2161,11 +2161,11 @@ protected override void BeginProcessing() /// private System.Management.Automation.PowerShell GetPowerShellForPSv2() { - if (_powershellV2 != null) { return _powershellV2; } + if (_powershellV2 is not null) { return _powershellV2; } // Try to convert the scriptblock to powershell commands. _powershellV2 = ConvertToPowerShell(); - if (_powershellV2 != null) + if (_powershellV2 is not null) { // Look for EndOfStatement tokens. foreach (var command in _powershellV2.Commands.Commands) @@ -2178,7 +2178,7 @@ private System.Management.Automation.PowerShell GetPowerShellForPSv2() } } - if (_powershellV2 != null) { return _powershellV2; } + if (_powershellV2 is not null) { return _powershellV2; } } List newParameterNames; @@ -2187,7 +2187,7 @@ private System.Management.Automation.PowerShell GetPowerShellForPSv2() string scriptTextAdaptedForPSv2 = GetConvertedScript(out newParameterNames, out newParameterValues); _powershellV2 = System.Management.Automation.PowerShell.Create().AddScript(scriptTextAdaptedForPSv2); - if (_args != null) + if (_args is not null) { foreach (object arg in _args) { @@ -2195,9 +2195,9 @@ private System.Management.Automation.PowerShell GetPowerShellForPSv2() } } - if (newParameterNames != null) + if (newParameterNames is not null) { - Dbg.Assert(newParameterValues != null && newParameterNames.Count == newParameterValues.Count, "We should get the value for each using variable"); + Dbg.Assert(newParameterValues is not null && newParameterNames.Count == newParameterValues.Count, "We should get the value for each using variable"); for (int i = 0; i < newParameterNames.Count; i++) { _powershellV2.AddParameter(newParameterNames[i], newParameterValues[i]); @@ -2232,12 +2232,12 @@ private System.Management.Automation.PowerShell GetPowerShellForPSv2() /// private System.Management.Automation.PowerShell GetPowerShellForPSv3OrLater(string serverPsVersion) { - if (_powershellV3 != null) { return _powershellV3; } + if (_powershellV3 is not null) { return _powershellV3; } // Try to convert the scriptblock to powershell commands. _powershellV3 = ConvertToPowerShell(); - if (_powershellV3 != null) { return _powershellV3; } + if (_powershellV3 is not null) { return _powershellV3; } // Using expressions can be a variable, as well as property and / or array references. E.g. // @@ -2275,7 +2275,7 @@ private System.Management.Automation.PowerShell GetPowerShellForPSv3OrLater(stri _powershellV3 = System.Management.Automation.PowerShell.Create().AddScript(textOfScriptBlock); - if (_args != null) + if (_args is not null) { foreach (object arg in _args) { @@ -2283,11 +2283,11 @@ private System.Management.Automation.PowerShell GetPowerShellForPSv3OrLater(stri } } - if (usingValuesInDict != null && usingValuesInDict.Count > 0) + if (usingValuesInDict is not null && usingValuesInDict.Count > 0) { _powershellV3.AddParameter(Parser.VERBATIM_ARGUMENT, usingValuesInDict); } - else if (usingValuesInArray != null && usingValuesInArray.Length > 0) + else if (usingValuesInArray is not null && usingValuesInArray.Length > 0) { _powershellV3.AddParameter(Parser.VERBATIM_ARGUMENT, usingValuesInArray); } @@ -2986,7 +2986,7 @@ private Dictionary GetMatchingRunspacesByVMNameContainerId(bool } // When "-name" is not set, we use "*" that means matching all. - if (Name != null) + if (Name is not null) { sessionNames = Name; } @@ -3092,7 +3092,7 @@ private Dictionary GetMatchingRunspacesByVMId(bool writeobject, List remoteRunspaceInfos = this.RunspaceRepository.Runspaces; // When "-name" is not set, we use "*" that means matching all . - if (Name != null) + if (Name is not null) { sessionNames = Name; } @@ -3432,7 +3432,7 @@ private void RaiseOperationCompleteEvent(EventArgs baseEventArgs) { CleanupRunspaceDebugging(PipelineRunspace); - if (pipeline != null) + if (pipeline is not null) { // Dispose the pipeline object and release data and remoting resources. // Pipeline object remains to provide information on final state and any errors incurred. @@ -3446,7 +3446,7 @@ private void RaiseOperationCompleteEvent(EventArgs baseEventArgs) OperationState.StopComplete; operationStateEventArgs.BaseEvent = baseEventArgs; - if (OperationComplete != null) + if (OperationComplete is not null) { OperationComplete.SafeInvoke(this, operationStateEventArgs); } @@ -3489,7 +3489,7 @@ internal class ExecutionCmdletHelperComputerName : ExecutionCmdletHelper /// Indicates if pipeline should be disconnected after invoking command. internal ExecutionCmdletHelperComputerName(RemoteRunspace remoteRunspace, Pipeline pipeline, bool invokeAndDisconnect = false) { - Dbg.Assert(remoteRunspace != null, + Dbg.Assert(remoteRunspace is not null, "RemoteRunspace reference cannot be null"); PipelineRunspace = remoteRunspace; @@ -3498,7 +3498,7 @@ internal ExecutionCmdletHelperComputerName(RemoteRunspace remoteRunspace, Pipeli RemoteRunspace = remoteRunspace; remoteRunspace.StateChanged += HandleRunspaceStateChanged; - Dbg.Assert(pipeline != null, + Dbg.Assert(pipeline is not null, "Pipeline cannot be null or empty"); this.pipeline = pipeline; @@ -3610,7 +3610,7 @@ private void HandleRunspaceStateChanged(object sender, { // raise a OperationComplete event with // StopComplete message - if (stateEventArgs.RunspaceStateInfo.Reason != null) + if (stateEventArgs.RunspaceStateInfo.Reason is not null) { RaiseOperationCompleteEvent(stateEventArgs); } @@ -3644,7 +3644,7 @@ private void HandlePipelineStateChanged(object sender, case PipelineState.Completed: case PipelineState.Stopped: case PipelineState.Failed: - if (RemoteRunspace != null) + if (RemoteRunspace is not null) { RemoteRunspace.CloseAsync(); } @@ -3669,7 +3669,7 @@ private void RaiseOperationCompleteEvent() /// raises this operation complete private void RaiseOperationCompleteEvent(EventArgs baseEventArgs) { - if (pipeline != null) + if (pipeline is not null) { // Dispose the pipeline object and release data and remoting resources. // Pipeline object remains to provide information on final state and any errors incurred. @@ -3677,7 +3677,7 @@ private void RaiseOperationCompleteEvent(EventArgs baseEventArgs) pipeline.Dispose(); } - if (RemoteRunspace != null) + if (RemoteRunspace is not null) { // Dispose of the runspace object. RemoteRunspace.Dispose(); @@ -3891,7 +3891,7 @@ internal Collection GetDisconnectedSessions(Collection GetDisconnectedSessions(Collection GetDisconnectedSessions(Collection GetDisconnectedSessions(Collection GetDisconnectedSessions(Collection 0)) + if ((matchIds is not null) && (filteredPSSessions.Count > 0)) { Collection matchIdsSessions = new Collection(); foreach (Guid id in matchIds) @@ -3986,7 +3986,7 @@ internal Collection GetDisconnectedSessions(Collection GetDisconnectedSessions(Collection 0)) + else if ((matchNames is not null) && (filteredPSSessions.Count > 0)) { Collection matchNamesSessions = new Collection(); foreach (string name in matchNames) @@ -4019,7 +4019,7 @@ internal Collection GetDisconnectedSessions(Collection protected override void EndProcessing() { - if (_stream != null) + if (_stream is not null) { while (true) { @@ -520,7 +520,7 @@ protected override void EndProcessing() protected override void StopProcessing() { var remoteRunspace = _tempRunspace; - if (remoteRunspace != null) + if (remoteRunspace is not null) { try { @@ -565,7 +565,7 @@ private RemoteRunspace CreateTemporaryRemoteRunspace(PSHost host, WSManConnectio this.SessionOption.ApplicationArguments, rsName, rsId); - Dbg.Assert(remoteRunspace != null, "Expected remoteRunspace != null"); + Dbg.Assert(remoteRunspace is not null, "Expected remoteRunspace is not null"); remoteRunspace.URIRedirectionReported += HandleURIDirectionReported; _stream = new ObjectStream(); @@ -607,7 +607,7 @@ private void WriteErrorCreateRemoteRunspaceFailed(Exception exception, object ar PSRemotingTransportException transException = exception as PSRemotingTransportException; string errorDetails = null; - if ((transException != null) && + if ((transException is not null) && (transException.ErrorCode == System.Management.Automation.Remoting.Client.WSManNativeApi.ERROR_WSMAN_REDIRECT_REQUESTED)) { @@ -675,7 +675,7 @@ private RemoteRunspace CreateRunspaceWhenComputerNameParameterSpecified() connectionInfo.AppName = ApplicationName; connectionInfo.ShellUri = ConfigurationName; connectionInfo.Scheme = scheme; - if (CertificateThumbprint != null) + if (CertificateThumbprint is not null) { connectionInfo.CertificateThumbprint = CertificateThumbprint; } @@ -718,7 +718,7 @@ private RemoteRunspace CreateRunspaceWhenUriParameterSpecified() WSManConnectionInfo connectionInfo = new WSManConnectionInfo(); connectionInfo.ConnectionUri = ConnectionUri; connectionInfo.ShellUri = ConfigurationName; - if (CertificateThumbprint != null) + if (CertificateThumbprint is not null) { connectionInfo.CertificateThumbprint = CertificateThumbprint; } @@ -783,7 +783,7 @@ private RemoteRunspace GetRunspaceMatchingCondition( else { remoteRunspace = (RemoteRunspace)matches[0].Runspace; - Dbg.Assert(remoteRunspace != null, "Expected remoteRunspace != null"); + Dbg.Assert(remoteRunspace is not null, "Expected remoteRunspace is not null"); } return remoteRunspace; @@ -846,8 +846,8 @@ private Job FindJobForRunspace(Guid id) { PSRemotingChildJob remotingChildJob = childJob as PSRemotingChildJob; - if (remotingChildJob != null && - remotingChildJob.Runspace != null && + if (remotingChildJob is not null && + remotingChildJob.Runspace is not null && remotingChildJob.JobStateInfo.State == JobState.Running && remotingChildJob.Runspace.InstanceId.Equals(id)) { @@ -881,7 +881,7 @@ private bool IsParameterSetForVMContainerSession() switch (ParameterSetName) { case SessionParameterSet: - if (this.Session != null) + if (this.Session is not null) { remoteRunspace = (RemoteRunspace)this.Session.Runspace; } @@ -904,8 +904,8 @@ private bool IsParameterSetForVMContainerSession() break; } - if ((remoteRunspace != null) && - (remoteRunspace.ConnectionInfo != null)) + if ((remoteRunspace is not null) && + (remoteRunspace.ConnectionInfo is not null)) { if ((remoteRunspace.ConnectionInfo is VMConnectionInfo) || (remoteRunspace.ConnectionInfo is ContainerConnectionInfo)) @@ -1060,7 +1060,7 @@ private RemoteRunspace GetRunspaceForVMSession() // In case of PSDirectException, we should output the precise error message // in inner exception instead of the generic one in outer exception. // - if ((e.InnerException != null) && (e.InnerException is PSDirectException)) + if ((e.InnerException is not null) && (e.InnerException is PSDirectException)) { errorRecord = new ErrorRecord(e.InnerException, "CreateRemoteRunspaceForVMFailed", @@ -1100,7 +1100,7 @@ private RemoteRunspace CreateTemporaryRemoteRunspaceForPowerShellDirect(PSHost h RemoteRunspace remoteRunspace = RunspaceFactory.CreateRunspace(connectionInfo, host, typeTable) as RemoteRunspace; remoteRunspace.Name = "PowerShellDirectAttach"; - Dbg.Assert(remoteRunspace != null, "Expected remoteRunspace != null"); + Dbg.Assert(remoteRunspace is not null, "Expected remoteRunspace is not null"); try { remoteRunspace.Open(); @@ -1145,14 +1145,14 @@ private void SetRunspacePrompt(RemoteRunspace remoteRunspace) break; case SessionParameterSet: - targetName = (this.Session != null) ? this.Session.ComputerName : string.Empty; + targetName = (this.Session is not null) ? this.Session.ComputerName : string.Empty; break; case InstanceIdParameterSet: case IdParameterSet: case NameParameterSet: - if ((remoteRunspace != null) && - (remoteRunspace.ConnectionInfo != null)) + if ((remoteRunspace is not null) && + (remoteRunspace.ConnectionInfo is not null)) { targetName = remoteRunspace.ConnectionInfo.ComputerName; } @@ -1236,7 +1236,7 @@ private RemoteRunspace GetRunspaceForContainerSession() // In case of PSDirectException, we should output the precise error message // in inner exception instead of the generic one in outer exception. // - if ((e.InnerException != null) && (e.InnerException is PSDirectException)) + if ((e.InnerException is not null) && (e.InnerException is PSDirectException)) { errorRecord = new ErrorRecord(e.InnerException, "CreateRemoteRunspaceForContainerFailed", @@ -1294,7 +1294,7 @@ private RemoteRunspace GetRunspaceForSSHSession() internal static RemotePipeline ConnectRunningPipeline(RemoteRunspace remoteRunspace) { RemotePipeline cmd = null; - if (remoteRunspace.RemoteCommand != null) + if (remoteRunspace.RemoteCommand is not null) { // Reconstruct scenario. // Newly connected pipeline object is added to the RemoteRunspace running @@ -1309,7 +1309,7 @@ internal static RemotePipeline ConnectRunningPipeline(RemoteRunspace remoteRunsp // Connect the runspace pipeline so that debugging and output data from // remote server can continue. - if (cmd != null && + if (cmd is not null && cmd.PipelineStateInfo.State == PipelineState.Disconnected) { using (ManualResetEvent connected = new ManualResetEvent(false)) @@ -1338,7 +1338,7 @@ internal static void ContinueCommand(RemoteRunspace remoteRunspace, Pipeline cmd { RemotePipeline remotePipeline = cmd as RemotePipeline; - if (remotePipeline != null) + if (remotePipeline is not null) { using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create()) { @@ -1355,7 +1355,7 @@ internal static void ContinueCommand(RemoteRunspace remoteRunspace, Pipeline cmd IAsyncResult async = ps.BeginInvoke(input, settings, null, null); RemoteDebugger remoteDebugger = remoteRunspace.Debugger as RemoteDebugger; - if (remoteDebugger != null) + if (remoteDebugger is not null) { // Update client with breakpoint information from pushed runspace. // Information will be passed to the client via the Debugger.BreakpointUpdated event. diff --git a/src/System.Management.Automation/engine/remoting/commands/ReceiveJob.cs b/src/System.Management.Automation/engine/remoting/commands/ReceiveJob.cs index 01109b0036d..92fe97c3f85 100644 --- a/src/System.Management.Automation/engine/remoting/commands/ReceiveJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/ReceiveJob.cs @@ -646,7 +646,7 @@ protected void Dispose(bool disposing) SetOutputProcessingState(false); - if (_jobsBeingAggregated != null) + if (_jobsBeingAggregated is not null) { foreach (var job in _jobsBeingAggregated) { @@ -707,7 +707,7 @@ private static void DoUnblockJob(Job job) // for remoting jobs, so use that if job is a remoting // job PSRemotingChildJob remotingChildJob = job as PSRemotingChildJob; - if (remotingChildJob != null) + if (remotingChildJob is not null) { remotingChildJob.UnblockJob(); } @@ -748,7 +748,7 @@ private void WriteJobResults(Job job) if (job.JobStateInfo.State == JobState.Disconnected) { PSRemotingChildJob remotingChildJob = job as PSRemotingChildJob; - if (remotingChildJob != null && remotingChildJob.DisconnectedAndBlocked) + if (remotingChildJob is not null && remotingChildJob.DisconnectedAndBlocked) { return; } @@ -804,7 +804,7 @@ private void WriteJobResults(Job job) { if (e is null) continue; MshCommandRuntime mshCommandRuntime = CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) + if (mshCommandRuntime is not null) { e.PreserveInvocationInfoOnce = true; mshCommandRuntime.WriteError(e, true); @@ -817,7 +817,7 @@ private void WriteJobResults(Job job) { if (v is null) continue; MshCommandRuntime mshCommandRuntime = CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) + if (mshCommandRuntime is not null) { mshCommandRuntime.WriteVerbose(v, true); } @@ -829,7 +829,7 @@ private void WriteJobResults(Job job) { if (d is null) continue; MshCommandRuntime mshCommandRuntime = CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) + if (mshCommandRuntime is not null) { mshCommandRuntime.WriteDebug(d, true); } @@ -841,7 +841,7 @@ private void WriteJobResults(Job job) { if (w is null) continue; MshCommandRuntime mshCommandRuntime = CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) + if (mshCommandRuntime is not null) { mshCommandRuntime.WriteWarning(w, true); } @@ -853,7 +853,7 @@ private void WriteJobResults(Job job) { if (p is null) continue; MshCommandRuntime mshCommandRuntime = CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) + if (mshCommandRuntime is not null) { mshCommandRuntime.WriteProgress(p, true); } @@ -865,7 +865,7 @@ private void WriteJobResults(Job job) { if (p is null) continue; MshCommandRuntime mshCommandRuntime = CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) + if (mshCommandRuntime is not null) { mshCommandRuntime.WriteInformation(p, true); } @@ -881,11 +881,11 @@ private void WriteReasonError(Job job) { // Write better error for the remoting case and generic error for the other case PSRemotingChildJob child = job as PSRemotingChildJob; - if (child != null && child.FailureErrorRecord != null) + if (child is not null && child.FailureErrorRecord is not null) { _results.Add(new PSStreamObject(PSStreamObjectType.Error, child.FailureErrorRecord, child.InstanceId)); } - else if (job.JobStateInfo.Reason != null) + else if (job.JobStateInfo.Reason is not null) { Exception baseReason = job.JobStateInfo.Reason; Exception resultReason = baseReason; @@ -893,7 +893,7 @@ private void WriteReasonError(Job job) // If it was generated by a job that gave location information, unpack the // base exception. JobFailedException exceptionWithLocation = baseReason as JobFailedException; - if (exceptionWithLocation != null) + if (exceptionWithLocation is not null) { resultReason = exceptionWithLocation.Reason; } @@ -902,7 +902,7 @@ private void WriteReasonError(Job job) // If it was generated by a job that gave location information, set the // location information. - if ((exceptionWithLocation != null) && (exceptionWithLocation.DisplayScriptPosition != null)) + if ((exceptionWithLocation is not null) && (exceptionWithLocation.DisplayScriptPosition is not null)) { if (errorRecord.InvocationInfo is null) { @@ -1083,10 +1083,10 @@ private void ResultsAdded(object sender, DataAddedEventArgs e) _writeExistingData.WaitOne(); PSDataCollection results = sender as PSDataCollection; - Dbg.Assert(results != null, "PSDataCollection is raising an inappropriate event"); + Dbg.Assert(results is not null, "PSDataCollection is raising an inappropriate event"); PSStreamObject record = GetData(results, e.Index); - if (record != null) + if (record is not null) { record.Id = results.SourceId; _results.Add(record); @@ -1096,7 +1096,7 @@ private void ResultsAdded(object sender, DataAddedEventArgs e) private void HandleJobStateChanged(object sender, JobStateEventArgs e) { Job job = sender as Job; - Dbg.Assert(job != null, "Job state info cannot be raised with reference to job"); + Dbg.Assert(job is not null, "Job state info cannot be raised with reference to job"); // waiting for existing data to be written ensures two things // 1. that no aggregation for a job is in progress @@ -1157,10 +1157,10 @@ private void Progress_DataAdded(object sender, DataAddedEventArgs e) { if (!_results.IsOpen) return; PSDataCollection progressRecords = sender as PSDataCollection; - Diagnostics.Assert(progressRecords != null, "PSDataCollection is raising an inappropriate event"); + Diagnostics.Assert(progressRecords is not null, "PSDataCollection is raising an inappropriate event"); ProgressRecord record = GetData(progressRecords, e.Index); - if (record != null) + if (record is not null) { _results.Add(new PSStreamObject(PSStreamObjectType.Progress, record, progressRecords.SourceId)); } @@ -1184,9 +1184,9 @@ private void Error_DataAdded(object sender, DataAddedEventArgs e) { if (!_results.IsOpen) return; PSDataCollection errorRecords = sender as PSDataCollection; - Diagnostics.Assert(errorRecords != null, "PSDataCollection is raising an inappropriate event"); + Diagnostics.Assert(errorRecords is not null, "PSDataCollection is raising an inappropriate event"); ErrorRecord errorRecord = GetData(errorRecords, e.Index); - if (errorRecord != null) + if (errorRecord is not null) { // error records are already tagged, skip tagging _results.Add(new PSStreamObject(PSStreamObjectType.Error, errorRecord, Guid.Empty)); @@ -1211,9 +1211,9 @@ private void Debug_DataAdded(object sender, DataAddedEventArgs e) { if (!_results.IsOpen) return; PSDataCollection debugRecords = sender as PSDataCollection; - Diagnostics.Assert(debugRecords != null, "PSDataCollection is raising an inappropriate event"); + Diagnostics.Assert(debugRecords is not null, "PSDataCollection is raising an inappropriate event"); DebugRecord record = GetData(debugRecords, e.Index); - if (record != null) + if (record is not null) { // debug records are already tagged, skip tagging _results.Add(new PSStreamObject(PSStreamObjectType.Debug, record.Message, Guid.Empty)); @@ -1238,9 +1238,9 @@ private void Warning_DataAdded(object sender, DataAddedEventArgs e) { if (!_results.IsOpen) return; PSDataCollection warningRecords = sender as PSDataCollection; - Diagnostics.Assert(warningRecords != null, "PSDataCollection is raising an inappropriate event"); + Diagnostics.Assert(warningRecords is not null, "PSDataCollection is raising an inappropriate event"); WarningRecord record = GetData(warningRecords, e.Index); - if (record != null) + if (record is not null) { // warning records are already tagged, skip tagging _results.Add(new PSStreamObject(PSStreamObjectType.Warning, record.Message, Guid.Empty)); @@ -1265,9 +1265,9 @@ private void Verbose_DataAdded(object sender, DataAddedEventArgs e) { if (!_results.IsOpen) return; PSDataCollection verboseRecords = sender as PSDataCollection; - Dbg.Assert(verboseRecords != null, "PSDataCollection is raising an inappropriate event"); + Dbg.Assert(verboseRecords is not null, "PSDataCollection is raising an inappropriate event"); VerboseRecord record = GetData(verboseRecords, e.Index); - if (record != null) + if (record is not null) { // verbose records are already tagged, skip tagging _results.Add(new PSStreamObject(PSStreamObjectType.Verbose, record.Message, Guid.Empty)); @@ -1292,9 +1292,9 @@ private void Information_DataAdded(object sender, DataAddedEventArgs e) { if (!_results.IsOpen) return; PSDataCollection informationRecords = sender as PSDataCollection; - Dbg.Assert(informationRecords != null, "PSDataCollection is raising an inappropriate event"); + Dbg.Assert(informationRecords is not null, "PSDataCollection is raising an inappropriate event"); InformationRecord record = GetData(informationRecords, e.Index); - if (record != null) + if (record is not null) { // information records are already tagged, skip tagging _results.Add(new PSStreamObject(PSStreamObjectType.Information, record, Guid.Empty)); @@ -1319,9 +1319,9 @@ private void Output_DataAdded(object sender, DataAddedEventArgs e) { if (!_results.IsOpen) return; PSDataCollection output = sender as PSDataCollection; - Dbg.Assert(output != null, "PSDataCollection is raising an inappropriate event"); + Dbg.Assert(output is not null, "PSDataCollection is raising an inappropriate event"); PSObject obj = GetData(output, e.Index); - if (obj != null) + if (obj is not null) { // output objects are already tagged, skip tagging _results.Add(new PSStreamObject(PSStreamObjectType.Output, obj, Guid.Empty)); @@ -1407,7 +1407,7 @@ private void AutoRemoveJobIfRequired(Job job) } Job2 job2 = job as Job2; - if (job2 != null) + if (job2 is not null) { #pragma warning disable 56500 try @@ -1585,7 +1585,7 @@ private void SetOutputProcessingState(bool processingOutput) } } - if (_outputProcessingNotification != null && stateChanged) + if (_outputProcessingNotification is not null && stateChanged) { _outputProcessingNotification.RaiseOutputProcessingStateChangedEvent(processingOutput); } diff --git a/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs b/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs index aa2130596d9..914647aed80 100644 --- a/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs +++ b/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs @@ -389,12 +389,12 @@ protected override void StopProcessing() tmpJob = _job; } - if (tmpPipeline != null) + if (tmpPipeline is not null) { tmpPipeline.StopAsync(); } - if (tmpJob != null) + if (tmpJob is not null) { tmpJob.StopJob(); } @@ -453,11 +453,11 @@ private void QueryForAndConnectCommands(string name, Guid instanceId) } // Filter returned runspaces by ConfigurationName if provided. - if (shellUri != null) + if (shellUri is not null) { // Compare with returned shell Uri in connection info. WSManConnectionInfo wsmanConnectionInfo = runspace.ConnectionInfo as WSManConnectionInfo; - if (wsmanConnectionInfo != null && + if (wsmanConnectionInfo is not null && !shellUri.Equals(wsmanConnectionInfo.ShellUri, StringComparison.OrdinalIgnoreCase)) { continue; @@ -489,7 +489,7 @@ private void QueryForAndConnectCommands(string name, Guid instanceId) Exception ex; PSSession connectedSession = ConnectSession(locSession, out ex); - if (connectedSession != null) + if (connectedSession is not null) { // Make sure that this connected session is included in the PSSession repository. // If it already exists then replace it because we want the latest/connected session in the repository. @@ -515,10 +515,10 @@ private void QueryForAndConnectCommands(string name, Guid instanceId) // Create and connect session. PSSession newSession = new PSSession(runspace as RemoteRunspace); connectedSession = ConnectSession(newSession, out ex); - if (connectedSession != null) + if (connectedSession is not null) { // Try to reuse the existing local repository PSSession object. - if (locSession != null) + if (locSession is not null) { connectedSession = locSession.InsertRunspace(connectedSession.Runspace as RemoteRunspace) ? locSession : connectedSession; } @@ -565,7 +565,7 @@ private WSManConnectionInfo GetConnectionObject() connectionInfo.AppName = ApplicationName; connectionInfo.ShellUri = ConfigurationName; connectionInfo.Port = Port; - if (CertificateThumbprint != null) + if (CertificateThumbprint is not null) { connectionInfo.CertificateThumbprint = CertificateThumbprint; } @@ -581,7 +581,7 @@ private WSManConnectionInfo GetConnectionObject() { connectionInfo.ConnectionUri = ConnectionUri; connectionInfo.ShellUri = ConfigurationName; - if (CertificateThumbprint != null) + if (CertificateThumbprint is not null) { connectionInfo.CertificateThumbprint = CertificateThumbprint; } @@ -617,7 +617,7 @@ private void UpdateConnectionInfo(WSManConnectionInfo connectionInfo) } // Update the connectionInfo object with passed in session options. - if (SessionOption != null) + if (SessionOption is not null) { connectionInfo.SetSessionOptions(SessionOption); } @@ -714,7 +714,7 @@ private void GetAndConnectSessionCommand() // If so then we use this job object, unless the user explicitly specifies // output to host. PSRemotingJob job = FindJobForSession(session); - if (job != null) + if (job is not null) { // Default is to route data to job. if (OutTarget == OutTarget.Host) @@ -803,7 +803,7 @@ private void DisconnectAndStopRunningCmds(RemoteRunspace remoteRunspace) remoteRunspace.Disconnect(); - if (stopPipelineReceive != null) + if (stopPipelineReceive is not null) { try { @@ -812,7 +812,7 @@ private void DisconnectAndStopRunningCmds(RemoteRunspace remoteRunspace) catch (ObjectDisposedException) { } } - if (job != null) + if (job is not null) { job.StopJob(); } @@ -834,9 +834,9 @@ private void WriteDebugStopWarning() private void ConnectSessionToHost(PSSession session, PSRemotingJob job = null) { RemoteRunspace remoteRunspace = session.Runspace as RemoteRunspace; - Dbg.Assert(remoteRunspace != null, "PS sessions can only contain RemoteRunspace type."); + Dbg.Assert(remoteRunspace is not null, "PS sessions can only contain RemoteRunspace type."); - if (job != null) + if (job is not null) { // If we have a job object associated with the session then this means // the user explicitly chose to connect and return data synchronously. @@ -861,7 +861,7 @@ private void ConnectSessionToHost(PSSession session, PSRemotingJob job = null) foreach (var result in childJob.ReadAll()) { - if (result != null) + if (result is not null) { result.WriteStreamObject(this); } @@ -908,7 +908,7 @@ private void ConnectSessionToHost(PSSession session, PSRemotingJob job = null) { _remotePipeline.StateChanged += (sender, args) => { - if (pipelineConnectedEvent != null && + if (pipelineConnectedEvent is not null && (args.PipelineStateInfo.State == PipelineState.Running || args.PipelineStateInfo.State == PipelineState.Stopped || args.PipelineStateInfo.State == PipelineState.Failed)) @@ -999,7 +999,7 @@ private void ConnectSessionToHost(PSSession session, PSRemotingJob job = null) { Exception reason = _remotePipeline.PipelineStateInfo.Reason; string msg; - if (reason != null && !string.IsNullOrEmpty(reason.Message)) + if (reason is not null && !string.IsNullOrEmpty(reason.Message)) { msg = StringUtil.Format(RemotingErrorIdStrings.PipelineFailedWithReason, reason.Message); } @@ -1175,7 +1175,7 @@ private PSSession TryGetSessionFromServer(PSSession session) } } - if (remoteRunspace != null) + if (remoteRunspace is not null) { // Try inserting connected runspace into existing PSSession. session = session.InsertRunspace(remoteRunspace) ? session : new PSSession(remoteRunspace); @@ -1197,7 +1197,7 @@ private PSRemotingJob FindJobForSession(PSSession session) RemoteRunspace remoteSessionRunspace = session.Runspace as RemoteRunspace; if (remoteSessionRunspace is null || - remoteSessionRunspace.RemoteCommand != null) + remoteSessionRunspace.RemoteCommand is not null) { // The provided session is created for *reconstruction* and we // cannot connect a previous job even if one exists. A new job @@ -1219,7 +1219,7 @@ private PSRemotingJob FindJobForSession(PSSession session) } } - if (job != null) + if (job is not null) { break; } diff --git a/src/System.Management.Automation/engine/remoting/commands/RemoveJob.cs b/src/System.Management.Automation/engine/remoting/commands/RemoveJob.cs index 12c92f286bf..ebba89f0177 100644 --- a/src/System.Management.Automation/engine/remoting/commands/RemoveJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/RemoveJob.cs @@ -77,7 +77,7 @@ internal List FindJobsMatchingByName( // search all jobs in JobManager List jobs2 = JobManager.GetJobsByName(name, this, false, writeobject, recurse, null); - bool job2Found = (jobs2 != null) && (jobs2.Count > 0); + bool job2Found = (jobs2 is not null) && (jobs2.Count > 0); if (job2Found) { @@ -161,7 +161,7 @@ private bool FindJobsMatchingByNameHelper(List matches, IList jobsToSe } // check if the job is available in any of the childjobs - if (job.ChildJobs != null && job.ChildJobs.Count > 0 && recurse) + if (job.ChildJobs is not null && job.ChildJobs.Count > 0 && recurse) { bool jobFoundinChildJobs = FindJobsMatchingByNameHelper(matches, job.ChildJobs, name, duplicateDetector, recurse, writeobject, checkIfJobCanBeRemoved); @@ -204,7 +204,7 @@ internal List FindJobsMatchingByInstanceId(bool recurse, bool writeobject, // search all jobs in JobManager Job2 job2 = JobManager.GetJobByInstanceId(id, this, false, writeobject, recurse); - bool job2Found = job2 != null; + bool job2Found = job2 is not null; if (job2Found) { @@ -277,7 +277,7 @@ private bool FindJobsMatchingByInstanceIdHelper(List matches, IList jo { foreach (Job job in jobsToSearch) { - if (job.ChildJobs != null && job.ChildJobs.Count > 0) + if (job.ChildJobs is not null && job.ChildJobs.Count > 0) { jobFound = FindJobsMatchingByInstanceIdHelper(matches, job.ChildJobs, instanceId, duplicateDetector, recurse, writeobject, checkIfJobCanBeRemoved); @@ -318,7 +318,7 @@ internal List FindJobsMatchingBySessionId(bool recurse, bool writeobject, b // check jobs in job manager Job2 job2 = JobManager.GetJobById(id, this, false, writeobject, recurse); - bool job2Found = job2 != null; + bool job2Found = job2 is not null; if (job2Found) { @@ -381,7 +381,7 @@ private bool FindJobsMatchingBySessionIdHelper(List matches, IList job { foreach (Job job in jobsToSearch) { - if (job.ChildJobs != null && job.ChildJobs.Count > 0) + if (job.ChildJobs is not null && job.ChildJobs.Count > 0) { jobFound = FindJobsMatchingBySessionIdHelper(matches, job.ChildJobs, sessionId, duplicateDetector, recurse, writeobject, checkIfJobCanBeRemoved); @@ -418,7 +418,7 @@ internal List FindJobsMatchingByCommand( { List jobs2 = JobManager.GetJobsByCommand(command, this, false, false, false, null); - if (jobs2 != null) + if (jobs2 is not null) { foreach (Job2 job2 in jobs2) { @@ -466,7 +466,7 @@ internal List FindJobsMatchingByState( List jobs2 = JobManager.GetJobsByState(_jobstate, this, false, false, false, null); - if (jobs2 != null) + if (jobs2 is not null) { foreach (Job2 job2 in jobs2) { @@ -511,7 +511,7 @@ internal List FindJobsMatchingByFilter(bool writeobject) } List jobs2 = JobManager.GetJobsByFilter(filterDictionary, this, false, false, true); - if (jobs2 != null) + if (jobs2 is not null) { foreach (Job2 job2 in jobs2) { @@ -900,7 +900,7 @@ protected override void ProcessRecord() { // if it is a Job2, then async is supported // stop the job asynchronously - if (job2 != null) + if (job2 is not null) { _cleanUpActions.Add(job2, HandleStopJobCompleted); job2.StopJobCompleted += HandleStopJobCompleted; @@ -924,7 +924,7 @@ protected override void ProcessRecord() } else { - RemoveJobAndDispose(job, job2 != null); + RemoveJobAndDispose(job, job2 is not null); } } } diff --git a/src/System.Management.Automation/engine/remoting/commands/ResumeJob.cs b/src/System.Management.Automation/engine/remoting/commands/ResumeJob.cs index 1b5fcd7bbe4..260ef9d67a5 100644 --- a/src/System.Management.Automation/engine/remoting/commands/ResumeJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/ResumeJob.cs @@ -175,13 +175,13 @@ private void HandleResumeJobCompleted(object sender, AsyncCompletedEventArgs eve { Job job = sender as Job; - if (eventArgs.Error != null && eventArgs.Error is InvalidJobStateException) + if (eventArgs.Error is not null && eventArgs.Error is InvalidJobStateException) { _warnInvalidState = true; } var parentJob = job as ContainerParentJob; - if (parentJob != null && parentJob.ExecutionError.Count > 0) + if (parentJob is not null && parentJob.ExecutionError.Count > 0) { foreach ( var e in diff --git a/src/System.Management.Automation/engine/remoting/commands/StartJob.cs b/src/System.Management.Automation/engine/remoting/commands/StartJob.cs index 79173c681dc..4f2add577bb 100644 --- a/src/System.Management.Automation/engine/remoting/commands/StartJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/StartJob.cs @@ -596,7 +596,7 @@ protected override void BeginProcessing() ThrowTerminatingError(errorRecord); } - if (WorkingDirectory != null && !Directory.Exists(WorkingDirectory)) + if (WorkingDirectory is not null && !Directory.Exists(WorkingDirectory)) { string message = StringUtil.Format(RemotingErrorIdStrings.StartJobWorkingDirectoryNotFound, WorkingDirectory); var errorRecord = new ErrorRecord( @@ -644,7 +644,7 @@ protected override void CreateHelpersForSpecifiedComputerNames() // we can't protect that boundary if ((Context.LanguageMode == PSLanguageMode.ConstrainedLanguage) && (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Enforce) && - ((ScriptBlock != null) || (InitializationScript != null))) + ((ScriptBlock is not null) || (InitializationScript is not null))) { ThrowTerminatingError( new ErrorRecord( @@ -723,7 +723,7 @@ protected override void ProcessRecord() if (jobs.Count == 0) { - string message = (_definitionType != null) ? + string message = (_definitionType is not null) ? StringUtil.Format(RemotingErrorIdStrings.StartJobDefinitionNotFound2, _definitionType, _definitionName) : StringUtil.Format(RemotingErrorIdStrings.StartJobDefinitionNotFound1, _definitionName); diff --git a/src/System.Management.Automation/engine/remoting/commands/StopJob.cs b/src/System.Management.Automation/engine/remoting/commands/StopJob.cs index 7890bdc54f0..c39e9dad71b 100644 --- a/src/System.Management.Automation/engine/remoting/commands/StopJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/StopJob.cs @@ -151,7 +151,7 @@ protected override void ProcessRecord() Job2 job2 = job as Job2; // if it is a Job2, then async is supported // stop the job asynchronously - if (job2 != null) + if (job2 is not null) { _cleanUpActions.Add(job2, HandleStopJobCompleted); job2.StopJobCompleted += HandleStopJobCompleted; @@ -213,13 +213,13 @@ private void HandleStopJobCompleted(object sender, AsyncCompletedEventArgs event { Job job = sender as Job; - if (eventArgs.Error != null) + if (eventArgs.Error is not null) { _errorsToWrite.Add(new ErrorRecord(eventArgs.Error, "StopJobError", ErrorCategory.ReadError, job)); } var parentJob = job as ContainerParentJob; - if (parentJob != null && parentJob.ExecutionError.Count > 0) + if (parentJob is not null && parentJob.ExecutionError.Count > 0) { foreach ( var e in diff --git a/src/System.Management.Automation/engine/remoting/commands/SuspendJob.cs b/src/System.Management.Automation/engine/remoting/commands/SuspendJob.cs index 1c729d8df74..99b8a2afcd4 100644 --- a/src/System.Management.Automation/engine/remoting/commands/SuspendJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/SuspendJob.cs @@ -251,7 +251,7 @@ private void HandleSuspendJobCompleted(object sender, AsyncCompletedEventArgs ev { Job job = sender as Job; - if (eventArgs.Error != null && eventArgs.Error is InvalidJobStateException) + if (eventArgs.Error is not null && eventArgs.Error is InvalidJobStateException) { _warnInvalidState = true; } @@ -283,12 +283,12 @@ private void ProcessExecutionErrorsAndReleaseWaitHandle(Job job) { job.StateChanged -= noWait_Job2_StateChanged; Job2 job2 = job as Job2; - if (job2 != null) + if (job2 is not null) job2.SuspendJobCompleted -= HandleSuspendJobCompleted; } var parentJob = job as ContainerParentJob; - if (parentJob != null && parentJob.ExecutionError.Count > 0) + if (parentJob is not null && parentJob.ExecutionError.Count > 0) { foreach ( var e in diff --git a/src/System.Management.Automation/engine/remoting/commands/WaitJob.cs b/src/System.Management.Automation/engine/remoting/commands/WaitJob.cs index 8755570d9ac..2e1f2e41f6e 100644 --- a/src/System.Management.Automation/engine/remoting/commands/WaitJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/WaitJob.cs @@ -82,7 +82,7 @@ public int Timeout private void SetEndProcessingAction(Action endProcessingAction) { - Dbg.Assert(endProcessingAction != null, "Caller should verify endProcessingAction != null"); + Dbg.Assert(endProcessingAction is not null, "Caller should verify endProcessingAction is not null"); lock (_endProcessingActionLock) { if (_endProcessingAction is null) @@ -105,7 +105,7 @@ private void InvokeEndProcessingAction() } // Invoke action outside lock. - if (endProcessingAction != null) + if (endProcessingAction is not null) { endProcessingAction(); } @@ -128,7 +128,7 @@ private void CleanUpEndProcessing() private void HandleJobStateChangedEvent(object source, JobStateEventArgs eventArgs) { Dbg.Assert(source is Job, "Caller should verify source is Job"); - Dbg.Assert(eventArgs != null, "Caller should verify eventArgs != null"); + Dbg.Assert(eventArgs is not null, "Caller should verify eventArgs is not null"); var job = (Job)source; lock (_jobTrackingLock) @@ -195,7 +195,7 @@ private void HandleJobStateChangedEvent(object source, JobStateEventArgs eventAr private void AddJobsThatNeedJobChangesTracking(IEnumerable jobsToAdd) { - Dbg.Assert(jobsToAdd != null, "Caller should verify jobs != null"); + Dbg.Assert(jobsToAdd is not null, "Caller should verify jobs is not null"); lock (_jobTrackingLock) { @@ -277,7 +277,7 @@ private void CleanUpTimeoutTracking() { lock (_timerLock) { - if (_timer != null) + if (_timer is not null) { _timer.Dispose(); _timer = null; @@ -359,7 +359,7 @@ protected override void EndProcessing() private void EndProcessingOutputSingleFinishedJob() { Job finishedJob = this.GetFinishedJobs().FirstOrDefault(); - if (finishedJob != null) + if (finishedJob is not null) { this.WriteObject(finishedJob); } diff --git a/src/System.Management.Automation/engine/remoting/commands/getrunspacecommand.cs b/src/System.Management.Automation/engine/remoting/commands/getrunspacecommand.cs index b80715973d9..265fcb6191e 100644 --- a/src/System.Management.Automation/engine/remoting/commands/getrunspacecommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/getrunspacecommand.cs @@ -439,7 +439,7 @@ private Collection GetConnectionObjects() connectionInfo.AppName = ApplicationName; connectionInfo.ShellUri = ConfigurationName; connectionInfo.Port = Port; - if (CertificateThumbprint != null) + if (CertificateThumbprint is not null) { connectionInfo.CertificateThumbprint = CertificateThumbprint; } @@ -462,7 +462,7 @@ private Collection GetConnectionObjects() WSManConnectionInfo connectionInfo = new WSManConnectionInfo(); connectionInfo.ConnectionUri = connectionUri; connectionInfo.ShellUri = ConfigurationName; - if (CertificateThumbprint != null) + if (CertificateThumbprint is not null) { connectionInfo.CertificateThumbprint = CertificateThumbprint; } @@ -501,7 +501,7 @@ private void UpdateConnectionInfo(WSManConnectionInfo connectionInfo) } // Update the connectionInfo object with passed in session options. - if (SessionOption != null) + if (SessionOption is not null) { connectionInfo.SetSessionOptions(SessionOption); } diff --git a/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs b/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs index e1ec5167777..259f6d7639c 100644 --- a/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs @@ -384,7 +384,7 @@ public void Dispose() /// private void OnRunspacePSEventReceived(object sender, PSEventArgs e) { - if (this.Events != null) + if (this.Events is not null) this.Events.AddForwardedEvent(e); } @@ -431,7 +431,7 @@ private void HandleRunspaceStateChanged(object sender, OperationStateEventArgs s // since we got state changed event..we dont need to listen on // URI redirections anymore - if (remoteRunspace != null) + if (remoteRunspace is not null) { remoteRunspace.URIRedirectionReported -= HandleURIDirectionReported; } @@ -474,11 +474,11 @@ private void HandleRunspaceStateChanged(object sender, OperationStateEventArgs s reason as PSRemotingTransportException; string errorDetails = null; int transErrorCode = 0; - if (transException != null) + if (transException is not null) { OpenRunspaceOperation senderAsOp = sender as OpenRunspaceOperation; transErrorCode = transException.ErrorCode; - if (senderAsOp != null) + if (senderAsOp is not null) { string host = senderAsOp.OperatedRunspace.ConnectionInfo.ComputerName; @@ -515,11 +515,11 @@ private void HandleRunspaceStateChanged(object sender, OperationStateEventArgs s // add host identification information in data structure handler message PSRemotingDataStructureException protoException = reason as PSRemotingDataStructureException; - if (protoException != null) + if (protoException is not null) { OpenRunspaceOperation senderAsOp = sender as OpenRunspaceOperation; - if (senderAsOp != null) + if (senderAsOp is not null) { string host = senderAsOp.OperatedRunspace.ConnectionInfo.ComputerName; @@ -552,11 +552,11 @@ private void HandleRunspaceStateChanged(object sender, OperationStateEventArgs s // In case of PSDirectException, we should output the precise error message // in inner exception instead of the generic one in outer exception. // - if ((errorRecord.Exception != null) && - (errorRecord.Exception.InnerException != null)) + if ((errorRecord.Exception is not null) && + (errorRecord.Exception.InnerException is not null)) { PSDirectException ex = errorRecord.Exception.InnerException as PSDirectException; - if (ex != null) + if (ex is not null) { errorRecord = new ErrorRecord(errorRecord.Exception.InnerException, errorRecord.FullyQualifiedErrorId, @@ -586,7 +586,7 @@ private void HandleRunspaceStateChanged(object sender, OperationStateEventArgs s "ConnectionUri", null); string message = GetMessage(RemotingErrorIdStrings.RemoteRunspaceClosed, - (connectionUri != null) ? + (connectionUri is not null) ? connectionUri.AbsoluteUri : string.Empty); Action verboseWriter = delegate (Cmdlet cmdlet) @@ -601,7 +601,7 @@ private void HandleRunspaceStateChanged(object sender, OperationStateEventArgs s // runspace may not have been opened in certain cases // like when the max memory is set to 25MB, in such // cases write an error record - if (reason != null) + if (reason is not null) { ErrorRecord errorRecord = new ErrorRecord(reason, "PSSessionStateClosed", @@ -670,7 +670,7 @@ private List CreateRunspacesWhenRunspaceParameterSpecified() WSManConnectionInfo originalWSManConnectionInfo = remoteRunspace.ConnectionInfo as WSManConnectionInfo; WSManConnectionInfo newWSManConnectionInfo = null; - if (originalWSManConnectionInfo != null) + if (originalWSManConnectionInfo is not null) { newWSManConnectionInfo = originalWSManConnectionInfo.Copy(); newWSManConnectionInfo.EnableNetworkAccess = (newWSManConnectionInfo.EnableNetworkAccess || EnableNetworkAccess) ? true : false; @@ -693,9 +693,9 @@ private List CreateRunspacesWhenRunspaceParameterSpecified() RemoteRunspacePoolInternal rrsPool = remoteRunspace.RunspacePool.RemoteRunspacePoolInternal; TypeTable typeTable = null; - if ((rrsPool != null) && - (rrsPool.DataStructureHandler != null) && - (rrsPool.DataStructureHandler.TransportManager != null)) + if ((rrsPool is not null) && + (rrsPool.DataStructureHandler is not null) && + (rrsPool.DataStructureHandler.TransportManager is not null)) { typeTable = rrsPool.DataStructureHandler.TransportManager.Fragmentor.TypeTable; } @@ -747,7 +747,7 @@ private List CreateRunspacesWhenUriParameterSpecified() WSManConnectionInfo connectionInfo = new WSManConnectionInfo(); connectionInfo.ConnectionUri = ConnectionUri[i]; connectionInfo.ShellUri = ConfigurationName; - if (CertificateThumbprint != null) + if (CertificateThumbprint is not null) { connectionInfo.CertificateThumbprint = CertificateThumbprint; } @@ -768,7 +768,7 @@ private List CreateRunspacesWhenUriParameterSpecified() Utils.GetTypeTableFromExecutionContextTLS(), connectionInfo, this.Host, this.SessionOption.ApplicationArguments, rsName, rsId); - Dbg.Assert(remoteRunspace != null, + Dbg.Assert(remoteRunspace is not null, "RemoteRunspace object created using URI is null"); remoteRunspaces.Add(remoteRunspace); @@ -823,7 +823,7 @@ private List CreateRunspacesWhenComputerNameParameterSpecified() connectionInfo.AppName = ApplicationName; connectionInfo.ShellUri = ConfigurationName; connectionInfo.Scheme = scheme; - if (CertificateThumbprint != null) + if (CertificateThumbprint is not null) { connectionInfo.CertificateThumbprint = CertificateThumbprint; } @@ -1186,7 +1186,7 @@ private string GetRunspaceName(int rsIndex, out int rsId) // runspace pool object, which in turn passes it on to the server during // construction. This way the friendly name can be returned when querying // the sever for disconnected sessions/runspaces. - if (Name != null && rsIndex < Name.Length) + if (Name is not null && rsIndex < Name.Length) { rsName = Name[rsIndex]; } @@ -1359,7 +1359,7 @@ internal override void StopOperation() } } - if (operationStateEventArgs != null) + if (operationStateEventArgs is not null) { FireEvent(operationStateEventArgs); } @@ -1451,7 +1451,7 @@ private void HandleRunspaceStateChanged(object source, RunspaceStateEventArgs st } } - if (operationStateEventArgs != null) + if (operationStateEventArgs is not null) { // Fire callbacks in list order. FireEvent(operationStateEventArgs); diff --git a/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs b/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs index 7b0f9659f96..f3605d565ea 100644 --- a/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs +++ b/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs @@ -97,7 +97,7 @@ internal static void CheckRemotingCmdletPrerequisites() // HKLM\Software\Microsoft\Windows\CurrentVersion\WSMAN\ServiceStackVersion string wsManStackValue = null; RegistryKey wsManKey = Registry.LocalMachine.OpenSubKey(WSManKeyPath); - if (wsManKey != null) + if (wsManKey is not null) { wsManStackValue = (string)wsManKey.GetValue("ServiceStackVersion"); } @@ -169,7 +169,7 @@ internal static void CheckHostRemotingPrerequisites() internal static void CheckPSVersion(Version version) { // PSVersion value can only be 2.0, 3.0, 4.0, 5.0, or 5.1 - if (version != null) + if (version is not null) { // PSVersion value can only be 2.0, 3.0, 4.0, 5.0, or 5.1 if (!(version.Major >= 2 && version.Major <= 4 && version.Minor == 0) && @@ -188,7 +188,7 @@ internal static void CheckPSVersion(Version version) internal static void CheckIfPowerShellVersionIsInstalled(Version version) { // Check if PowerShell 2.0 is installed - if (version != null && version.Major == 2) + if (version is not null && version.Major == 2) { #if CORECLR // PowerShell 2.0 is not available for CoreCLR diff --git a/src/System.Management.Automation/engine/remoting/commands/runspacerepository.cs b/src/System.Management.Automation/engine/remoting/commands/runspacerepository.cs index 3f1f20b4c6c..0b217ce2b60 100644 --- a/src/System.Management.Automation/engine/remoting/commands/runspacerepository.cs +++ b/src/System.Management.Automation/engine/remoting/commands/runspacerepository.cs @@ -42,7 +42,7 @@ internal RunspaceRepository() : base("runspace") /// protected override Guid GetKey(PSSession item) { - if (item != null) + if (item is not null) { return item.InstanceId; } diff --git a/src/System.Management.Automation/engine/remoting/common/DispatchTable.cs b/src/System.Management.Automation/engine/remoting/common/DispatchTable.cs index 50f49621367..c4e14948e85 100644 --- a/src/System.Management.Automation/engine/remoting/common/DispatchTable.cs +++ b/src/System.Management.Automation/engine/remoting/common/DispatchTable.cs @@ -70,7 +70,7 @@ private AsyncObject GetResponseAsyncObject(long callId) AsyncObject responseAsyncObject = null; Dbg.Assert(_responseAsyncObjects.ContainsKey(callId), "Expected _responseAsyncObjects.ContainsKey(callId)"); responseAsyncObject = _responseAsyncObjects[callId]; - Dbg.Assert(responseAsyncObject != null, "Expected responseAsyncObject != null"); + Dbg.Assert(responseAsyncObject is not null, "Expected responseAsyncObject is not null"); return responseAsyncObject; } @@ -117,7 +117,7 @@ internal T GetResponse(long callId, T defaultValue) /// internal void SetResponse(long callId, T remoteHostResponse) { - Dbg.Assert(remoteHostResponse != null, "Expected remoteHostResponse != null"); + Dbg.Assert(remoteHostResponse is not null, "Expected remoteHostResponse is not null"); lock (_responseAsyncObjects) { // The response-async-object might not exist if the call was aborted by Ctrl-C or if diff --git a/src/System.Management.Automation/engine/remoting/common/Indexer.cs b/src/System.Management.Automation/engine/remoting/common/Indexer.cs index 0f6b70482c8..b6150d283f9 100644 --- a/src/System.Management.Automation/engine/remoting/common/Indexer.cs +++ b/src/System.Management.Automation/engine/remoting/common/Indexer.cs @@ -39,7 +39,7 @@ public object Current /// internal Indexer(int[] lengths) { - Dbg.Assert(lengths != null, "Expected lengths != null"); + Dbg.Assert(lengths is not null, "Expected lengths is not null"); _lengths = lengths; Dbg.Assert(CheckLengthsNonNegative(lengths), "Expected CheckLengthsNonNegative(lengths)"); _current = new int[lengths.Length]; diff --git a/src/System.Management.Automation/engine/remoting/common/ObjectRef.cs b/src/System.Management.Automation/engine/remoting/common/ObjectRef.cs index d65a05b026a..6ba8aa40288 100644 --- a/src/System.Management.Automation/engine/remoting/common/ObjectRef.cs +++ b/src/System.Management.Automation/engine/remoting/common/ObjectRef.cs @@ -58,7 +58,7 @@ internal bool IsOverridden { get { - return _newValue != null; + return _newValue is not null; } } @@ -67,7 +67,7 @@ internal bool IsOverridden /// internal ObjectRef(T oldValue) { - Dbg.Assert(oldValue != null, "Expected oldValue != null"); + Dbg.Assert(oldValue is not null, "Expected oldValue is not null"); _oldValue = oldValue; } @@ -76,7 +76,7 @@ internal ObjectRef(T oldValue) /// internal void Override(T newValue) { - Dbg.Assert(newValue != null, "Expected newValue != null"); + Dbg.Assert(newValue is not null, "Expected newValue is not null"); _newValue = newValue; } diff --git a/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs b/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs index f0e562ac18c..8b2d272fb8b 100644 --- a/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs +++ b/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs @@ -255,7 +255,7 @@ public RemoteSessionHyperVSocketServer(bool LoopbackMode) // cause problem when we set up a second PowerShell Direct session. Let's // explicitly close listenSocket here for safe. // - if (listenSocket != null) + if (listenSocket is not null) { try { listenSocket.Dispose(); } catch (ObjectDisposedException) { } @@ -266,7 +266,7 @@ public RemoteSessionHyperVSocketServer(bool LoopbackMode) ex = e; } - if (ex != null) + if (ex is not null) { Dbg.Fail("Unexpected error in RemoteSessionHyperVSocketServer."); @@ -300,7 +300,7 @@ public void Dispose() IsDisposed = true; } - if (TextReader != null) + if (TextReader is not null) { try { TextReader.Dispose(); } catch (ObjectDisposedException) { } @@ -308,7 +308,7 @@ public void Dispose() TextReader = null; } - if (TextWriter != null) + if (TextWriter is not null) { try { TextWriter.Dispose(); } catch (ObjectDisposedException) { } @@ -316,13 +316,13 @@ public void Dispose() TextWriter = null; } - if (Stream != null) + if (Stream is not null) { try { Stream.Dispose(); } catch (ObjectDisposedException) { } } - if (HyperVSocket != null) + if (HyperVSocket is not null) { try { HyperVSocket.Dispose(); } catch (ObjectDisposedException) { } @@ -450,7 +450,7 @@ public void Dispose() IsDisposed = true; } - if (TextReader != null) + if (TextReader is not null) { try { TextReader.Dispose(); } catch (ObjectDisposedException) { } @@ -458,7 +458,7 @@ public void Dispose() TextReader = null; } - if (TextWriter != null) + if (TextWriter is not null) { try { TextWriter.Dispose(); } catch (ObjectDisposedException) { } @@ -466,13 +466,13 @@ public void Dispose() TextWriter = null; } - if (Stream != null) + if (Stream is not null) { try { Stream.Dispose(); } catch (ObjectDisposedException) { } } - if (HyperVSocket != null) + if (HyperVSocket is not null) { try { HyperVSocket.Dispose(); } catch (ObjectDisposedException) { } diff --git a/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs b/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs index 2aba46e2a9d..0fa904811f5 100644 --- a/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs +++ b/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs @@ -492,7 +492,7 @@ private NamedPipeServerStream CreateNamedPipe( // Create optional security attributes based on provided PipeSecurity. NamedPipeNative.SECURITY_ATTRIBUTES securityAttributes = null; GCHandle? securityDescHandle = null; - if (securityDesc != null) + if (securityDesc is not null) { byte[] securityDescBuffer = new byte[securityDesc.BinaryLength]; securityDesc.GetBinaryForm(securityDescBuffer, 0); @@ -512,7 +512,7 @@ private NamedPipeServerStream CreateNamedPipe( securityAttributes); int lastError = Marshal.GetLastWin32Error(); - if (securityDescHandle != null) + if (securityDescHandle is not null) { securityDescHandle.Value.Free(); } @@ -578,7 +578,7 @@ public void Dispose() IsDisposed = true; } - if (TextReader != null) + if (TextReader is not null) { try { TextReader.Dispose(); } catch (ObjectDisposedException) { } @@ -586,7 +586,7 @@ public void Dispose() TextReader = null; } - if (TextWriter != null) + if (TextWriter is not null) { try { TextWriter.Dispose(); } catch (ObjectDisposedException) { } @@ -594,7 +594,7 @@ public void Dispose() TextWriter = null; } - if (Stream != null) + if (Stream is not null) { try { Stream.Dispose(); } catch (ObjectDisposedException) { } @@ -613,7 +613,7 @@ public static void CreateCustomNamedPipeServer(string pipeName) { lock (s_syncObject) { - if (_customNamedPipeServer != null && !_customNamedPipeServer.IsDisposed) + if (_customNamedPipeServer is not null && !_customNamedPipeServer.IsDisposed) { if (pipeName == _customNamedPipeServer.PipeName) { @@ -801,7 +801,7 @@ private void ProcessListeningThread(object state) ex = e; } - if (ex != null) + if (ex is not null) { // Error during connection handling. Don't try to restart listening thread. string errorMessage = !string.IsNullOrEmpty(ex.Message) ? ex.Message : string.Empty; @@ -820,7 +820,7 @@ private void ProcessListeningThread(object state) try { Action clientConnectCallback = state as Action; - Dbg.Assert(clientConnectCallback != null, "Client callback should never be null."); + Dbg.Assert(clientConnectCallback is not null, "Client callback should never be null."); // Handle a new client connect by making the callback. // The callback must handle all exceptions except @@ -964,7 +964,7 @@ private static void CreateProcessExitHandler() { IPCNamedPipeServerEnabled = false; RemoteSessionNamedPipeServer namedPipeServer = IPCNamedPipeServer; - if (namedPipeServer != null) + if (namedPipeServer is not null) { try { @@ -1060,7 +1060,7 @@ public NamedPipeClientBase() /// public void Dispose() { - if (TextReader != null) + if (TextReader is not null) { try { TextReader.Dispose(); } catch (ObjectDisposedException) { } @@ -1068,7 +1068,7 @@ public void Dispose() TextReader = null; } - if (TextWriter != null) + if (TextWriter is not null) { try { TextWriter.Dispose(); } catch (ObjectDisposedException) { } @@ -1076,7 +1076,7 @@ public void Dispose() TextWriter = null; } - if (_clientPipeStream != null) + if (_clientPipeStream is not null) { try { _clientPipeStream.Dispose(); } catch (ObjectDisposedException) { } @@ -1112,7 +1112,7 @@ public void Connect( /// public void Close() { - if (_clientPipeStream != null) + if (_clientPipeStream is not null) { _clientPipeStream.Dispose(); } diff --git a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs index c1063b1f47e..322720821a1 100644 --- a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs +++ b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs @@ -284,12 +284,12 @@ public virtual void SetSessionOptions(PSSessionOption options) throw new ArgumentNullException(nameof(options)); } - if (options.Culture != null) + if (options.Culture is not null) { this.Culture = options.Culture; } - if (options.UICulture != null) + if (options.UICulture is not null) { this.UICulture = options.UICulture; } @@ -978,7 +978,7 @@ public override void SetSessionOptions(PSSessionOption options) throw new ArgumentNullException(nameof(options)); } - if ((options.ProxyAccessType == ProxyAccessType.None) && (options.ProxyCredential != null)) + if ((options.ProxyAccessType == ProxyAccessType.None) && (options.ProxyCredential is not null)) { string message = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.ProxyCredentialWithoutAccess, ProxyAccessType.None); @@ -1135,7 +1135,7 @@ internal static T ExtractPropertyAsWsManConnectionInfo(RunspaceConnectionInfo internal void SetConnectionUri(Uri newUri) { - Dbg.Assert(newUri != null, "newUri cannot be null."); + Dbg.Assert(newUri is not null, "newUri cannot be null."); _connectionUri = newUri; } @@ -1271,7 +1271,7 @@ internal static string GetConnectionString(Uri connectionUri, private void ValidateSpecifiedAuthentication() { if ((WSManAuthenticationMechanism != WSManAuthenticationMechanism.WSMAN_FLAG_DEFAULT_AUTHENTICATION) - && (_thumbPrint != null)) + && (_thumbPrint is not null)) { throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.NewRunspaceAmbiguousAuthentication, "CertificateThumbPrint", this.AuthenticationMechanism.ToString()); @@ -2056,10 +2056,10 @@ internal int StartSSHProcess( string sshCommand = "ssh.exe"; #endif var context = Runspaces.LocalPipeline.GetExecutionContextFromTLS(); - if (context != null) + if (context is not null) { var cmdInfo = context.CommandDiscovery.LookupCommandInfo(sshCommand, CommandOrigin.Internal) as ApplicationInfo; - if (cmdInfo != null) + if (cmdInfo is not null) { filePath = cmdInfo.Path; } @@ -2362,7 +2362,7 @@ private static unsafe void AllocNullTerminatedArray(string[] arr, ref byte** arr // Allocate the unmanaged array to hold each string pointer. // It needs to have an extra element to null terminate the array. arrPtr = (byte**)Marshal.AllocHGlobal(sizeof(IntPtr) * arrLength); - System.Diagnostics.Debug.Assert(arrPtr != null, "Invalid array ptr"); + System.Diagnostics.Debug.Assert(arrPtr is not null, "Invalid array ptr"); // Zero the memory so that if any of the individual string allocations fails, // we can loop through the array to free any that succeeded. @@ -2379,7 +2379,7 @@ private static unsafe void AllocNullTerminatedArray(string[] arr, ref byte** arr byte[] byteArr = System.Text.Encoding.UTF8.GetBytes(arr[i]); arrPtr[i] = (byte*)Marshal.AllocHGlobal(byteArr.Length + 1); // +1 for null termination - System.Diagnostics.Debug.Assert(arrPtr[i] != null, "Invalid array ptr"); + System.Diagnostics.Debug.Assert(arrPtr[i] is not null, "Invalid array ptr"); Marshal.Copy(byteArr, 0, (IntPtr)arrPtr[i], byteArr.Length); // copy over the data from the managed byte array arrPtr[i][byteArr.Length] = (byte)'\0'; // null terminate @@ -2388,12 +2388,12 @@ private static unsafe void AllocNullTerminatedArray(string[] arr, ref byte** arr private static unsafe void FreeArray(byte** arr, int length) { - if (arr != null) + if (arr is not null) { // Free each element of the array for (int i = 0; i < length; i++) { - if (arr[i] != null) + if (arr[i] is not null) { Marshal.FreeHGlobal((IntPtr)arr[i]); arr[i] = null; @@ -2452,12 +2452,12 @@ private static int StartSSHProcessImpl( catch (FileNotFoundException e) { ex = e; } catch (System.ComponentModel.Win32Exception e) { ex = e; } - if ((ex != null) || + if ((ex is not null) || (sshProcess is null) || (sshProcess.HasExited)) { throw new InvalidOperationException( - StringUtil.Format(RemotingErrorIdStrings.CannotStartSSHClient, (ex != null) ? ex.Message : string.Empty), + StringUtil.Format(RemotingErrorIdStrings.CannotStartSSHClient, (ex is not null) ? ex.Message : string.Empty), ex); } @@ -2473,11 +2473,11 @@ private static int StartSSHProcessImpl( } catch (Exception) { - if (stdInWriterVar != null) { stdInWriterVar.Dispose(); } else { stdInPipeServer.Dispose(); } + if (stdInWriterVar is not null) { stdInWriterVar.Dispose(); } else { stdInPipeServer.Dispose(); } - if (stdOutReaderVar != null) { stdInWriterVar.Dispose(); } else { stdOutPipeServer.Dispose(); } + if (stdOutReaderVar is not null) { stdInWriterVar.Dispose(); } else { stdOutPipeServer.Dispose(); } - if (stdErrReaderVar != null) { stdInWriterVar.Dispose(); } else { stdErrPipeServer.Dispose(); } + if (stdErrReaderVar is not null) { stdInWriterVar.Dispose(); } else { stdErrPipeServer.Dispose(); } throw; } @@ -2528,17 +2528,17 @@ private static Process CreateProcessWithRedirectedStd( } catch (Exception) { - if (stdInPipeServer != null) { stdInPipeServer.Dispose(); } + if (stdInPipeServer is not null) { stdInPipeServer.Dispose(); } - if (stdInPipeClient != null) { stdInPipeClient.Dispose(); } + if (stdInPipeClient is not null) { stdInPipeClient.Dispose(); } - if (stdOutPipeServer != null) { stdOutPipeServer.Dispose(); } + if (stdOutPipeServer is not null) { stdOutPipeServer.Dispose(); } - if (stdOutPipeClient != null) { stdOutPipeClient.Dispose(); } + if (stdOutPipeClient is not null) { stdOutPipeClient.Dispose(); } - if (stdErrPipeServer != null) { stdErrPipeServer.Dispose(); } + if (stdErrPipeServer is not null) { stdErrPipeServer.Dispose(); } - if (stdErrPipeClient != null) { stdErrPipeClient.Dispose(); } + if (stdErrPipeClient is not null) { stdErrPipeClient.Dispose(); } throw; } @@ -2604,17 +2604,17 @@ private static Process CreateProcessWithRedirectedStd( } catch (Exception) { - if (stdInPipeServer != null) { stdInPipeServer.Dispose(); } + if (stdInPipeServer is not null) { stdInPipeServer.Dispose(); } - if (stdInPipeClient != null) { stdInPipeClient.Dispose(); } + if (stdInPipeClient is not null) { stdInPipeClient.Dispose(); } - if (stdOutPipeServer != null) { stdOutPipeServer.Dispose(); } + if (stdOutPipeServer is not null) { stdOutPipeServer.Dispose(); } - if (stdOutPipeClient != null) { stdOutPipeClient.Dispose(); } + if (stdOutPipeClient is not null) { stdOutPipeClient.Dispose(); } - if (stdErrPipeServer != null) { stdErrPipeServer.Dispose(); } + if (stdErrPipeServer is not null) { stdErrPipeServer.Dispose(); } - if (stdErrPipeClient != null) { stdErrPipeClient.Dispose(); } + if (stdErrPipeClient is not null) { stdErrPipeClient.Dispose(); } throw; } @@ -2658,7 +2658,7 @@ private static SafePipeHandle CreateNamedPipe( // Create optional security attributes based on provided PipeSecurity. NamedPipeNative.SECURITY_ATTRIBUTES securityAttributes = null; GCHandle? securityDescHandle = null; - if (securityDesc != null) + if (securityDesc is not null) { byte[] securityDescBuffer = new byte[securityDesc.BinaryLength]; securityDesc.GetBinaryForm(securityDescBuffer, 0); @@ -2678,7 +2678,7 @@ private static SafePipeHandle CreateNamedPipe( securityAttributes); int lastError = Marshal.GetLastWin32Error(); - if (securityDescHandle != null) + if (securityDescHandle is not null) { securityDescHandle.Value.Free(); } @@ -3423,7 +3423,7 @@ private void GetContainerPropertiesInternal() // Since Hyper-V changed this from a property to a field, we can optimize for newest Windows to see if it's a field, // otherwise we fall back to old code to be compatible with older versions of Windows var fieldInfo = computeSystemPropertiesType.GetField("RuntimeId"); - if (fieldInfo != null) + if (fieldInfo is not null) { RuntimeId = (Guid)fieldInfo.GetValue(computeSystemPropertiesHandle); } @@ -3457,7 +3457,7 @@ private void GetContainerPropertiesInternal() } catch (Exception e) { - if (e.InnerException != null && + if (e.InnerException is not null && StringComparer.Ordinal.Equals( e.InnerException.GetType().FullName, "Microsoft.HostCompute.Interop.ObjectNotFoundException")) @@ -3498,7 +3498,7 @@ private string GetErrorMessageFromException(Exception e) { string errorMessage = e.Message; - if (e.InnerException != null) + if (e.InnerException is not null) { errorMessage += " " + e.InnerException.Message; } 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..73bc455cdeb 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs @@ -1014,7 +1014,7 @@ internal static RemoteDataObject GenerateGetCommandMetadata(ClientRemotePowerShe } } - Dbg.Assert(getCommand != null, "Whoever sets PowerShell.IsGetCommandMetadataSpecialPipeline needs to make sure Get-Command is present"); + Dbg.Assert(getCommand is not null, "Whoever sets PowerShell.IsGetCommandMetadataSpecialPipeline needs to make sure Get-Command is present"); string[] name = null; CommandTypes commandTypes = CommandTypes.Alias | CommandTypes.Cmdlet | CommandTypes.Function | CommandTypes.Filter | CommandTypes.Configuration; @@ -1047,7 +1047,7 @@ internal static RemoteDataObject GenerateGetCommandMetadata(ClientRemotePowerShe } RunspacePool rsPool = shell.PowerShell.GetRunspaceConnection() as RunspacePool; - Dbg.Assert(rsPool != null, "Runspacepool cannot be null for a CreatePowerShell request"); + Dbg.Assert(rsPool is not null, "Runspacepool cannot be null for a CreatePowerShell request"); Guid clientRunspacePoolId = rsPool.InstanceId; PSObject dataAsPSObject = CreateEmptyPSObject(); @@ -1096,7 +1096,7 @@ internal static RemoteDataObject GenerateCreatePowerShell(ClientRemotePowerShell RunspacePool rsPool = powerShell.GetRunspaceConnection() as RunspacePool; - Dbg.Assert(rsPool != null, "Runspacepool cannot be null for a CreatePowerShell request"); + Dbg.Assert(rsPool is not null, "Runspacepool cannot be null for a CreatePowerShell request"); clientRunspacePoolId = rsPool.InstanceId; @@ -1194,7 +1194,7 @@ internal static RemoteDataObject GenerateRunspacePoolStateInfo( dataAsPSObject.Properties.Add(stateProperty); // Add Reason property - if (stateInfo.Reason != null) + if (stateInfo.Reason is not null) { // If Reason is of not type IContainsErrorRecord, a new ErrorRecord is // created using this errorId @@ -1277,7 +1277,7 @@ internal static RemoteDataObject GenerateResetRunspaceState(Guid clientRunspaceP /// PS remoting protocol version. internal static Version GetPSRemotingProtocolVersion(RunspacePool rsPool) { - return (rsPool != null && rsPool.RemoteRunspacePoolInternal != null) ? + return (rsPool is not null && rsPool.RemoteRunspacePoolInternal is not null) ? rsPool.RemoteRunspacePoolInternal.PSRemotingProtocolVersion : null; } @@ -1513,7 +1513,7 @@ internal static RemoteDataObject GeneratePowerShellStateInfo(PSInvocationStateIn dataAsPSObject.Properties.Add(stateProperty); // Add exception property - if (stateInfo.Reason != null) + if (stateInfo.Reason is not null) { // If Reason is of not type IContainsErrorRecord, // a new ErrorRecord is created using this errorId @@ -1545,11 +1545,11 @@ internal static RemoteDataObject GeneratePowerShellStateInfo(PSInvocationStateIn /// internal static ErrorRecord GetErrorRecordFromException(Exception exception) { - Dbg.Assert(exception != null, "Caller should validate the data"); + Dbg.Assert(exception is not null, "Caller should validate the data"); ErrorRecord er = null; IContainsErrorRecord cer = exception as IContainsErrorRecord; - if (cer != null) + if (cer is not null) { er = cer.ErrorRecord; // Exception inside the error record is ParentContainsErrorRecordException which @@ -1569,7 +1569,7 @@ internal static ErrorRecord GetErrorRecordFromException(Exception exception) /// private static PSNoteProperty GetExceptionProperty(Exception exception, string errorId, ErrorCategory category) { - Dbg.Assert(exception != null, "Caller should validate the data"); + Dbg.Assert(exception is not null, "Caller should validate the data"); ErrorRecord er = GetErrorRecordFromException(exception) ?? new ErrorRecord(exception, errorId, category, null); @@ -1703,7 +1703,7 @@ private static T ConvertPropertyValueTo(string propertyName, object propertyV RemotingErrorIdStrings.CantCastPropertyToExpectedType, propertyName, typeof(T).FullName, - propertyValue != null ? propertyValue.GetType().FullName : "null"); + propertyValue is not null ? propertyValue.GetType().FullName : "null"); } else if (propertyValue is T) { @@ -1728,7 +1728,7 @@ private static T ConvertPropertyValueTo(string propertyName, object propertyV RemotingErrorIdStrings.CantCastPropertyToExpectedType, propertyName, typeof(T).FullName, - propertyValue != null ? propertyValue.GetType().FullName : "null"); + propertyValue is not null ? propertyValue.GetType().FullName : "null"); } } else @@ -1793,7 +1793,7 @@ internal static IEnumerable EnumerateListProperty(PSObject psObject, strin } IEnumerable e = GetPropertyValue(psObject, propertyName); - if (e != null) + if (e is not null) { foreach (object o in e) { @@ -1815,7 +1815,7 @@ internal static IEnumerable> EnumerateHashtable } Hashtable h = GetPropertyValue(psObject, propertyName); - if (h != null) + if (h is not null) { foreach (DictionaryEntry e in h) { @@ -2041,7 +2041,7 @@ private static Exception GetExceptionFromStateInfoObject(PSObject stateInfo) { // Check if exception is encoded as errorrecord PSPropertyInfo property = stateInfo.Properties[RemoteDataNameStrings.ExceptionAsErrorRecord]; - if (property != null && property.Value != null) + if (property is not null && property.Value is not null) { return GetExceptionFromSerializedErrorRecord(property.Value); } @@ -2219,7 +2219,7 @@ internal static PowerShell GetCommandDiscoveryPipeline(object data) CommandTypes commandType = GetPropertyValue(dataAsPSObject, RemoteDataNameStrings.DiscoveryType); string[] name; - if (GetPropertyValue(dataAsPSObject, RemoteDataNameStrings.DiscoveryName) != null) + if (GetPropertyValue(dataAsPSObject, RemoteDataNameStrings.DiscoveryName) is not null) { IEnumerable tmp = EnumerateListProperty(dataAsPSObject, RemoteDataNameStrings.DiscoveryName); name = new List(tmp).ToArray(); @@ -2230,7 +2230,7 @@ internal static PowerShell GetCommandDiscoveryPipeline(object data) } string[] module; - if (GetPropertyValue(dataAsPSObject, RemoteDataNameStrings.DiscoveryModule) != null) + if (GetPropertyValue(dataAsPSObject, RemoteDataNameStrings.DiscoveryModule) is not null) { IEnumerable tmp = EnumerateListProperty(dataAsPSObject, RemoteDataNameStrings.DiscoveryModule); module = new List(tmp).ToArray(); @@ -2243,14 +2243,14 @@ internal static PowerShell GetCommandDiscoveryPipeline(object data) ModuleSpecification[] fullyQualifiedName = null; if (DeserializingTypeConverter.GetPropertyValue(dataAsPSObject, RemoteDataNameStrings.DiscoveryFullyQualifiedModule, - DeserializingTypeConverter.RehydrationFlags.NullValueOk | DeserializingTypeConverter.RehydrationFlags.MissingPropertyOk) != null) + DeserializingTypeConverter.RehydrationFlags.NullValueOk | DeserializingTypeConverter.RehydrationFlags.MissingPropertyOk) is not null) { IEnumerable tmp = EnumerateListProperty(dataAsPSObject, RemoteDataNameStrings.DiscoveryFullyQualifiedModule); fullyQualifiedName = new List(tmp).ToArray(); } object[] argumentList; - if (GetPropertyValue(dataAsPSObject, RemoteDataNameStrings.DiscoveryArgumentList) != null) + if (GetPropertyValue(dataAsPSObject, RemoteDataNameStrings.DiscoveryArgumentList) is not null) { IEnumerable tmp = EnumerateListProperty(dataAsPSObject, RemoteDataNameStrings.DiscoveryArgumentList); argumentList = new List(tmp).ToArray(); @@ -2264,7 +2264,7 @@ internal static PowerShell GetCommandDiscoveryPipeline(object data) powerShell.AddCommand("Get-Command"); powerShell.AddParameter("Name", name); powerShell.AddParameter("CommandType", commandType); - if (fullyQualifiedName != null) + if (fullyQualifiedName is not null) { powerShell.AddParameter("FullyQualifiedModule", fullyQualifiedName); } @@ -2374,7 +2374,7 @@ internal static RemoteSessionCapability GetSessionCapability(object data) RemotingDestination.InvalidDestination, protocolVersion, psVersion, serializationVersion); - if (dataAsPSObject.Properties[RemoteDataNameStrings.TimeZone] != null) + if (dataAsPSObject.Properties[RemoteDataNameStrings.TimeZone] is not null) { // Binary deserialization of timezone info via BinaryFormatter is unsafe, // so don't deserialize any untrusted client data using this API. 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..0863cb15230 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHost.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHost.cs @@ -70,7 +70,7 @@ internal long CallId /// internal RemoteHostCall(long callId, RemoteHostMethodId methodId, object[] parameters) { - Dbg.Assert(parameters != null, "Expected parameters != null"); + Dbg.Assert(parameters is not null, "Expected parameters is not null"); _callId = callId; MethodId = methodId; Parameters = parameters; @@ -135,7 +135,7 @@ internal PSObject Encode() /// internal static RemoteHostCall Decode(PSObject data) { - Dbg.Assert(data != null, "Expected data != null"); + Dbg.Assert(data is not null, "Expected data is not null"); // Extract all the fields from data. long callId = RemotingDecoder.GetPropertyValue(data, RemoteDataNameStrings.CallId); @@ -188,7 +188,7 @@ internal void ExecuteVoidMethod(PSHost clientHost) } finally { - if (remoteRunspaceToClose != null) + if (remoteRunspaceToClose is not null) { remoteRunspaceToClose.Close(); } @@ -380,7 +380,7 @@ internal Collection PerformSecurityChecksOnHostMessage(string co fieldDesc.IsFromRemoteHost = true; Type fieldType = InternalHostUserInterface.GetFieldType(fieldDesc); - if (fieldType != null) + if (fieldType is not null) { if (fieldType == typeof(PSCredential)) { @@ -574,7 +574,7 @@ internal RemoteHostResponse(long callId, RemoteHostMethodId methodId, object ret /// internal object SimulateExecution() { - if (_exception != null) + if (_exception is not null) { throw _exception; } @@ -643,7 +643,7 @@ internal PSObject Encode() /// internal static RemoteHostResponse Decode(PSObject data) { - Dbg.Assert(data != null, "Expected data != null"); + Dbg.Assert(data is not null, "Expected data is not null"); // Extract all the fields from data. long callId = RemotingDecoder.GetPropertyValue(data, RemoteDataNameStrings.CallId); @@ -719,7 +719,7 @@ internal static Exception NewDecodingErrorForErrorRecordException() /// internal static Exception NewRemoteHostDataEncodingNotSupportedException(Type type) { - Dbg.Assert(type != null, "Expected type != null"); + Dbg.Assert(type is not null, "Expected type is not null"); return new PSRemotingDataStructureException( RemotingErrorIdStrings.RemoteHostDataEncodingNotSupported, type.ToString()); @@ -730,7 +730,7 @@ internal static Exception NewRemoteHostDataEncodingNotSupportedException(Type ty /// internal static Exception NewRemoteHostDataDecodingNotSupportedException(Type type) { - Dbg.Assert(type != null, "Expected type != null"); + Dbg.Assert(type is not null, "Expected type is not null"); return new PSRemotingDataStructureException( RemotingErrorIdStrings.RemoteHostDataDecodingNotSupported, type.ToString()); @@ -741,7 +741,7 @@ internal static Exception NewRemoteHostDataDecodingNotSupportedException(Type ty /// internal static Exception NewUnknownTargetClassException(string className) { - Dbg.Assert(className != null, "Expected className != null"); + Dbg.Assert(className is not null, "Expected className is not null"); return new PSRemotingDataStructureException(RemotingErrorIdStrings.UnknownTargetClass, className); } 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..0ded35f163f 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHostEncoder.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHostEncoder.cs @@ -32,7 +32,7 @@ internal class RemoteHostEncoder private static bool IsKnownType(Type type) { TypeSerializationInfo info = KnownTypes.GetTypeSerializationInfo(type); - return (info != null); + return (info is not null); } /// @@ -412,7 +412,7 @@ internal static object DecodeObject(object obj, Type type) return null; } - Dbg.Assert(type != null, "Expected type != null"); + Dbg.Assert(type is not null, "Expected type is not null"); if (type == typeof(PSObject)) { return DecodePSObject(obj); @@ -510,8 +510,8 @@ internal static object DecodeObject(object obj, Type type) /// internal static void EncodeAndAddAsProperty(PSObject psObject, string propertyName, object propertyValue) { - Dbg.Assert(psObject != null, "Expected psObject != null"); - Dbg.Assert(propertyName != null, "Expected propertyName != null"); + Dbg.Assert(psObject is not null, "Expected psObject is not null"); + Dbg.Assert(propertyName is not null, "Expected propertyName is not null"); if (propertyValue is null) { return; @@ -525,9 +525,9 @@ internal static void EncodeAndAddAsProperty(PSObject psObject, string propertyNa /// internal static object DecodePropertyValue(PSObject psObject, string propertyName, Type propertyValueType) { - Dbg.Assert(psObject != null, "Expected psObject != null"); - Dbg.Assert(propertyName != null, "Expected propertyName != null"); - Dbg.Assert(propertyValueType != null, "Expected propertyValueType != null"); + Dbg.Assert(psObject is not null, "Expected psObject is not null"); + Dbg.Assert(propertyName is not null, "Expected propertyName is not null"); + Dbg.Assert(propertyValueType is not null, "Expected propertyValueType is not null"); ReadOnlyPSMemberInfoCollection matches = psObject.Properties.Match(propertyName); if (matches.Count == 0) { @@ -624,7 +624,7 @@ private static bool ArrayIsZeroBased(Array array) /// private static PSObject EncodeArray(Array array) { - Dbg.Assert(array != null, "Expected array != null"); + Dbg.Assert(array is not null, "Expected array is not null"); Dbg.Assert(ArrayIsZeroBased(array), "Expected ArrayIsZeroBased(array)"); Type arrayType = array.GetType(); Type elementType = arrayType.GetElementType(); 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..a3d43fac899 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs @@ -129,7 +129,7 @@ internal static byte[] GetCurrentTimeZoneInByteFormat() // if there is any exception serializing the timezone information // ignore it and dont try to serialize again. - if (e != null) + if (e is not null) { _timeZoneInByteFormat = Array.Empty(); } diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemotingDataObject.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemotingDataObject.cs index 664c2a91ae0..246f3992386 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemotingDataObject.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemotingDataObject.cs @@ -136,8 +136,8 @@ internal static RemoteDataObject CreateFrom(RemotingDestination destination, /// internal static RemoteDataObject CreateFrom(Stream serializedDataStream, Fragmentor defragmentor) { - Dbg.Assert(serializedDataStream != null, "cannot construct a RemoteDataObject from null data"); - Dbg.Assert(defragmentor != null, "defragmentor cannot be null."); + Dbg.Assert(serializedDataStream is not null, "cannot construct a RemoteDataObject from null data"); + Dbg.Assert(defragmentor is not null, "defragmentor cannot be null."); if ((serializedDataStream.Length - serializedDataStream.Position) < headerLength) { @@ -177,11 +177,11 @@ internal static RemoteDataObject CreateFrom(Stream serializedDataStream, Frag /// internal virtual void Serialize(Stream streamToWriteTo, Fragmentor fragmentor) { - Dbg.Assert(streamToWriteTo != null, "Stream to write to cannot be null."); - Dbg.Assert(fragmentor != null, "Fragmentor cannot be null."); + Dbg.Assert(streamToWriteTo is not null, "Stream to write to cannot be null."); + Dbg.Assert(fragmentor is not null, "Fragmentor cannot be null."); SerializeHeader(streamToWriteTo); - if (Data != null) + if (Data is not null) { fragmentor.SerializeToBytes(Data, streamToWriteTo); } @@ -199,7 +199,7 @@ internal virtual void Serialize(Stream streamToWriteTo, Fragmentor fragmentor) /// private void SerializeHeader(Stream streamToWriteTo) { - Dbg.Assert(streamToWriteTo != null, "stream to write to cannot be null"); + Dbg.Assert(streamToWriteTo is not null, "stream to write to cannot be null"); // Serialize destination SerializeUInt((uint)Destination, streamToWriteTo); @@ -215,7 +215,7 @@ private void SerializeHeader(Stream streamToWriteTo) private void SerializeUInt(uint data, Stream streamToWriteTo) { - Dbg.Assert(streamToWriteTo != null, "stream to write to cannot be null"); + Dbg.Assert(streamToWriteTo is not null, "stream to write to cannot be null"); byte[] result = new byte[4]; // size of int @@ -243,7 +243,7 @@ private static uint DeserializeUInt(Stream serializedDataStream) private void SerializeGuid(Guid guid, Stream streamToWriteTo) { - Dbg.Assert(streamToWriteTo != null, "stream to write to cannot be null"); + Dbg.Assert(streamToWriteTo is not null, "stream to write to cannot be null"); byte[] guidArray = guid.ToByteArray(); diff --git a/src/System.Management.Automation/engine/remoting/common/fragmentor.cs b/src/System.Management.Automation/engine/remoting/common/fragmentor.cs index 0fc927fe3f2..7089667d990 100644 --- a/src/System.Management.Automation/engine/remoting/common/fragmentor.cs +++ b/src/System.Management.Automation/engine/remoting/common/fragmentor.cs @@ -98,7 +98,7 @@ internal FragmentedRemoteObject() internal FragmentedRemoteObject(byte[] blob, long objectId, long fragmentId, bool isEndFragment) { - Dbg.Assert((blob != null) || (blob.Length == 0), "Cannot create a fragment for null or empty data."); + Dbg.Assert((blob is not null) || (blob.Length == 0), "Cannot create a fragment for null or empty data."); Dbg.Assert(objectId >= 0, "Object Id cannot be < 0"); Dbg.Assert(fragmentId >= 0, "Fragment Id cannot be < 0"); @@ -160,7 +160,7 @@ internal byte[] Blob set { - Dbg.Assert(value != null, "Blob cannot be null"); + Dbg.Assert(value is not null, "Blob cannot be null"); _blob = value; } } @@ -277,7 +277,7 @@ internal byte[] GetBytes() /// internal static long GetObjectId(byte[] fragmentBytes, int startIndex) { - Dbg.Assert(fragmentBytes != null, "fragmentBytes cannot be null"); + Dbg.Assert(fragmentBytes is not null, "fragmentBytes cannot be null"); Dbg.Assert(fragmentBytes.Length >= HeaderLength, "not enough data to decode object id"); long objectId = 0; @@ -311,7 +311,7 @@ internal static long GetObjectId(byte[] fragmentBytes, int startIndex) /// internal static long GetFragmentId(byte[] fragmentBytes, int startIndex) { - Dbg.Assert(fragmentBytes != null, "fragmentBytes cannot be null"); + Dbg.Assert(fragmentBytes is not null, "fragmentBytes cannot be null"); Dbg.Assert(fragmentBytes.Length >= HeaderLength, "not enough data to decode fragment id"); long fragmentId = 0; int idx = startIndex + _fragmentIdOffset; @@ -346,7 +346,7 @@ internal static long GetFragmentId(byte[] fragmentBytes, int startIndex) /// internal static bool GetIsStartFragment(byte[] fragmentBytes, int startIndex) { - Dbg.Assert(fragmentBytes != null, "fragment cannot be null"); + Dbg.Assert(fragmentBytes is not null, "fragment cannot be null"); Dbg.Assert(fragmentBytes.Length >= HeaderLength, "not enough data to decode if it is a start fragment."); if ((fragmentBytes[startIndex + _flagsOffset] & SFlag) != 0) @@ -375,7 +375,7 @@ internal static bool GetIsStartFragment(byte[] fragmentBytes, int startIndex) /// internal static bool GetIsEndFragment(byte[] fragmentBytes, int startIndex) { - Dbg.Assert(fragmentBytes != null, "fragment cannot be null"); + Dbg.Assert(fragmentBytes is not null, "fragment cannot be null"); Dbg.Assert(fragmentBytes.Length >= HeaderLength, "not enough data to decode if it is an end fragment."); if ((fragmentBytes[startIndex + _flagsOffset] & EFlag) != 0) @@ -404,7 +404,7 @@ internal static bool GetIsEndFragment(byte[] fragmentBytes, int startIndex) /// internal static int GetBlobLength(byte[] fragmentBytes, int startIndex) { - Dbg.Assert(fragmentBytes != null, "fragment cannot be null"); + Dbg.Assert(fragmentBytes is not null, "fragment cannot be null"); Dbg.Assert(fragmentBytes.Length >= HeaderLength, "not enough data to decode blob length."); int blobLength = 0; @@ -506,7 +506,7 @@ internal SerializedDataStream(int fragmentSize) internal SerializedDataStream(int fragmentSize, OnDataAvailableCallback callbackToNotify) : this(fragmentSize) { - if (callbackToNotify != null) + if (callbackToNotify is not null) { _notifyOnWriteFragmentImmediately = true; _onDataAvailableCallback = callbackToNotify; @@ -811,7 +811,7 @@ private void WriteCurrentFragmentAndReset() } // call the callback since we have data available - if (_onDataAvailableCallback != null) + if (_onDataAvailableCallback is not null) { _onDataAvailableCallback(data, _currentFragment.IsEndFragment); } @@ -864,12 +864,12 @@ protected override void Dispose(bool disposing) } } - if ((_readStream != null) && (_readStream.CanRead)) + if ((_readStream is not null) && (_readStream.CanRead)) { _readStream.Dispose(); } - if ((_writeStream != null) && (_writeStream.CanRead)) + if ((_writeStream is not null) && (_writeStream.CanRead)) { _writeStream.Dispose(); } @@ -1006,8 +1006,8 @@ internal Fragmentor(int fragmentSize, PSRemotingCryptoHelper cryptoHelper) /// internal void Fragment(RemoteDataObject obj, SerializedDataStream dataToBeSent) { - Dbg.Assert(obj != null, "Cannot fragment a null object"); - Dbg.Assert(dataToBeSent != null, "SendDataCollection cannot be null"); + Dbg.Assert(obj is not null, "Cannot fragment a null object"); + Dbg.Assert(dataToBeSent is not null, "SendDataCollection cannot be null"); dataToBeSent.Enter(); try @@ -1053,8 +1053,8 @@ internal int FragmentSize /// internal void SerializeToBytes(object obj, Stream streamToWriteTo) { - Dbg.Assert(obj != null, "Cannot serialize a null object"); - Dbg.Assert(streamToWriteTo != null, "Stream to write to cannot be null"); + Dbg.Assert(obj is not null, "Cannot serialize a null object"); + Dbg.Assert(streamToWriteTo is not null, "Stream to write to cannot be null"); XmlWriterSettings xmlSettings = new XmlWriterSettings(); xmlSettings.CheckCharacters = false; @@ -1094,7 +1094,7 @@ internal void SerializeToBytes(object obj, Stream streamToWriteTo) /// internal PSObject DeserializeToPSObject(Stream serializedDataStream) { - Dbg.Assert(serializedDataStream != null, "Cannot Deserialize null data"); + Dbg.Assert(serializedDataStream is not null, "Cannot Deserialize null data"); Dbg.Assert(serializedDataStream.Length != 0, "Cannot Deserialize empty data"); object result = null; diff --git a/src/System.Management.Automation/engine/remoting/common/misc.cs b/src/System.Management.Automation/engine/remoting/common/misc.cs index 5afa294acda..b155ea0ebd2 100644 --- a/src/System.Management.Automation/engine/remoting/common/misc.cs +++ b/src/System.Management.Automation/engine/remoting/common/misc.cs @@ -13,7 +13,7 @@ internal sealed class RemoteSessionNegotiationEventArgs : EventArgs internal RemoteSessionNegotiationEventArgs(RemoteSessionCapability remoteSessionCapability) { - Dbg.Assert(remoteSessionCapability != null, "caller should validate the parameter"); + Dbg.Assert(remoteSessionCapability is not null, "caller should validate the parameter"); if (remoteSessionCapability is null) { @@ -46,7 +46,7 @@ internal sealed class RemoteDataEventArgs : EventArgs internal RemoteDataEventArgs(RemoteDataObject receivedData) { - Dbg.Assert(receivedData != null, "caller should validate the parameter"); + Dbg.Assert(receivedData is not null, "caller should validate the parameter"); if (receivedData is null) { @@ -88,7 +88,7 @@ internal sealed class RemoteDataEventArgs : EventArgs internal RemoteDataEventArgs(object data) { - // Dbg.Assert(data != null, "data passed should not be null"); + // Dbg.Assert(data is not null, "data passed should not be null"); Data = (T)data; } @@ -310,7 +310,7 @@ internal class RemoteSessionStateEventArgs : EventArgs internal RemoteSessionStateEventArgs(RemoteSessionStateInfo remoteSessionStateInfo) { - Dbg.Assert(remoteSessionStateInfo != null, "caller should validate the parameter"); + Dbg.Assert(remoteSessionStateInfo is not null, "caller should validate the parameter"); if (remoteSessionStateInfo is null) { diff --git a/src/System.Management.Automation/engine/remoting/common/psstreamobject.cs b/src/System.Management.Automation/engine/remoting/common/psstreamobject.cs index af48748cba8..a5199e6ce68 100644 --- a/src/System.Management.Automation/engine/remoting/common/psstreamobject.cs +++ b/src/System.Management.Automation/engine/remoting/common/psstreamobject.cs @@ -102,7 +102,7 @@ public PSStreamObject(PSStreamObjectType objectType, object value) : /// Used by Receive-Job to suppress inquire preference. public void WriteStreamObject(Cmdlet cmdlet, bool overrideInquire = false) { - if (cmdlet != null) + if (cmdlet is not null) { switch (this.ObjectType) { @@ -118,7 +118,7 @@ public void WriteStreamObject(Cmdlet cmdlet, bool overrideInquire = false) ErrorRecord errorRecord = (ErrorRecord)this.Value; errorRecord.PreserveInvocationInfoOnce = true; MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) + if (mshCommandRuntime is not null) { mshCommandRuntime.WriteError(errorRecord, overrideInquire); } @@ -131,7 +131,7 @@ public void WriteStreamObject(Cmdlet cmdlet, bool overrideInquire = false) string debug = (string)Value; DebugRecord debugRecord = new DebugRecord(debug); MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) + if (mshCommandRuntime is not null) { mshCommandRuntime.WriteDebug(debugRecord, overrideInquire); } @@ -144,7 +144,7 @@ public void WriteStreamObject(Cmdlet cmdlet, bool overrideInquire = false) string warning = (string)Value; WarningRecord warningRecord = new WarningRecord(warning); MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) + if (mshCommandRuntime is not null) { mshCommandRuntime.WriteWarning(warningRecord, overrideInquire); } @@ -157,7 +157,7 @@ public void WriteStreamObject(Cmdlet cmdlet, bool overrideInquire = false) string verbose = (string)Value; VerboseRecord verboseRecord = new VerboseRecord(verbose); MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) + if (mshCommandRuntime is not null) { mshCommandRuntime.WriteVerbose(verboseRecord, overrideInquire); } @@ -168,7 +168,7 @@ public void WriteStreamObject(Cmdlet cmdlet, bool overrideInquire = false) case PSStreamObjectType.Progress: { MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) + if (mshCommandRuntime is not null) { mshCommandRuntime.WriteProgress((ProgressRecord)Value, overrideInquire); } @@ -179,7 +179,7 @@ public void WriteStreamObject(Cmdlet cmdlet, bool overrideInquire = false) case PSStreamObjectType.Information: { MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) + if (mshCommandRuntime is not null) { mshCommandRuntime.WriteInformation((InformationRecord)Value, overrideInquire); } @@ -191,7 +191,7 @@ public void WriteStreamObject(Cmdlet cmdlet, bool overrideInquire = false) { WarningRecord warningRecord = (WarningRecord)Value; MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) + if (mshCommandRuntime is not null) { mshCommandRuntime.AppendWarningVarList(warningRecord); } @@ -272,7 +272,7 @@ internal void WriteStreamObject(Cmdlet cmdlet, Guid instanceId, bool overrideInq if (instanceId != Guid.Empty) { PSObject o = Value as PSObject; - if (o != null) + if (o is not null) AddSourceJobNoteProperty(o, instanceId); } @@ -290,7 +290,7 @@ internal void WriteStreamObject(Cmdlet cmdlet, Guid instanceId, bool overrideInq { // if we get a base ErrorRecord object, check if the computerName is // populated in the RecommendedAction field - if (errorRecord.ErrorDetails != null && !string.IsNullOrEmpty(errorRecord.ErrorDetails.RecommendedAction)) + if (errorRecord.ErrorDetails is not null && !string.IsNullOrEmpty(errorRecord.ErrorDetails.RecommendedAction)) { string computerName; Guid jobInstanceId; @@ -309,7 +309,7 @@ internal void WriteStreamObject(Cmdlet cmdlet, Guid instanceId, bool overrideInq errorRecord.PreserveInvocationInfoOnce = true; MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) + if (mshCommandRuntime is not null) { mshCommandRuntime.WriteError(errorRecord, overrideInquire); } @@ -322,7 +322,7 @@ internal void WriteStreamObject(Cmdlet cmdlet, Guid instanceId, bool overrideInq string warning = (string)Value; WarningRecord warningRecord = new WarningRecord(warning); MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) + if (mshCommandRuntime is not null) { mshCommandRuntime.WriteWarning(warningRecord, overrideInquire); } @@ -335,7 +335,7 @@ internal void WriteStreamObject(Cmdlet cmdlet, Guid instanceId, bool overrideInq string verbose = (string)Value; VerboseRecord verboseRecord = new VerboseRecord(verbose); MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) + if (mshCommandRuntime is not null) { mshCommandRuntime.WriteVerbose(verboseRecord, overrideInquire); } @@ -363,7 +363,7 @@ internal void WriteStreamObject(Cmdlet cmdlet, Guid instanceId, bool overrideInq } MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) + if (mshCommandRuntime is not null) { mshCommandRuntime.WriteProgress(progressRecord, overrideInquire); } @@ -376,7 +376,7 @@ internal void WriteStreamObject(Cmdlet cmdlet, Guid instanceId, bool overrideInq string debug = (string)Value; DebugRecord debugRecord = new DebugRecord(debug); MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) + if (mshCommandRuntime is not null) { mshCommandRuntime.WriteDebug(debugRecord, overrideInquire); } @@ -409,7 +409,7 @@ internal void WriteStreamObject(Cmdlet cmdlet, Guid instanceId, bool overrideInq } MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) + if (mshCommandRuntime is not null) { mshCommandRuntime.WriteInformation(informationRecord, overrideInquire); } @@ -446,7 +446,7 @@ internal void WriteStreamObject(Cmdlet cmdlet, bool writeSourceIdentifier, bool private static void InvokeCmdletMethodAndWaitForResults(CmdletMethodInvoker cmdletMethodInvoker, Cmdlet cmdlet) { - Dbg.Assert(cmdletMethodInvoker != null, "Caller should verify cmdletMethodInvoker != null"); + Dbg.Assert(cmdletMethodInvoker is not null, "Caller should verify cmdletMethodInvoker is not null"); cmdletMethodInvoker.MethodResult = default(T); try @@ -468,7 +468,7 @@ private static void InvokeCmdletMethodAndWaitForResults(CmdletMethodInvoker(CmdletMethodInvoker operations) // add items to the queue foreach (IThrottleOperation operation in operations) { - Dbg.Assert(operation != null, + Dbg.Assert(operation is not null, "Operation submitComplete to throttle manager cannot be null"); _operationsQueue.Add(operation); } @@ -270,7 +270,7 @@ internal void AddOperation(IThrottleOperation operation) // is not set to true (happens when EndSubmitOperations is called) if (!_submitComplete) { - Dbg.Assert(operation != null, + Dbg.Assert(operation is not null, "Operation submitComplete to throttle manager cannot be null"); _operationsQueue.Add(operation); @@ -466,7 +466,7 @@ private void OperationCompleteHandler(object source, OperationStateEventArgs sta { IThrottleOperation operation = source as IThrottleOperation; - Dbg.Assert(operation != null, "Source of event should not be null"); + Dbg.Assert(operation is not null, "Source of event should not be null"); int index = -1; @@ -532,7 +532,7 @@ private void StartOneOperationFromQueue() } } - if (operation != null) + if (operation is not null) { operation.StartOperation(); } diff --git a/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs index a6dd940a4fc..eb35aaf9901 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs @@ -287,7 +287,7 @@ internal void ProcessRawData(byte[] data, string stream, ReceiveDataCollection.OnDataAvailableCallback dataAvailableCallback) { - Dbg.Assert(data != null, "Cannot process null data"); + Dbg.Assert(data is not null, "Cannot process null data"); s_baseTracer.WriteLine("Processing incoming data for stream {0}.", stream); @@ -699,14 +699,14 @@ internal void EnqueueAndStartProcessingThread(RemoteDataObject remoteO lock (_callbackNotificationQueue) { - if ((remoteObject != null) || (transportErrorArgs != null) || (privateData != null)) + if ((remoteObject is not null) || (transportErrorArgs is not null) || (privateData is not null)) { CallbackNotificationInformation rcvdDataInfo = new CallbackNotificationInformation(); rcvdDataInfo.remoteObject = remoteObject; rcvdDataInfo.transportError = transportErrorArgs; rcvdDataInfo.privateData = privateData; - if (remoteObject != null && (remoteObject.DataType == RemotingDataType.PublicKey || + if (remoteObject is not null && (remoteObject.DataType == RemotingDataType.PublicKey || remoteObject.DataType == RemotingDataType.EncryptedSessionKey || remoteObject.DataType == RemotingDataType.PublicKeyRequest)) { @@ -761,7 +761,7 @@ private bool CheckForInteractiveHostCall(RemoteDataObject remoteObject { bool interactiveHostCall = false; - if ((remoteObject != null) && + if ((remoteObject is not null) && (remoteObject.DataType == RemotingDataType.RemoteHostCallUsingPowerShellHost)) { RemoteHostMethodId methodId = 0; @@ -826,15 +826,15 @@ internal void ServicePendingCallbacks(object objectToProcess) rcvdDataInfo = _callbackNotificationQueue.Dequeue(); } // Handle callback. - if (rcvdDataInfo != null) + if (rcvdDataInfo is not null) { // Handling transport exception in thread-pool thread - if (rcvdDataInfo.transportError != null) + if (rcvdDataInfo.transportError is not null) { RaiseErrorHandler(rcvdDataInfo.transportError); break; } - else if (rcvdDataInfo.privateData != null) + else if (rcvdDataInfo.privateData is not null) { ProcessPrivateData(rcvdDataInfo.privateData); } @@ -1320,7 +1320,7 @@ internal void SendDataToClient(RemoteDataObject data, bool flush, bool rep Fragmentor.Fragment(dataToBeSent, serializedData); } - if ((_dataToBeSentQueue != null) && (_dataToBeSentQueue.Count > 0)) + if ((_dataToBeSentQueue is not null) && (_dataToBeSentQueue.Count > 0)) { Tuple dataToBeSentQueueItem = _dataToBeSentQueue.Dequeue(); dataToBeSent = dataToBeSentQueueItem.Item1; @@ -1331,7 +1331,7 @@ internal void SendDataToClient(RemoteDataObject data, bool flush, bool rep { dataToBeSent = null; } - } while (dataToBeSent != null); + } while (dataToBeSent is not null); } finally { @@ -1342,7 +1342,7 @@ internal void SendDataToClient(RemoteDataObject data, bool flush, bool rep private void OnDataAvailable(byte[] dataToSend, bool isEndFragment) { - Dbg.Assert(dataToSend != null, "ServerTransportManager cannot send null fragment"); + Dbg.Assert(dataToSend is not null, "ServerTransportManager cannot send null fragment"); // log to crimson log. PSEtwLog.LogAnalyticInformational(PSEventId.ServerSendData, PSOpcode.Send, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, diff --git a/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs b/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs index 0860207ab83..dde2244807a 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs @@ -159,7 +159,7 @@ private void Update(string optionName, string optionValue) /// private void AssertValueNotAssigned(string optionName, object originalValue) { - if (originalValue != null) + if (originalValue is not null) { throw PSTraceSource.NewArgumentException(optionName, RemotingErrorIdStrings.DuplicateInitializationParameterFound, optionName, INITPARAMETERSTOKEN); @@ -479,7 +479,7 @@ private static void LoadRSConfigProvider(string shellId, string initializationPa configData.ApplicationBase, configData.AssemblyName, configData.EndPointConfigurationTypeName); - Dbg.Assert(endPointConfigType != null, "EndPointConfiguration type cannot be null"); + Dbg.Assert(endPointConfigType is not null, "EndPointConfiguration type cannot be null"); configData.EndPointConfigurationType = endPointConfigType; lock (s_syncObject) { @@ -534,7 +534,7 @@ private static Type LoadAndAnalyzeAssembly(string shellId, string applicationBas } // configuration xml specified an assembly and typetoload. - if (assembly != null) + if (assembly is not null) { try { @@ -659,7 +659,7 @@ private static Assembly LoadSsnStateProviderAssembly(string applicationBase, str s_tracer.TraceWarning("Not able to load assembly {0}: {1}", assemblyName, e.Message); } - if (result != null) + if (result is not null) { return result; } @@ -760,7 +760,7 @@ private static string ReadStringValue(RegistryKey registryKey, string name, bool mandatory) { Dbg.Assert(!string.IsNullOrEmpty(name), "caller should validate the name parameter"); - Dbg.Assert(registryKey != null, "Caller should validate the registryKey parameter"); + Dbg.Assert(registryKey is not null, "Caller should validate the registryKey parameter"); object value = registryKey.GetValue(name); if (value is null && mandatory) @@ -806,7 +806,7 @@ public override InitialSessionState GetInitialSessionState(PSSenderInfo senderIn { InitialSessionState result = InitialSessionState.CreateDefault2(); // TODO: Remove this after RDS moved to $using - if (senderInfo.ConnectionString != null && senderInfo.ConnectionString.Contains("MSP=7a83d074-bb86-4e52-aa3e-6cc73cc066c8")) { PSSessionConfigurationData.IsServerManager = true; } + if (senderInfo.ConnectionString is not null && senderInfo.ConnectionString.Contains("MSP=7a83d074-bb86-4e52-aa3e-6cc73cc066c8")) { PSSessionConfigurationData.IsServerManager = true; } return result; } @@ -824,12 +824,12 @@ public override InitialSessionState GetInitialSessionState(PSSessionConfiguratio InitialSessionState sessionState = InitialSessionState.CreateDefault2(); // now get all the modules in the specified path and import the same - if (sessionConfigurationData != null && sessionConfigurationData.ModulesToImportInternal != null) + if (sessionConfigurationData is not null && sessionConfigurationData.ModulesToImportInternal is not null) { foreach (var module in sessionConfigurationData.ModulesToImportInternal) { var moduleName = module as string; - if (moduleName != null) + if (moduleName is not null) { moduleName = Environment.ExpandEnvironmentVariables(moduleName); @@ -838,7 +838,7 @@ public override InitialSessionState GetInitialSessionState(PSSessionConfiguratio else { var moduleSpec = module as ModuleSpecification; - if (moduleSpec != null) + if (moduleSpec is not null) { var modulesToImport = new Collection { moduleSpec }; sessionState.ImportPSModule(modulesToImport); @@ -848,7 +848,7 @@ public override InitialSessionState GetInitialSessionState(PSSessionConfiguratio } // TODO: Remove this after RDS moved to $using - if (senderInfo.ConnectionString != null && senderInfo.ConnectionString.Contains("MSP=7a83d074-bb86-4e52-aa3e-6cc73cc066c8")) { PSSessionConfigurationData.IsServerManager = true; } + if (senderInfo.ConnectionString is not null && senderInfo.ConnectionString.Contains("MSP=7a83d074-bb86-4e52-aa3e-6cc73cc066c8")) { PSSessionConfigurationData.IsServerManager = true; } return sessionState; } @@ -1797,7 +1797,7 @@ private void MergeRoleCapabilitiesIntoConfigHash() { string[] roleCapabilities = TryGetStringArray(_configHash[ConfigFileConstants.RoleCapabilities]); - if (roleCapabilities != null) + if (roleCapabilities is not null) { foreach (string roleCapability in roleCapabilities) { @@ -1818,7 +1818,7 @@ private void MergeRoleCapabilitiesIntoConfigHash() if (ConfigHash.ContainsKey(ConfigFileConstants.RoleCapabilityFiles)) { string[] roleCapabilityFiles = TryGetStringArray(ConfigHash[ConfigFileConstants.RoleCapabilityFiles]); - if (roleCapabilityFiles != null) + if (roleCapabilityFiles is not null) { foreach (var roleCapabilityFilePath in roleCapabilityFiles) { @@ -1864,7 +1864,7 @@ private void MergeConfigHashIntoConfigHash(IDictionary childConfigHash) if (_configHash.ContainsKey(customizationString)) { IEnumerable existingValueAsCollection = LanguagePrimitives.GetEnumerable(_configHash[customization]); - if (existingValueAsCollection != null) + if (existingValueAsCollection is not null) { foreach (object value in existingValueAsCollection) { @@ -1879,7 +1879,7 @@ private void MergeConfigHashIntoConfigHash(IDictionary childConfigHash) // Then add the current role's values IEnumerable newValueAsCollection = LanguagePrimitives.GetEnumerable(childConfigHash[customization]); - if (newValueAsCollection != null) + if (newValueAsCollection is not null) { foreach (object value in newValueAsCollection) { @@ -2002,7 +2002,7 @@ public override InitialSessionState GetInitialSessionState(PSSenderInfo senderIn { string[] providers = TryGetStringArray(_configHash[ConfigFileConstants.VisibleProviders]); - if (providers != null) + if (providers is not null) { System.Collections.Generic.HashSet addedProviders = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (string provider in providers) @@ -2030,7 +2030,7 @@ public override InitialSessionState GetInitialSessionState(PSSenderInfo senderIn { string[] assemblies = TryGetStringArray(_configHash[ConfigFileConstants.AssembliesToLoad]); - if (assemblies != null) + if (assemblies is not null) { foreach (string assembly in assemblies) { @@ -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] is not null) && (modules is null)) { string message = StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeStringOrHashtableArray, ConfigFileConstants.ModulesToImport); @@ -2053,7 +2053,7 @@ public override InitialSessionState GetInitialSessionState(PSSenderInfo senderIn throw ioe; } - if (modules != null) + if (modules is not null) { Collection modulesToImport = new Collection(); foreach (object module in modules) @@ -2067,14 +2067,14 @@ public override InitialSessionState GetInitialSessionState(PSSenderInfo senderIn else { Hashtable moduleHash = module as Hashtable; - if (moduleHash != null) + if (moduleHash is not null) { moduleSpec = new ModuleSpecification(moduleHash); } } // Now add the moduleSpec to modulesToImport - if (moduleSpec != null) + if (moduleSpec is not null) { if (string.Equals(InitialSessionState.CoreModule, moduleSpec.Name, StringComparison.OrdinalIgnoreCase)) @@ -2123,17 +2123,17 @@ public override InitialSessionState GetInitialSessionState(PSSenderInfo senderIn { Hashtable[] aliases = TryGetHashtableArray(_configHash[ConfigFileConstants.AliasDefinitions]); - if (aliases != null) + if (aliases is not null) { foreach (Hashtable alias in aliases) { SessionStateAliasEntry entry = CreateSessionStateAliasEntry(alias, aliasVisibilityApplied); - if (entry != null) + if (entry is not null) { // Indexing iss.Commands with a command that does not exist returns 'null', rather // than some sort of KeyNotFound exception. - if (iss.Commands[entry.Name] != null) + if (iss.Commands[entry.Name] is not null) { iss.Commands.Remove(entry.Name, typeof(SessionStateAliasEntry)); } @@ -2148,7 +2148,7 @@ public override InitialSessionState GetInitialSessionState(PSSenderInfo senderIn { string[] aliases = DISCPowerShellConfiguration.TryGetStringArray(_configHash[ConfigFileConstants.VisibleAliases]); - if (aliases != null) + if (aliases is not null) { foreach (string alias in aliases) { @@ -2180,13 +2180,13 @@ public override InitialSessionState GetInitialSessionState(PSSenderInfo senderIn { Hashtable[] functions = TryGetHashtableArray(_configHash[ConfigFileConstants.FunctionDefinitions]); - if (functions != null) + if (functions is not null) { foreach (Hashtable function in functions) { SessionStateFunctionEntry entry = CreateSessionStateFunctionEntry(function, functionVisibilityApplied); - if (entry != null) + if (entry is not null) { iss.Commands.Add(entry); } @@ -2216,12 +2216,12 @@ public override InitialSessionState GetInitialSessionState(PSSenderInfo senderIn { Hashtable[] variables = TryGetHashtableArray(_configHash[ConfigFileConstants.VariableDefinitions]); - if (variables != null) + if (variables is not null) { foreach (Hashtable variable in variables) { if (variable.ContainsKey(ConfigFileConstants.VariableValueToken) && - ((variable[ConfigFileConstants.VariableValueToken] as ScriptBlock) != null)) + ((variable[ConfigFileConstants.VariableValueToken] as ScriptBlock) is not null)) { iss.DynamicVariablesToDefine.Add(variable); continue; @@ -2229,7 +2229,7 @@ public override InitialSessionState GetInitialSessionState(PSSenderInfo senderIn SessionStateVariableEntry entry = CreateSessionStateVariableEntry(variable, iss.LanguageMode); - if (entry != null) + if (entry is not null) { iss.Variables.Add(entry); } @@ -2241,7 +2241,7 @@ public override InitialSessionState GetInitialSessionState(PSSenderInfo senderIn { Hashtable[] variablesList = TryGetHashtableArray(_configHash[ConfigFileConstants.EnvironmentVariables]); - if (variablesList != null) + if (variablesList is not null) { foreach (Hashtable variables in variablesList) { @@ -2259,7 +2259,7 @@ public override InitialSessionState GetInitialSessionState(PSSenderInfo senderIn { string[] types = DISCPowerShellConfiguration.TryGetStringArray(_configHash[ConfigFileConstants.TypesToProcess]); - if (types != null) + if (types is not null) { foreach (string type in types) { @@ -2276,7 +2276,7 @@ public override InitialSessionState GetInitialSessionState(PSSenderInfo senderIn { string[] formats = DISCPowerShellConfiguration.TryGetStringArray(_configHash[ConfigFileConstants.FormatsToProcess]); - if (formats != null) + if (formats is not null) { foreach (string format in formats) { @@ -2292,7 +2292,7 @@ public override InitialSessionState GetInitialSessionState(PSSenderInfo senderIn if (_configHash.ContainsKey(ConfigFileConstants.VisibleExternalCommands)) { string[] externalCommands = TryGetStringArray(_configHash[ConfigFileConstants.VisibleExternalCommands]); - if (externalCommands != null) + if (externalCommands is not null) { foreach (string command in externalCommands) { @@ -2321,7 +2321,7 @@ public override InitialSessionState GetInitialSessionState(PSSenderInfo senderIn { string[] startupScripts = DISCPowerShellConfiguration.TryGetStringArray(_configHash[ConfigFileConstants.ScriptsToProcess]); - if (startupScripts != null) + if (startupScripts is not null) { foreach (string script in startupScripts) { @@ -2395,7 +2395,7 @@ public override InitialSessionState GetInitialSessionState(PSSenderInfo senderIn if (Convert.ToBoolean(_configHash[ConfigFileConstants.MountUserDrive], CultureInfo.InvariantCulture)) { iss.UserDriveEnabled = true; - iss.UserDriveUserName = (senderInfo != null) ? senderInfo.UserInfo.Identity.Name : null; + iss.UserDriveUserName = (senderInfo is not null) ? senderInfo.UserInfo.Identity.Name : null; // Set user drive max drive if provided. if (_configHash.ContainsKey(ConfigFileConstants.UserDriveMaxSize)) @@ -2477,7 +2477,7 @@ private static void ProcessVisibleCommands(InitialSessionState iss, object[] com // (I.e.: Exposed parameter with ValidateSet and / or ValidatePattern) // Collect these so that we can post-process them. IDictionary commandModification = commandObject as IDictionary; - if (commandModification != null) + if (commandModification is not null) { ProcessCommandModification(commandModifications, commandModification); } @@ -2501,7 +2501,7 @@ private static void ProcessCommandModification(Dictionary com { parameters = TryGetHashtableArray(commandModification["Parameters"]); - if (parameters != null) + if (parameters is not null) { // Validate that the parameter restriction has the right keys foreach (Hashtable parameter in parameters) @@ -2785,7 +2785,7 @@ internal static Hashtable[] TryGetHashtableArray(object hashObj) // Scalar case Hashtable hashtable = hashObj as Hashtable; - if (hashtable != null) + if (hashtable is not null) { return new[] { hashtable }; } @@ -2798,7 +2798,7 @@ internal static Hashtable[] TryGetHashtableArray(object hashObj) // 2. Convert from object array object[] objArray = hashObj as object[]; - if (objArray != null) + if (objArray is not null) { hashArray = new Hashtable[objArray.Length]; @@ -2833,7 +2833,7 @@ internal static string[] TryGetStringArray(object hashObj) // Scalar case object obj = hashObj as object; - if (obj != null) + if (obj is not null) { return new string[] { obj.ToString() }; } @@ -2860,7 +2860,7 @@ internal static T[] TryGetObjectsOfType(object hashObj, IEnumerable typ { // Scalar case object obj = hashObj; - if (obj != null) + if (obj is not null) { foreach (Type type in types) { diff --git a/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs index a692267cc6d..aec693f3a46 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs @@ -215,7 +215,7 @@ internal static void ProcessData(string data, DataProcessingDelegates callbacks) /// private static void ProcessElement(XmlReader xmlReader, DataProcessingDelegates callbacks) { - Dbg.Assert(xmlReader != null, "xmlReader cannot be null."); + Dbg.Assert(xmlReader is not null, "xmlReader cannot be null."); Dbg.Assert(xmlReader.NodeType == XmlNodeType.Element, "xmlReader's NodeType should be of type Element"); PowerShellTraceSource tracer = PowerShellTraceSourceFactory.GetTraceSource(); @@ -416,7 +416,7 @@ internal class OutOfProcessTextWriter /// internal OutOfProcessTextWriter(TextWriter writerToWrap) { - Dbg.Assert(writerToWrap != null, "Cannot wrap a null writer."); + Dbg.Assert(writerToWrap is not null, "Cannot wrap a null writer."); _writer = writerToWrap; } @@ -608,7 +608,7 @@ internal override BaseClientCommandTransportManager CreateClientCommandTransport ClientRemotePowerShell cmd, bool noInput) { - Dbg.Assert(cmd != null, "Cmd cannot be null"); + Dbg.Assert(cmd is not null, "Cmd cannot be null"); OutOfProcessClientCommandTransportManager result = new OutOfProcessClientCommandTransportManager(cmd, noInput, this, stdInWriter); @@ -851,7 +851,7 @@ protected void SendOneItem() // This will either return data or register callback but doesn't do both. byte[] data = dataToBeSent.ReadOrRegisterCallback(_onDataAvailableToSendCallback, out priorityType); - if (data != null) + if (data is not null) { SendData(data, priorityType); } @@ -859,7 +859,7 @@ protected void SendOneItem() private void OnDataAvailableCallback(byte[] data, DataPriorityType priorityType) { - Dbg.Assert(data != null, "data cannot be null in the data available callback"); + Dbg.Assert(data is not null, "data cannot be null in the data available callback"); tracer.WriteLine("Received data to be sent from the callback."); SendData(data, priorityType); @@ -924,7 +924,7 @@ private void OnDataPacketReceived(byte[] rawData, string stream, Guid psGuid) { // this is for a command OutOfProcessClientCommandTransportManager cmdTM = GetCommandTransportManager(psGuid); - if (cmdTM != null) + if (cmdTM is not null) { // not throwing the exception in null case as the command might have already // closed. The RS data structure handler does not wait for the close ack before @@ -945,7 +945,7 @@ private void OnDataAckPacketReceived(Guid psGuid) { // this is for a command OutOfProcessClientCommandTransportManager cmdTM = GetCommandTransportManager(psGuid); - if (cmdTM != null) + if (cmdTM is not null) { // not throwing the exception in null case as the command might have already // closed. The RS data structure handler does not wait for the close ack before @@ -995,7 +995,7 @@ private void OnSignalAckPacketReceived(Guid psGuid) else { OutOfProcessClientCommandTransportManager cmdTM = GetCommandTransportManager(psGuid); - if (cmdTM != null) + if (cmdTM is not null) { cmdTM.OnRemoteCmdSignalCompleted(); } @@ -1028,7 +1028,7 @@ private void OnCloseAckReceived(Guid psGuid) _tracer.WriteMessage("OutOfProcessClientSessionTransportManager.OnCloseAckReceived, in progress command count should be greater than zero: " + commandCount + ", RunSpacePool Id : " + this.RunspacePoolInstanceId + ", psGuid : " + psGuid.ToString()); OutOfProcessClientCommandTransportManager cmdTM = GetCommandTransportManager(psGuid); - if (cmdTM != null) + if (cmdTM is not null) { // this might legitimately happen if cmd is already closed before we get an // ACK back from server. @@ -1087,14 +1087,14 @@ internal OutOfProcessClientSessionTransportManager(Guid runspaceId, /// internal override void CreateAsync() { - if (_connectionInfo != null) + if (_connectionInfo is not null) { _processInstance = _connectionInfo.Process ?? new PowerShellProcessInstance(_connectionInfo.PSVersion, _connectionInfo.Credential, _connectionInfo.InitializationScript, _connectionInfo.RunAs32, _connectionInfo.WorkingDirectory); - if (_connectionInfo.Process != null) + if (_connectionInfo.Process is not null) { _processCreated = false; } @@ -1116,7 +1116,7 @@ internal override void CreateAsync() // Attach handlers and start the process _serverProcess = _processInstance.Process; - if (_processInstance.RunspacePool != null) + if (_processInstance.RunspacePool is not null) { _processInstance.RunspacePool.Close(); _processInstance.RunspacePool.Dispose(); @@ -1174,7 +1174,7 @@ private void ProcessOutputData(object arg) try { string data = reader.ReadLine(); - while (data != null) + while (data is not null) { HandleOutputDataReceived(data); data = reader.ReadLine(); @@ -1207,7 +1207,7 @@ private void ProcessErrorData(object arg) try { string data = reader.ReadLine(); - while (data != null) + while (data is not null) { HandleErrorDataReceived(data); data = reader.ReadLine(); @@ -1243,7 +1243,7 @@ internal override void Dispose(bool isDisposing) if (isDisposing) { KillServerProcess(); - if (_serverProcess != null && _processCreated) + if (_serverProcess is not null && _processCreated) { // null can happen if Dispose is called before ConnectAsync() _serverProcess.Dispose(); @@ -1332,7 +1332,7 @@ internal override void Dispose(bool isDisposing) if (isDisposing) { - if (_client != null) + if (_client is not null) { _client.Dispose(); } @@ -1362,7 +1362,7 @@ protected void ProcessReaderThread(object state) try { StreamReader reader = state as StreamReader; - Dbg.Assert(reader != null, "Reader cannot be null."); + Dbg.Assert(reader is not null, "Reader cannot be null."); // Send one fragment. SendOneItem(); @@ -1407,7 +1407,7 @@ protected void ProcessReaderThread(object state) Dbg.Assert(false, "Need to adjust transport fragmentor to accomodate read buffer size."); } - string errorMsg = (e.Message != null) ? e.Message : string.Empty; + string errorMsg = (e.Message is not null) ? e.Message : string.Empty; _tracer.WriteMessage("HyperVSocketClientSessionTransportManager", "StartReaderThread", Guid.Empty, "Transport manager reader thread ended with error: {0}", errorMsg); @@ -1654,13 +1654,13 @@ internal override void CloseAsync() private void CloseConnection() { var stdInWriter = Interlocked.Exchange(ref _stdInWriter, null); - if (stdInWriter != null) { stdInWriter.Dispose(); } + if (stdInWriter is not null) { stdInWriter.Dispose(); } var stdOutReader = Interlocked.Exchange(ref _stdOutReader, null); - if (stdOutReader != null) { stdOutReader.Dispose(); } + if (stdOutReader is not null) { stdOutReader.Dispose(); } var stdErrReader = Interlocked.Exchange(ref _stdErrReader, null); - if (stdErrReader != null) { stdErrReader.Dispose(); } + if (stdErrReader is not null) { stdErrReader.Dispose(); } // The CloseConnection() method can be called multiple times from multiple places. // Set the _sshProcessId to zero here so that we go through the work of finding @@ -1671,7 +1671,7 @@ private void CloseConnection() try { var sshProcess = System.Diagnostics.Process.GetProcessById(sshProcessId); - if ((sshProcess != null) && (sshProcess.Handle != IntPtr.Zero) && !sshProcess.HasExited) + if ((sshProcess is not null) && (sshProcess.Handle != IntPtr.Zero) && !sshProcess.HasExited) { sshProcess.Kill(); } @@ -1697,7 +1697,7 @@ private void ProcessErrorThread(object state) try { StreamReader reader = state as StreamReader; - Dbg.Assert(reader != null, "Reader cannot be null."); + Dbg.Assert(reader is not null, "Reader cannot be null."); while (true) { @@ -1723,7 +1723,7 @@ private void ProcessErrorThread(object state) } catch (Exception e) { - string errorMsg = (e.Message != null) ? e.Message : string.Empty; + string errorMsg = (e.Message is not null) ? e.Message : string.Empty; _tracer.WriteMessage("SSHClientSessionTransportManager", "ProcessErrorThread", Guid.Empty, "Transport manager error thread ended with error: {0}", errorMsg); @@ -1770,7 +1770,7 @@ private static string ReadError(StreamReader reader) try { var task = reader.ReadLineAsync(); - if (task.Wait(1000) && (task.Result != null)) + if (task.Wait(1000) && (task.Result is not null)) { sb.Append(Environment.NewLine); sb.Append(task.Result); @@ -1803,7 +1803,7 @@ private void ProcessReaderThread(object state) try { StreamReader reader = state as StreamReader; - Dbg.Assert(reader != null, "Reader cannot be null."); + Dbg.Assert(reader is not null, "Reader cannot be null."); // Send one fragment. SendOneItem(); @@ -1847,7 +1847,7 @@ private void ProcessReaderThread(object state) Dbg.Assert(false, "Need to adjust transport fragmentor to accomodate read buffer size."); } - string errorMsg = (e.Message != null) ? e.Message : string.Empty; + string errorMsg = (e.Message is not null) ? e.Message : string.Empty; _tracer.WriteMessage("SSHClientSessionTransportManager", "ProcessReaderThread", Guid.Empty, "Transport manager reader thread ended with error: {0}", errorMsg); } @@ -1895,7 +1895,7 @@ internal override void Dispose(bool isDisposing) if (isDisposing) { - if (_clientPipe != null) + if (_clientPipe is not null) { _clientPipe.Dispose(); } @@ -1929,7 +1929,7 @@ private void ProcessReaderThread(object state) try { StreamReader reader = state as StreamReader; - Dbg.Assert(reader != null, "Reader cannot be null."); + Dbg.Assert(reader is not null, "Reader cannot be null."); // Send one fragment. SendOneItem(); @@ -1974,7 +1974,7 @@ private void ProcessReaderThread(object state) Dbg.Assert(false, "Need to adjust transport fragmentor to accommodate read buffer size."); } - string errorMsg = (e.Message != null) ? e.Message : string.Empty; + string errorMsg = (e.Message is not null) ? e.Message : string.Empty; _tracer.WriteMessage("NamedPipeClientSessionTransportManager", "StartReaderThread", Guid.Empty, "Transport manager reader thread ended with error: {0}", errorMsg); } @@ -2042,7 +2042,7 @@ internal override void CreateAsync() /// public void AbortConnect() { - if (_clientPipe != null) + if (_clientPipe is not null) { _clientPipe.AbortConnect(); } @@ -2185,7 +2185,7 @@ internal override void CloseAsync() RunspacePoolInstanceId.ToString(), powershellInstanceId.ToString()); // Send Close information to the server - if (_stdInWriter != null) + if (_stdInWriter is not null) { try { @@ -2341,7 +2341,7 @@ private void StopSignalTimerAndDecrementOperations() /// internal override void ProcessPrivateData(object privateData) { - Dbg.Assert(privateData != null, "privateData cannot be null."); + Dbg.Assert(privateData is not null, "privateData cannot be null."); // For this version...only a boolean can be used for privateData. bool shouldRaiseSignalCompleted = (bool)privateData; @@ -2379,7 +2379,7 @@ private void SendOneItem() data = dataToBeSent.ReadOrRegisterCallback(_onDataAvailableToSendCallback, out priorityType); } - if (data != null) + if (data is not null) { SendData(data, priorityType); } @@ -2409,7 +2409,7 @@ private void SendData(byte[] data, DataPriorityType priorityType) private void OnDataAvailableCallback(byte[] data, DataPriorityType priorityType) { - Dbg.Assert(data != null, "data cannot be null in the data available callback"); + Dbg.Assert(data is not null, "data cannot be null in the data available callback"); tracer.WriteLine("Received data from dataToBeSent store."); SendData(data, priorityType); @@ -2437,8 +2437,8 @@ internal class OutOfProcessServerSessionTransportManager : AbstractServerSession internal OutOfProcessServerSessionTransportManager(OutOfProcessTextWriter outWriter, OutOfProcessTextWriter errWriter, PSRemotingCryptoHelperServer cryptoHelper) : base(BaseTransportManager.DefaultFragmentSize, cryptoHelper) { - Dbg.Assert(outWriter != null, "outWriter cannot be null."); - Dbg.Assert(errWriter != null, "errWriter cannot be null."); + Dbg.Assert(outWriter is not null, "outWriter cannot be null."); + Dbg.Assert(errWriter is not null, "errWriter cannot be null."); _stdOutWriter = outWriter; _stdErrWriter = errWriter; _cmdTransportManagers = new Dictionary(); diff --git a/src/System.Management.Automation/engine/remoting/fanin/PSPrincipal.cs b/src/System.Management.Automation/engine/remoting/fanin/PSPrincipal.cs index a8a99d4e072..aa5a7bc8f7a 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/PSPrincipal.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/PSPrincipal.cs @@ -219,7 +219,7 @@ IIdentity IPrincipal.Identity /// public bool IsInRole(string role) { - if (WindowsIdentity != null) + if (WindowsIdentity is not null) { // Get Windows Principal for this identity WindowsPrincipal windowsPrincipal = new WindowsPrincipal(WindowsIdentity); @@ -236,7 +236,7 @@ public bool IsInRole(string role) /// internal bool IsInRole(WindowsBuiltInRole role) { - if (WindowsIdentity != null) + if (WindowsIdentity is not null) { // Get Windows Principal for this identity WindowsPrincipal windowsPrincipal = new WindowsPrincipal(WindowsIdentity); diff --git a/src/System.Management.Automation/engine/remoting/fanin/PSSessionConfigurationData.cs b/src/System.Management.Automation/engine/remoting/fanin/PSSessionConfigurationData.cs index 51932ead4c6..790c8476bea 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/PSSessionConfigurationData.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/PSSessionConfigurationData.cs @@ -164,7 +164,7 @@ internal static PSSessionConfigurationData Create(string configurationData) /// private static void AssertValueNotAssigned(string optionName, object originalValue) { - if (originalValue != null) + if (originalValue is not null) { throw PSTraceSource.NewArgumentException(optionName, RemotingErrorIdStrings.DuplicateInitializationParameterFound, optionName, SessionConfigToken); @@ -193,7 +193,7 @@ private void Update(string optionName, string optionValue) foreach (var module in modulesToImport) { var s = module as string; - if (s != null) + if (s is not null) { _modulesToImport.Add(s.Trim()); diff --git a/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs b/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs index 8612fbf0cdf..d9e638fd0a7 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs @@ -92,7 +92,7 @@ internal Fragmentor Fragmentor set { - Dbg.Assert(value != null, "Fragmentor cannot be null."); + Dbg.Assert(value is not null, "Fragmentor cannot be null."); _fragmentor = value; // create serialized streams using fragment size. string[] names = Enum.GetNames(typeof(DataPriorityType)); @@ -121,9 +121,9 @@ internal Fragmentor Fragmentor /// internal void Add(RemoteDataObject data, DataPriorityType priority) { - Dbg.Assert(data != null, "Cannot send null data object"); - Dbg.Assert(_fragmentor != null, "Fragmentor cannot be null while adding objects"); - Dbg.Assert(_dataToBeSent != null, "Serialized streams are not initialized"); + Dbg.Assert(data is not null, "Cannot send null data object"); + Dbg.Assert(_fragmentor is not null, "Fragmentor cannot be null while adding objects"); + Dbg.Assert(_dataToBeSent is not null, "Serialized streams are not initialized"); // make sure the only one object is fragmented and added to the collection // at any give time. This way the order of fragment is maintained @@ -161,14 +161,14 @@ internal void Clear() causing an unhandled exception in finalize and a process crash. Verify arrays and dataToBeSent objects before referencing. */ - if (_dataSyncObjects != null && _dataToBeSent != null) + if (_dataSyncObjects is not null && _dataToBeSent is not null) { int promptResponseIndex = (int)DataPriorityType.PromptResponse; int defaultIndex = (int)DataPriorityType.Default; lock (_dataSyncObjects[promptResponseIndex]) { - if (_dataToBeSent[promptResponseIndex] != null) + if (_dataToBeSent[promptResponseIndex] is not null) { _dataToBeSent[promptResponseIndex].Dispose(); _dataToBeSent[promptResponseIndex] = null; @@ -177,7 +177,7 @@ Verify arrays and dataToBeSent objects before referencing. lock (_dataSyncObjects[defaultIndex]) { - if (_dataToBeSent[defaultIndex] != null) + if (_dataToBeSent[defaultIndex] is not null) { _dataToBeSent[defaultIndex].Dispose(); _dataToBeSent[defaultIndex] = null; @@ -253,13 +253,13 @@ private void OnDataAvailable(byte[] data, bool isEndFragment) _isHandlingCallback = true; } - if (_onDataAvailableCallback != null) + if (_onDataAvailableCallback is not null) { DataPriorityType prType; // now get the fragment and call the callback.. byte[] result = ReadOrRegisterCallback(_onDataAvailableCallback, out prType); - if (result != null) + if (result is not null) { // reset the onDataAvailableCallback so that we dont notify // multiple times. we are resetting before actually calling @@ -356,7 +356,7 @@ internal class ReceiveDataCollection : IDisposable /// internal ReceiveDataCollection(Fragmentor defragmentor, bool createdByClientTM) { - Dbg.Assert(defragmentor != null, "ReceiveDataCollection needs a defragmentor to work with"); + Dbg.Assert(defragmentor is not null, "ReceiveDataCollection needs a defragmentor to work with"); // Memory streams created with an unsigned byte array provide a non-resizable stream view // of the data, and can only be written to. When using a byte array, you can neither append @@ -431,8 +431,8 @@ internal void PrepareForStreamConnect() /// internal void ProcessRawData(byte[] data, OnDataAvailableCallback callback) { - Dbg.Assert(data != null, "Cannot process null data"); - Dbg.Assert(callback != null, "Callback cannot be null"); + Dbg.Assert(data is not null, "Cannot process null data"); + Dbg.Assert(callback is not null, "Callback cannot be null"); lock (_syncObject) { @@ -568,7 +568,7 @@ internal void ProcessRawData(byte[] data, OnDataAvailableCallback callback) // reset incoming stream. _pendingDataStream.Dispose(); _pendingDataStream = new MemoryStream(); - if (extraData != null) + if (extraData is not null) { _pendingDataStream.Write(extraData, 0, extraData.Length); } @@ -673,7 +673,7 @@ internal void ProcessRawData(byte[] data, OnDataAvailableCallback callback) private void ResetReceiveData() { // reset resources used to store incoming data (for a single object) - if (_dataToProcessStream != null) + if (_dataToProcessStream is not null) { _dataToProcessStream.Dispose(); } @@ -685,13 +685,13 @@ private void ResetReceiveData() private void ReleaseResources() { - if (_pendingDataStream != null) + if (_pendingDataStream is not null) { _pendingDataStream.Dispose(); _pendingDataStream = null; } - if (_dataToProcessStream != null) + if (_dataToProcessStream is not null) { _dataToProcessStream.Dispose(); _dataToProcessStream = null; @@ -855,7 +855,7 @@ internal void ProcessRawData(byte[] data, DataPriorityType priorityType, ReceiveDataCollection.OnDataAvailableCallback callback) { - Dbg.Assert(data != null, "Cannot process null data"); + Dbg.Assert(data is not null, "Cannot process null data"); try { @@ -902,7 +902,7 @@ public void Dispose() internal virtual void Dispose(bool isDisposing) { - if (_recvdData != null) + if (_recvdData is not null) { for (int index = 0; index < _recvdData.Length; index++) { diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs index 1b1fe2b2163..47157d6443a 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs @@ -344,7 +344,7 @@ internal WSManUserNameAuthenticationCredentials(string name, _cred = new WSManUserNameCredentialStruct(); _cred.authenticationMechanism = authMechanism; _cred.userName = name; - if (pwd != null) + if (pwd is not null) { _cred.password = Marshal.SecureStringToCoTaskMemUnicode(pwd); } @@ -650,7 +650,7 @@ internal class WSManData_ManToUn : IDisposable /// internal WSManData_ManToUn(byte[] data) { - Dbg.Assert(data != null, "Data cannot be null"); + Dbg.Assert(data is not null, "Data cannot be null"); _internalData = new WSManDataStruct(); _internalData.binaryOrTextData = new WSManBinaryOrTextDataStruct(); @@ -673,7 +673,7 @@ internal WSManData_ManToUn(byte[] data) /// internal WSManData_ManToUn(string data) { - Dbg.Assert(data != null, "Data cannot be null"); + Dbg.Assert(data is not null, "Data cannot be null"); _internalData = new WSManDataStruct(); _internalData.binaryOrTextData = new WSManBinaryOrTextDataStruct(); @@ -754,7 +754,7 @@ private void Dispose(bool isDisposing) /// public static implicit operator IntPtr(WSManData_ManToUn data) { - if (data != null) + if (data is not null) { return data._marshalledObject; } @@ -952,7 +952,7 @@ internal struct WSManStreamIDSet_ManToUn /// internal WSManStreamIDSet_ManToUn(string[] streamIds) { - Dbg.Assert(streamIds != null, "stream ids cannot be null or empty"); + Dbg.Assert(streamIds is not null, "stream ids cannot be null or empty"); int sizeOfIntPtr = Marshal.SizeOf(); _streamSetInfo = new WSManStreamIDSetStruct(); @@ -1112,7 +1112,7 @@ internal struct WSManOptionSet : IDisposable /// internal WSManOptionSet(WSManOption[] options) { - Dbg.Assert(options != null, "options cannot be null"); + Dbg.Assert(options is not null, "options cannot be null"); int sizeOfOption = Marshal.SizeOf(); _optionSet = new WSManOptionSetStruct(); @@ -1592,7 +1592,7 @@ internal WSManProxyInfo(ProxyAccessType proxyAccessType, internalInfo.proxyAuthCredentialsStruct = new WSManUserNameAuthenticationCredentials.WSManUserNameCredentialStruct(); internalInfo.proxyAuthCredentialsStruct.authenticationMechanism = WSManAuthenticationMechanism.WSMAN_FLAG_DEFAULT_AUTHENTICATION; - if (authCredentials != null) + if (authCredentials is not null) { internalInfo.proxyAuthCredentialsStruct = authCredentials.CredentialStruct; } diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs index 6ed2312e8f4..956b7c8efd9 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs @@ -330,7 +330,7 @@ internal void CreateShell( AddToActiveShellSessions(mgdShellSession); mgdShellSession.SessionClosed += HandleShellSessionClosed; - if (inboundShellInformation != null) + if (inboundShellInformation is not null) { if ((uint)WSManNativeApi.WSManDataType.WSMAN_DATA_TYPE_TEXT != inboundShellInformation.Type) { @@ -441,7 +441,7 @@ internal void CreateShell( try { - if (convertedBase64 != null) + if (convertedBase64 is not null) { mgdShellSession.SendOneItemToSessionHelper(convertedBase64, WSManPluginConstants.SupportedInputStream); } @@ -1114,12 +1114,12 @@ private PSSenderInfo GetPSSenderInfo( WSManNativeApi.WSManSenderDetails senderDetails) { // senderDetails will not be null. - Dbg.Assert(senderDetails != null, "senderDetails cannot be null"); + Dbg.Assert(senderDetails is not null, "senderDetails cannot be null"); // Construct PSIdentity PSCertificateDetails psCertDetails = null; // Construct Certificate Details - if (senderDetails.certificateDetails != null) + if (senderDetails.certificateDetails is not null) { psCertDetails = new PSCertificateDetails( senderDetails.certificateDetails.subject, @@ -1170,7 +1170,7 @@ private PSSenderInfo GetPSSenderInfo( private IntPtr GetRunAsClientToken() { string clientTokenStr = System.Environment.GetEnvironmentVariable(WSManRunAsClientTokenName); - if (clientTokenStr != null) + if (clientTokenStr is not null) { // Remove the token value from the environment variable System.Environment.SetEnvironmentVariable(WSManRunAsClientTokenName, null); @@ -1264,7 +1264,7 @@ protected internal bool EnsureProtocolVersionComplies( System.Version clientVersion = Utils.StringToVersion(clientVersionString); System.Version serverVersion = Utils.StringToVersion(WSManPluginConstants.PowerShellStartupProtocolVersionValue); - if ((clientVersion != null) && (serverVersion != null) && + if ((clientVersion is not null) && (serverVersion is not null) && (clientVersion.Major == serverVersion.Major) && (clientVersion.Minor >= serverVersion.Minor)) { @@ -1581,7 +1581,7 @@ internal static void PerformWSManPluginSignal( { // Close operations associated with this command.. WSManPluginOperationShutdownContext cmdCtxt = new WSManPluginOperationShutdownContext(pluginContext, shellContext, commandContext, false); - if (cmdCtxt != null) + if (cmdCtxt is not null) { PerformCloseOperation(cmdCtxt); } @@ -1701,7 +1701,7 @@ internal static void ReportWSManOperationComplete( WSManNativeApi.WSManPluginRequest requestDetails, WSManPluginErrorCodes errorCode) { - Dbg.Assert(requestDetails != null, "requestDetails cannot be null in operation complete."); + Dbg.Assert(requestDetails is not null, "requestDetails cannot be null in operation complete."); PSEtwLog.LogAnalyticInformational( PSEventId.ReportOperationComplete, @@ -1724,13 +1724,13 @@ internal static void ReportWSManOperationComplete( WSManNativeApi.WSManPluginRequest requestDetails, Exception reasonForClose) { - Dbg.Assert(requestDetails != null, "requestDetails cannot be null in operation complete."); + Dbg.Assert(requestDetails is not null, "requestDetails cannot be null in operation complete."); WSManPluginErrorCodes error = WSManPluginErrorCodes.NoError; string errorMessage = string.Empty; string stackTrace = string.Empty; - if (reasonForClose != null) + if (reasonForClose is not null) { error = WSManPluginErrorCodes.ManagedException; errorMessage = reasonForClose.Message; @@ -1746,7 +1746,7 @@ internal static void ReportWSManOperationComplete( errorMessage, stackTrace); - if (reasonForClose != null) + if (reasonForClose is not null) { // report operation complete to wsman with the error message (if any). ReportOperationComplete( @@ -1775,7 +1775,7 @@ internal static void SetThreadProperties( WSManNativeApi.WSManPluginRequest requestDetails) { // requestDetails cannot not be null. - Dbg.Assert(requestDetails != null, "requestDetails cannot be null"); + Dbg.Assert(requestDetails is not null, "requestDetails cannot be null"); // IntPtr nativeLocaleData = IntPtr.Zero; WSManNativeApi.WSManDataStruct outputStruct = new WSManNativeApi.WSManDataStruct(); @@ -1865,7 +1865,7 @@ internal static void ReportOperationComplete( WSManPluginErrorCodes errorCode, string errorMessage) { - if (requestDetails != null) + if (requestDetails is not null) { ReportOperationComplete(requestDetails.unmanagedHandle, errorCode, errorMessage); } @@ -1881,7 +1881,7 @@ internal static void ReportOperationComplete( WSManNativeApi.WSManPluginRequest requestDetails, WSManPluginErrorCodes errorCode) { - if (requestDetails != null && + if (requestDetails is not null && IntPtr.Zero != requestDetails.unmanagedHandle) { wsmanPinvokeStatic.WSManPluginOperationComplete( diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs index 2eb657bf0dc..c3c458ca348 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs @@ -318,7 +318,7 @@ private void populateDelegates() private void CleanUpDelegates() { // Free GCHandles so that the memory they point to may be unpinned (garbage collected) - if (_pluginShellGCHandle != null) + if (_pluginShellGCHandle is not null) { _pluginShellGCHandle.Free(); _pluginReleaseShellContextGCHandle.Free(); @@ -450,7 +450,7 @@ public static void ShutdownPlugin( { WSManPluginInstance.PerformShutdown(pluginContext); - if (workerPtrs != null) + if (workerPtrs is not null) { workerPtrs.Dispose(); } @@ -519,7 +519,7 @@ public static void WSManPluginShell( #if(DEBUG) // In debug builds, allow remote runspaces to wait for debugger attach - if (Environment.GetEnvironmentVariable("__PSRemoteRunspaceWaitForDebugger", EnvironmentVariableTarget.Machine) != null) + if (Environment.GetEnvironmentVariable("__PSRemoteRunspaceWaitForDebugger", EnvironmentVariableTarget.Machine) is not null) { bool debuggerAttached = false; while (!debuggerAttached) diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs index 631a0c1571e..b82d1b59979 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs @@ -312,7 +312,7 @@ protected internal void SafeInvokeSessionClosed(object sender, EventArgs eventAr internal void HandleTransportError(object sender, TransportErrorOccuredEventArgs eventArgs) { Exception reasonForClose = null; - if (eventArgs != null) + if (eventArgs is not null) { reasonForClose = eventArgs.Exception; } @@ -333,7 +333,7 @@ internal void Close(bool isShuttingDown) if (Interlocked.Exchange(ref registeredShutdownNotification, 0) == 1) { // release the shutdown notification handle. - if (registeredShutDownWaitHandle != null) + if (registeredShutDownWaitHandle is not null) { registeredShutDownWaitHandle.Unregister(null); registeredShutDownWaitHandle = null; @@ -343,7 +343,7 @@ internal void Close(bool isShuttingDown) // Delete the context only if isShuttingDown != true. isShuttingDown will // be true only when the method is called from RegisterWaitForSingleObject // handler..in which case the context will be freed from the callback. - if (shutDownContext != null) + if (shutDownContext is not null) { shutDownContext = null; } @@ -371,7 +371,7 @@ internal void ReportSendOperationComplete() { lock (_syncObject) { - if (sendRequestDetails != null) + if (sendRequestDetails is not null) { // report and clear the send request details WSManPluginInstance.ReportWSManOperationComplete(sendRequestDetails, lastErrorReported); @@ -662,7 +662,7 @@ private void HandleServerRemoteSessionClosed( RemoteSessionStateMachineEventArgs eventArgs) { Exception reasonForClose = null; - if (eventArgs != null) + if (eventArgs is not null) { reasonForClose = eventArgs.Reason; } diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginTransportManager.cs index 3edfecd5e6e..2107c2ff750 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginTransportManager.cs @@ -109,7 +109,7 @@ internal void DoClose( _activeCmdTransportManagers.Clear(); - if (_registeredShutDownWaitHandle != null) + if (_registeredShutDownWaitHandle is not null) { // This will not wait for the callback to complete. _registeredShutDownWaitHandle.Unregister(null); @@ -119,14 +119,14 @@ internal void DoClose( // Delete the context only if isShuttingDown != true. isShuttingDown will // be true only when the method is called from RegisterWaitForSingleObject // handler..in which case the context will be freed from the callback. - if (_shutDownContext != null) + if (_shutDownContext is not null) { _shutDownContext = null; } // This might happen when client did not send a receive request // but the server is closing - if (_requestDetails != null) + if (_requestDetails is not null) { // Notify that no more data is being sent on this transport. WSManNativeApi.WSManPluginReceiveResult( diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs index 33c96b5d5d4..5dd5751aa5f 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs @@ -121,7 +121,7 @@ internal static TransportErrorOccuredEventArgs ConstructTransportErrorEventArgs( // Not worth to handle these cases separately as there are very corner scenarios, but need to make sure wsmanSessionTM is not referenced // Destination server is reporting that URI redirect is required for this user. - if ((errorStruct.errorCode == WSManNativeApi.ERROR_WSMAN_REDIRECT_REQUESTED) && (wsmanSessionTM != null)) + if ((errorStruct.errorCode == WSManNativeApi.ERROR_WSMAN_REDIRECT_REQUESTED) && (wsmanSessionTM is not null)) { IntPtr wsmanSessionHandle = wsmanSessionTM.SessionHandle; // populate the transport message with the redirection uri..this will @@ -137,7 +137,7 @@ internal static TransportErrorOccuredEventArgs ConstructTransportErrorEventArgs( winrmMessage, redirectLocation); } - else if ((errorStruct.errorCode == WSManNativeApi.ERROR_WSMAN_INVALID_RESOURCE_URI) && (wsmanSessionTM != null)) + else if ((errorStruct.errorCode == WSManNativeApi.ERROR_WSMAN_INVALID_RESOURCE_URI) && (wsmanSessionTM is not null)) { string configurationName = wsmanSessionTM.ConnectionInfo.ShellUri.Replace(Remoting.Client.WSManNativeApi.ResourceURIPrefix, string.Empty); @@ -569,7 +569,7 @@ internal WSManClientSessionTransportManager(Guid runspacePoolInstanceId, StringUtil.Format(RemotingErrorIdStrings.WSManInitFailed, WSManAPIData.ErrorCode)); } - Dbg.Assert(connectionInfo != null, "connectionInfo cannot be null"); + Dbg.Assert(connectionInfo is not null, "connectionInfo cannot be null"); CryptoHelper = cryptoHelper; dataToBeSent.Fragmentor = base.Fragmentor; @@ -918,7 +918,7 @@ internal override void ConnectAsync() DataPriorityType additionalDataType; byte[] additionalData = dataToBeSent.ReadOrRegisterCallback(null, out additionalDataType); - if (additionalData != null) + if (additionalData is not null) { // WSMan expects the data to be in XML format (which is text + xml tags) // so convert byte[] into base64 encoded format @@ -932,7 +932,7 @@ internal override void ConnectAsync() // THERE SHOULD BE NO ADDITIONAL DATA. If there is, it means we are not able to push all initial negotiation related data // as part of Connect SOAP. The connect algorithm is based on this assumption. So bail out. additionalData = dataToBeSent.ReadOrRegisterCallback(null, out additionalDataType); - if (additionalData != null) + if (additionalData is not null) { // Negotiation payload does not fit in ConnectShell. bail out. // Assert for now. should be replaced with raising an exception so upper layers can catch. @@ -1034,13 +1034,13 @@ internal override void CreateAsync() { Dbg.Assert(!isClosed, "object already disposed"); Dbg.Assert(!string.IsNullOrEmpty(ConnectionInfo.ShellUri), "shell uri cannot be null or empty."); - Dbg.Assert(WSManAPIData != null, "WSManApiData should always be created before session creation."); + Dbg.Assert(WSManAPIData is not null, "WSManApiData should always be created before session creation."); List shellOptions = new List(WSManAPIData.CommonOptionSet); #region SHIM: Redirection code for protocol version - if (s_protocolVersionRedirect != null) + if (s_protocolVersionRedirect is not null) { string newProtocolVersion = (string)s_protocolVersionRedirect.DynamicInvoke(); shellOptions.Clear(); @@ -1077,7 +1077,7 @@ internal override void CreateAsync() bool sendContinue = true; - if (s_sessionSendRedirect != null) + if (s_sessionSendRedirect is not null) { object[] arguments = new object[2] { null, additionalData }; sendContinue = (bool)s_sessionSendRedirect.DynamicInvoke(arguments); @@ -1089,7 +1089,7 @@ internal override void CreateAsync() #endregion - if (additionalData != null) + if (additionalData is not null) { // WSMan expects the data to be in XML format (which is text + xml tags) // so convert byte[] into base64 encoded format @@ -1344,10 +1344,10 @@ internal override void Redirect(Uri newUri, RunspaceConnectionInfo connectionInf internal override BaseClientCommandTransportManager CreateClientCommandTransportManager(RunspaceConnectionInfo connectionInfo, ClientRemotePowerShell cmd, bool noInput) { - Dbg.Assert(cmd != null, "Cmd cannot be null"); + Dbg.Assert(cmd is not null, "Cmd cannot be null"); WSManConnectionInfo wsmanConnectionInfo = connectionInfo as WSManConnectionInfo; - Dbg.Assert(wsmanConnectionInfo != null, "ConnectionInfo must be WSManConnectionInfo"); + Dbg.Assert(wsmanConnectionInfo is not null, "ConnectionInfo must be WSManConnectionInfo"); WSManClientCommandTransportManager result = new WSManClientCommandTransportManager(wsmanConnectionInfo, _wsManShellOperationHandle, cmd, noInput, this); @@ -1368,7 +1368,7 @@ internal override BaseClientCommandTransportManager CreateClientCommandTransport /// private void Initialize(Uri connectionUri, WSManConnectionInfo connectionInfo) { - Dbg.Assert(connectionInfo != null, "connectionInfo cannot be null."); + Dbg.Assert(connectionInfo is not null, "connectionInfo cannot be null."); ConnectionInfo = connectionInfo; @@ -1418,7 +1418,7 @@ private void Initialize(Uri connectionUri, WSManConnectionInfo connectionInfo) WSManNativeApi.BaseWSManAuthenticationCredentials authCredentials; // use certificate thumbprint for authentication - if (connectionInfo.CertificateThumbprint != null) + if (connectionInfo.CertificateThumbprint is not null) { authCredentials = new WSManNativeApi.WSManCertificateThumbprintCredentials(connectionInfo.CertificateThumbprint); } @@ -1427,7 +1427,7 @@ private void Initialize(Uri connectionUri, WSManConnectionInfo connectionInfo) // use credential based authentication string userName = null; System.Security.SecureString password = null; - if ((connectionInfo.Credential != null) && (!string.IsNullOrEmpty(connectionInfo.Credential.UserName))) + if ((connectionInfo.Credential is not null) && (!string.IsNullOrEmpty(connectionInfo.Credential.UserName))) { userName = connectionInfo.Credential.UserName; password = connectionInfo.Credential.Password; @@ -1443,7 +1443,7 @@ private void Initialize(Uri connectionUri, WSManConnectionInfo connectionInfo) // proxy related data WSManNativeApi.WSManUserNameAuthenticationCredentials proxyAuthCredentials = null; - if (connectionInfo.ProxyCredential != null) + if (connectionInfo.ProxyCredential is not null) { WSManNativeApi.WSManAuthenticationMechanism authMechanism = WSManNativeApi.WSManAuthenticationMechanism.WSMAN_FLAG_AUTH_NEGOTIATE; string userName = null; @@ -1488,17 +1488,17 @@ private void Initialize(Uri connectionUri, WSManConnectionInfo connectionInfo) finally { // release resources - if (proxyAuthCredentials != null) + if (proxyAuthCredentials is not null) { proxyAuthCredentials.Dispose(); } - if (proxyInfo != null) + if (proxyInfo is not null) { proxyInfo.Dispose(); } - if (authCredentials != null) + if (authCredentials is not null) { authCredentials.Dispose(); } @@ -1639,7 +1639,7 @@ internal override void RaiseErrorHandler(TransportErrorOccuredEventArgs eventArg { stackTrace = eventArgs.Exception.StackTrace; } - else if (eventArgs.Exception.InnerException != null && + else if (eventArgs.Exception.InnerException is not null && !string.IsNullOrEmpty(eventArgs.Exception.InnerException.StackTrace)) { stackTrace = eventArgs.Exception.InnerException.StackTrace; @@ -1683,7 +1683,7 @@ internal void ClearReceiveOrSendResources(int flags, bool shouldClearSend) { if (shouldClearSend) { - if (_sendToRemoteCompleted != null) + if (_sendToRemoteCompleted is not null) { _sendToRemoteCompleted.Dispose(); _sendToRemoteCompleted = null; @@ -1707,7 +1707,7 @@ internal void ClearReceiveOrSendResources(int flags, bool shouldClearSend) _wsManReceiveOperationHandle = IntPtr.Zero; } - if (_receivedFromRemote != null) + if (_receivedFromRemote is not null) { _receivedFromRemote.Dispose(); _receivedFromRemote = null; @@ -1724,14 +1724,14 @@ internal override void ProcessPrivateData(object privateData) { // Raise the Robust ConnectionStatusEventArgs rcArgs = privateData as ConnectionStatusEventArgs; - if (rcArgs != null) + if (rcArgs is not null) { RaiseRobustConnectionNotification(rcArgs); return; } CompletionEventArgs completionArgs = privateData as CompletionEventArgs; - if (completionArgs != null) + if (completionArgs is not null) { switch (completionArgs.Notification) { @@ -1924,7 +1924,7 @@ private static void OnCreateSessionCallback(IntPtr operationContext, // openContent is used by redirection ie., while redirecting to // a new machine.. this is not needed anymore as the connection // is successfully established. - if (sessionTM._openContent != null) + if (sessionTM._openContent is not null) { sessionTM._openContent.Dispose(); sessionTM._openContent = null; @@ -1933,7 +1933,7 @@ private static void OnCreateSessionCallback(IntPtr operationContext, if (data != IntPtr.Zero) { WSManNativeApi.WSManCreateShellDataResult shellData = WSManNativeApi.WSManCreateShellDataResult.UnMarshal(data); - if (shellData.data != null) + if (shellData.data is not null) { string returnXml = shellData.data; @@ -2043,7 +2043,7 @@ private static void OnRemoteSessionDisconnectCompleted(IntPtr operationContext, "OnRemoteSessionDisconnectCompleted"); // Dispose the OnDisconnect callback as it is not needed anymore - if (sessionTM._disconnectSessionCompleted != null) + if (sessionTM._disconnectSessionCompleted is not null) { sessionTM._disconnectSessionCompleted.Dispose(); sessionTM._disconnectSessionCompleted = null; @@ -2125,7 +2125,7 @@ private static void OnRemoteSessionReconnectCompleted(IntPtr operationContext, "OnRemoteSessionReconnectCompleted"); // Dispose the OnCreate callback as it is not needed anymore - if (sessionTM._reconnectSessionCompleted != null) + if (sessionTM._reconnectSessionCompleted is not null) { sessionTM._reconnectSessionCompleted.Dispose(); sessionTM._reconnectSessionCompleted = null; @@ -2263,7 +2263,7 @@ private static void OnRemoteSessionConnectCallback(IntPtr operationContext, } // dispose openContent - if (sessionTM._openContent != null) + if (sessionTM._openContent is not null) { sessionTM._openContent.Dispose(); sessionTM._openContent = null; @@ -2280,9 +2280,9 @@ private static void OnRemoteSessionConnectCallback(IntPtr operationContext, } // process returned Xml - Dbg.Assert(data != null, "WSManConnectShell callback returned null data"); + Dbg.Assert(data is not null, "WSManConnectShell callback returned null data"); WSManNativeApi.WSManConnectDataResult connectData = WSManNativeApi.WSManConnectDataResult.UnMarshal(data); - if (connectData.data != null) + if (connectData.data is not null) { byte[] connectResponse = ServerOperationHelpers.ExtractEncodedXmlElement(connectData.data, WSManNativeApi.PS_CONNECTRESPONSE_XML_TAG); sessionTM.ProcessRawData(connectResponse, WSManNativeApi.WSMAN_STREAM_ID_STDOUT); @@ -2440,7 +2440,7 @@ private static void OnRemoteSessionDataReceived(IntPtr operationContext, } WSManNativeApi.WSManReceiveDataResult dataReceived = WSManNativeApi.WSManReceiveDataResult.UnMarshal(data); - if (dataReceived.data != null) + if (dataReceived.data is not null) { tracer.WriteLine("Session Received Data : {0}", dataReceived.data.Length); PSEtwLog.LogAnalyticInformational( @@ -2463,7 +2463,7 @@ private void SendOneItem() // This will either return data or register callback but doesn't do both. byte[] data = dataToBeSent.ReadOrRegisterCallback(_onDataAvailableToSendCallback, out priorityType); - if (data != null) + if (data is not null) { SendData(data, priorityType); } @@ -2471,7 +2471,7 @@ private void SendOneItem() private void OnDataAvailableCallback(byte[] data, DataPriorityType priorityType) { - Dbg.Assert(data != null, "data cannot be null in the data available callback"); + Dbg.Assert(data is not null, "data cannot be null in the data available callback"); tracer.WriteLine("Received data to be sent from the callback."); SendData(data, priorityType); @@ -2486,7 +2486,7 @@ private void SendData(byte[] data, DataPriorityType priorityType) bool sendContinue = true; - if (s_sessionSendRedirect != null) + if (s_sessionSendRedirect is not null) { object[] arguments = new object[2] { null, package }; sendContinue = (bool)s_sessionSendRedirect.DynamicInvoke(arguments); @@ -2545,7 +2545,7 @@ internal override void Dispose(bool isDisposing) // openContent is used by redirection ie., while redirecting to // a new machine and hence this is cleared only when the session // is disposing. - if (isDisposing && (_openContent != null)) + if (isDisposing && (_openContent is not null)) { _openContent.Dispose(); _openContent = null; @@ -2583,7 +2583,7 @@ private void CloseSessionAndClearResources() // remove session context from session handles dictionary RemoveSessionTransportManager(_sessionContextID); - if (_closeSessionCompleted != null) + if (_closeSessionCompleted is not null) { _closeSessionCompleted.Dispose(); _closeSessionCompleted = null; @@ -2592,7 +2592,7 @@ private void CloseSessionAndClearResources() // Dispose the create session completed callback here, since it is // used for periodic robust connection retry/auto-disconnect // notifications while the shell is active. - if (_createSessionCallback != null) + if (_createSessionCallback is not null) { _createSessionCallbackGCHandle.Free(); _createSessionCallback.Dispose(); @@ -2600,7 +2600,7 @@ private void CloseSessionAndClearResources() } // Dispose the OnConnect callback if one present - if (_connectSessionCallback != null) + if (_connectSessionCallback is not null) { _connectSessionCallback.Dispose(); _connectSessionCallback = null; @@ -2735,7 +2735,7 @@ public void Dispose() #if !UNIX // If we initialized with thread impersonation, make sure de-initialize is run with the same. - if (_identityToImpersonate != null) + if (_identityToImpersonate is not null) { result = WindowsIdentity.RunImpersonated( _identityToImpersonate.AccessToken, @@ -2918,7 +2918,7 @@ internal WSManClientCommandTransportManager(WSManConnectionInfo connectionInfo, base(shell, sessnTM.CryptoHelper, sessnTM) { Dbg.Assert(IntPtr.Zero != wsManShellOperationHandle, "Shell operation handle cannot be IntPtr.Zero."); - Dbg.Assert(connectionInfo != null, "connectionInfo cannot be null"); + Dbg.Assert(connectionInfo is not null, "connectionInfo cannot be null"); _wsManShellOperationHandle = wsManShellOperationHandle; @@ -3014,13 +3014,13 @@ internal override void ConnectAsync() internal override void CreateAsync() { byte[] cmdPart1 = serializedPipeline.ReadOrRegisterCallback(null); - if (cmdPart1 != null) + if (cmdPart1 is not null) { #region SHIM: Redirection code for command code send. bool sendContinue = true; - if (s_commandCodeSendRedirect != null) + if (s_commandCodeSendRedirect is not null) { object[] arguments = new object[2] { null, cmdPart1 }; sendContinue = (bool)s_commandCodeSendRedirect.DynamicInvoke(arguments); @@ -3215,7 +3215,7 @@ internal override void RaiseErrorHandler(TransportErrorOccuredEventArgs eventArg { stackTrace = eventArgs.Exception.StackTrace; } - else if (eventArgs.Exception.InnerException != null && + else if (eventArgs.Exception.InnerException is not null && !string.IsNullOrEmpty(eventArgs.Exception.InnerException.StackTrace)) { stackTrace = eventArgs.Exception.InnerException.StackTrace; @@ -3256,7 +3256,7 @@ internal override void RaiseErrorHandler(TransportErrorOccuredEventArgs eventArg /// internal override void ProcessPrivateData(object privateData) { - Dbg.Assert(privateData != null, "privateData cannot be null."); + Dbg.Assert(privateData is not null, "privateData cannot be null."); // For this version...only a boolean can be used for privateData. bool shouldRaiseSignalCompleted = (bool)privateData; @@ -3278,7 +3278,7 @@ internal void ClearReceiveOrSendResources(int flags, bool shouldClearSend) { if (shouldClearSend) { - if (_sendToRemoteCompleted != null) + if (_sendToRemoteCompleted is not null) { _sendToRemoteCompleted.Dispose(); _sendToRemoteCompleted = null; @@ -3302,7 +3302,7 @@ internal void ClearReceiveOrSendResources(int flags, bool shouldClearSend) _wsManReceiveOperationHandle = IntPtr.Zero; } - if (_receivedFromRemote != null) + if (_receivedFromRemote is not null) { _receivedFromRemote.Dispose(); _receivedFromRemote = null; @@ -3371,7 +3371,7 @@ private static void OnCreateCmdCompleted(IntPtr operationContext, cmdTM.powershellInstanceId.ToString()); // dispose the cmdCompleted callback as it is not needed any more - if (cmdTM._createCmdCompleted != null) + if (cmdTM._createCmdCompleted is not null) { cmdTM._createCmdCompletedGCHandle.Free(); cmdTM._createCmdCompleted.Dispose(); @@ -3475,7 +3475,7 @@ private static void OnConnectCmdCompleted(IntPtr operationContext, } // dispose the cmdCompleted callback as it is not needed any more - if (cmdTM._connectCmdCompleted != null) + if (cmdTM._connectCmdCompleted is not null) { cmdTM._connectCmdCompleted.Dispose(); cmdTM._connectCmdCompleted = null; @@ -3759,7 +3759,7 @@ private static void OnRemoteCmdDataReceived(IntPtr operationContext, } WSManNativeApi.WSManReceiveDataResult dataReceived = WSManNativeApi.WSManReceiveDataResult.UnMarshal(data); - if (dataReceived.data != null) + if (dataReceived.data is not null) { tracer.WriteLine("Cmd Received Data : {0}", dataReceived.data.Length); PSEtwLog.LogAnalyticInformational( @@ -3890,7 +3890,7 @@ private static void OnRemoteCmdSignalCompleted(IntPtr operationContext, cmdTM._cmdSignalOperationHandle = IntPtr.Zero; } - if (cmdTM._signalCmdCompleted != null) + if (cmdTM._signalCmdCompleted is not null) { cmdTM._signalCmdCompleted.Dispose(); cmdTM._signalCmdCompleted = null; @@ -3950,7 +3950,7 @@ private void SendOneItem() _shouldStartReceivingData = true; } } - else if (_chunkToSend != null) // there is a pending chunk to be sent + else if (_chunkToSend is not null) // there is a pending chunk to be sent { data = _chunkToSend.Data; priorityType = _chunkToSend.Type; @@ -3962,7 +3962,7 @@ private void SendOneItem() data = dataToBeSent.ReadOrRegisterCallback(_onDataAvailableToSendCallback, out priorityType); } - if (data != null) + if (data is not null) { _isSendingInput = true; SendData(data, priorityType); @@ -3976,7 +3976,7 @@ private void SendOneItem() private void OnDataAvailableCallback(byte[] data, DataPriorityType priorityType) { - Dbg.Assert(data != null, "data cannot be null in the data available callback"); + Dbg.Assert(data is not 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"); @@ -3999,7 +3999,7 @@ private void SendData(byte[] data, DataPriorityType priorityType) bool sendContinue = true; - if (s_commandSendRedirect != null) + if (s_commandSendRedirect is not null) { object[] arguments = new object[2] { null, package }; sendContinue = (bool)s_commandSendRedirect.DynamicInvoke(arguments); @@ -4089,19 +4089,19 @@ internal override void Dispose(bool isDisposing) RemoveCmdTransportManager(_cmdContextId); // unregister event handlers - if (_sessnTm != null) + if (_sessnTm is not null) { _sessnTm.RobustConnectionsInitiated -= HandleRobustConnectionsInitiated; _sessnTm.RobustConnectionsCompleted -= HandleRobusConnectionsCompleted; } - if (_closeCmdCompleted != null) + if (_closeCmdCompleted is not null) { _closeCmdCompleted.Dispose(); _closeCmdCompleted = null; } - if (_reconnectCmdCompleted != null) + if (_reconnectCmdCompleted is not null) { _reconnectCmdCompleted.Dispose(); _reconnectCmdCompleted = null; diff --git a/src/System.Management.Automation/engine/remoting/server/OutOfProcServerMediator.cs b/src/System.Management.Automation/engine/remoting/server/OutOfProcServerMediator.cs index cbcfa470739..a506c06c319 100644 --- a/src/System.Management.Automation/engine/remoting/server/OutOfProcServerMediator.cs +++ b/src/System.Management.Automation/engine/remoting/server/OutOfProcServerMediator.cs @@ -142,7 +142,7 @@ protected void OnDataPacketReceived(byte[] rawData, string stream, Guid psGuid) cmdTM = sessionTM.GetCommandTransportManager(psGuid); } - if (cmdTM != null) + if (cmdTM is not null) { // not throwing when there is no associated command as the command might have // legitimately closed while the client is sending data. however the client @@ -209,7 +209,7 @@ protected void OnSignalPacketReceived(Guid psGuid) } // dont throw if there is no cmdTM as it might have legitimately closed - if (cmdTM != null) + if (cmdTM is not null) { cmdTM.Close(null); } @@ -253,7 +253,7 @@ protected void OnClosePacketReceived(Guid psGuid) { tracer.WriteMessage("OnClosePacketReceived, in progress commands count should be zero : " + _inProgressCommandsCount + ", psGuid : " + psGuid.ToString()); - if (sessionTM != null) + if (sessionTM is not null) { // it appears that when closing PowerShell ISE, therefore closing OutOfProcServerMediator, there are 2 Close command requests // changing PSRP/IPC at this point is too risky, therefore protecting about this duplication @@ -277,7 +277,7 @@ protected void OnClosePacketReceived(Guid psGuid) } // dont throw if there is no cmdTM as it might have legitimately closed - if (cmdTM != null) + if (cmdTM is not null) { cmdTM.Close(null); } @@ -494,7 +494,7 @@ internal static void Run(string initialCommand, string workingDirectory) { lock (SyncObject) { - if (s_singletonInstance != null) + if (s_singletonInstance is not null) { Dbg.Assert(false, "Run should not be called multiple times"); return; @@ -559,7 +559,7 @@ internal static void Run(string initialCommand) { lock (SyncObject) { - if (s_singletonInstance != null) + if (s_singletonInstance is not null) { Dbg.Assert(false, "Run should not be called multiple times"); return; @@ -628,7 +628,7 @@ internal static void Run( { lock (SyncObject) { - if (s_singletonInstance != null && !s_singletonInstance.IsDisposed) + if (s_singletonInstance is not null && !s_singletonInstance.IsDisposed) { Dbg.Assert(false, "Run should not be called multiple times, unless the singleton was disposed."); return; @@ -676,7 +676,7 @@ internal NamedPipeErrorTextWriter( internal override void WriteLine(string data) { - string dataToWrite = (data != null) ? _errorPrepend + data : null; + string dataToWrite = (data is not null) ? _errorPrepend + data : null; base.WriteLine(dataToWrite); } @@ -768,7 +768,7 @@ internal HyperVSocketErrorTextWriter( internal override void WriteLine(string data) { - string dataToWrite = (data != null) ? _errorPrepend + data : null; + string dataToWrite = (data is not null) ? _errorPrepend + data : null; base.WriteLine(dataToWrite); } diff --git a/src/System.Management.Automation/engine/remoting/server/ServerMethodExecutor.cs b/src/System.Management.Automation/engine/remoting/server/ServerMethodExecutor.cs index aa10265ec9a..b1763d958ba 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerMethodExecutor.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerMethodExecutor.cs @@ -52,7 +52,7 @@ internal ServerMethodExecutor( { _clientRunspacePoolId = clientRunspacePoolId; _clientPowerShellId = clientPowerShellId; - Dbg.Assert(transportManager != null, "Expected transportManager != null"); + Dbg.Assert(transportManager is not null, "Expected transportManager is not null"); _transportManager = transportManager; _remoteHostCallDataType = clientPowerShellId == Guid.Empty ? RemotingDataType.RemoteHostCallUsingRunspaceHost : RemotingDataType.RemoteHostCallUsingPowerShellHost; @@ -64,7 +64,7 @@ internal ServerMethodExecutor( /// internal void HandleRemoteHostResponseFromClient(RemoteHostResponse remoteHostResponse) { - Dbg.Assert(remoteHostResponse != null, "Expected remoteHostResponse != null"); + Dbg.Assert(remoteHostResponse is not null, "Expected remoteHostResponse is not null"); _serverDispatchTable.SetResponse(remoteHostResponse.CallId, remoteHostResponse); } @@ -89,7 +89,7 @@ internal void ExecuteVoidMethod(RemoteHostMethodId methodId) /// internal void ExecuteVoidMethod(RemoteHostMethodId methodId, object[] parameters) { - Dbg.Assert(parameters != null, "Expected parameters != null"); + Dbg.Assert(parameters is not null, "Expected parameters is not null"); // Use void call ID so that the call is known to not have a return value. long callId = ServerDispatchTable.VoidCallId; @@ -120,7 +120,7 @@ internal T ExecuteMethod(RemoteHostMethodId methodId) /// internal T ExecuteMethod(RemoteHostMethodId methodId, object[] parameters) { - Dbg.Assert(parameters != null, "Expected parameters != null"); + Dbg.Assert(parameters is not null, "Expected parameters is not null"); // Create the method call object. long callId = _serverDispatchTable.CreateNewCallId(); diff --git a/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs b/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs index e52cffd5ce0..eec78424833 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs @@ -135,13 +135,13 @@ internal ServerPowerShellDriver(PowerShell powershell, PowerShell extraPowerShel RegisterPipelineOutputEventHandlers(_localPowerShellOutput); - if (LocalPowerShell != null) + if (LocalPowerShell is not null) { RegisterPowerShellEventHandlers(LocalPowerShell); _datasent[0] = false; } - if (extraPowerShell != null) + if (extraPowerShell is not null) { RegisterPowerShellEventHandlers(extraPowerShell); _datasent[1] = false; @@ -150,10 +150,10 @@ internal ServerPowerShellDriver(PowerShell powershell, PowerShell extraPowerShel RegisterDataStructureHandlerEventHandlers(DataStructureHandler); // set the runspace pool and invoke this powershell - if (rsToUse != null) + if (rsToUse is not null) { LocalPowerShell.Runspace = rsToUse; - if (extraPowerShell != null) + if (extraPowerShell is not null) { extraPowerShell.Runspace = rsToUse; } @@ -161,13 +161,13 @@ internal ServerPowerShellDriver(PowerShell powershell, PowerShell extraPowerShel else { LocalPowerShell.RunspacePool = runspacePoolDriver.RunspacePool; - if (extraPowerShell != null) + if (extraPowerShell is not null) { extraPowerShell.RunspacePool = runspacePoolDriver.RunspacePool; } } - if (output != null) + if (output is not null) { output.DataAdded += (sender, args) => { @@ -293,7 +293,7 @@ internal IAsyncResult Start() /// The output from preprocessing that we want to send to the client. internal void RunNoOpCommand(IReadOnlyCollection output) { - if (LocalPowerShell != null) + if (LocalPowerShell is not null) { System.Threading.ThreadPool.QueueUserWorkItem( (state) => @@ -304,7 +304,7 @@ internal void RunNoOpCommand(IReadOnlyCollection output) foreach (var item in output) { - if (item != null) + if (item is not null) { _localPowerShellOutput.Add(PSObject.AsPSObject(item)); } @@ -334,7 +334,7 @@ internal void InvokeMain() ex = e; } - if (ex != null) + if (ex is not null) { // Since this is being invoked asynchronously on a single pipeline thread // any invoke failures (such as possible debugger failures) need to be @@ -444,7 +444,7 @@ private void HandlePowerShellInvocationStateChanged(object sender, SendRemainingData(); if (state == PSInvocationState.Completed && - (_extraPowerShell != null) && + (_extraPowerShell is not null) && !_extraPowerShellAlreadyScheduled) { _extraPowerShellAlreadyScheduled = true; @@ -459,7 +459,7 @@ private void HandlePowerShellInvocationStateChanged(object sender, eventArgs.InvocationStateInfo); UnregisterPowerShellEventHandlers(LocalPowerShell); - if (_extraPowerShell != null) + if (_extraPowerShell is not null) { UnregisterPowerShellEventHandlers(_extraPowerShell); } @@ -733,7 +733,7 @@ private void HandleStopReceived(object sender, EventArgs eventArgs) // Ensure that the local PowerShell command is not stopped in debug mode. bool handledByDebugger = false; if (!LocalPowerShell.IsNested && - _psDriverInvoker != null) + _psDriverInvoker is not null) { handledByDebugger = _psDriverInvoker.HandleStopSignal(); } @@ -745,7 +745,7 @@ private void HandleStopReceived(object sender, EventArgs eventArgs) } } while (false); - if (_extraPowerShell != null) + if (_extraPowerShell is not null) { do // false loop { @@ -773,7 +773,7 @@ private void HandleInputReceived(object sender, RemoteDataEventArgs even { // This can be called in pushed runspace scenarios for error reporting (pipeline stopped). // Ignore for noInput. - if (!_noInput && (InputCollection != null)) + if (!_noInput && (InputCollection is not null)) { InputCollection.Add(eventArgs.Data); } @@ -788,7 +788,7 @@ private void HandleInputEndReceived(object sender, EventArgs eventArgs) { // This can be called in pushed runspace scenarios for error reporting (pipeline stopped). // Ignore for noInput. - if (!_noInput && (InputCollection != null)) + if (!_noInput && (InputCollection is not null)) { InputCollection.Complete(); } @@ -798,7 +798,7 @@ private void HandleSessionConnected(object sender, EventArgs eventArgs) { // Close input if its active. no need to synchronize as input stream would have already been processed // when connect call came into PS plugin - if (InputCollection != null) + if (InputCollection is not null) { // TODO: Post an ETW event InputCollection.Complete(); @@ -823,11 +823,11 @@ private void HandleHostResponseReceived(object sender, RemoteDataEventArgs public virtual void PushRunspace(Runspace runspace) { - if (_serverDriverRemoteHost != null) + if (_serverDriverRemoteHost is not null) { _serverDriverRemoteHost.PushRunspace(runspace); } @@ -248,7 +248,7 @@ public virtual void PushRunspace(Runspace runspace) /// public virtual void PopRunspace() { - if ((_serverDriverRemoteHost != null) && (_serverDriverRemoteHost.IsRunspacePushed)) + if ((_serverDriverRemoteHost is not null) && (_serverDriverRemoteHost.IsRunspacePushed)) { if (_serverDriverRemoteHost.PropagatePop) { @@ -307,7 +307,7 @@ public override bool IsRunspacePushed { get { - return (_pushedRunspace != null); + return (_pushedRunspace is not null); } } @@ -322,7 +322,7 @@ public override void PushRunspace(Runspace runspace) throw new PSInvalidOperationException(RemotingErrorIdStrings.ServerDriverRemoteHostNoDebuggerToPush); } - if (_pushedRunspace != null) + if (_pushedRunspace is not null) { throw new PSInvalidOperationException(RemotingErrorIdStrings.ServerDriverRemoteHostAlreadyPushed); } @@ -335,8 +335,8 @@ public override void PushRunspace(Runspace runspace) // PSEdit support. Existence of RemoteSessionOpenFileEvent event indicates host supports PSEdit _hostSupportsPSEdit = false; - PSEventManager localEventManager = (Runspace != null) ? Runspace.Events : null; - _hostSupportsPSEdit = (localEventManager != null) ? localEventManager.GetEventSubscribers(HostUtilities.RemoteSessionOpenFileEvent).GetEnumerator().MoveNext() : false; + PSEventManager localEventManager = (Runspace is not null) ? Runspace.Events : null; + _hostSupportsPSEdit = (localEventManager is not null) ? localEventManager.GetEventSubscribers(HostUtilities.RemoteSessionOpenFileEvent).GetEnumerator().MoveNext() : false; if (_hostSupportsPSEdit) { AddPSEditForRunspace(remoteRunspace); @@ -351,9 +351,9 @@ public override void PushRunspace(Runspace runspace) /// public override void PopRunspace() { - if (_pushedRunspace != null) + if (_pushedRunspace is not null) { - if (_debugger != null) + if (_debugger is not null) { _debugger.PopDebugger(); } diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostRawUserInterface.cs b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostRawUserInterface.cs index e7f4e08a500..e50cb206573 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostRawUserInterface.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostRawUserInterface.cs @@ -40,7 +40,7 @@ private HostDefaultData HostDefaultData /// internal ServerRemoteHostRawUserInterface(ServerRemoteHostUserInterface remoteHostUserInterface) { - Dbg.Assert(remoteHostUserInterface != null, "Expected remoteHostUserInterface != null"); + Dbg.Assert(remoteHostUserInterface is not null, "Expected remoteHostUserInterface is not null"); _remoteHostUserInterface = remoteHostUserInterface; Dbg.Assert(!remoteHostUserInterface.ServerRemoteHost.HostInfo.IsHostRawUINull, "Expected !remoteHostUserInterface.ServerRemoteHost.HostInfo.IsHostRawUINull"); diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostUserInterface.cs b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostUserInterface.cs index 10abafe8171..cd7de9201f7 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostUserInterface.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostUserInterface.cs @@ -27,7 +27,7 @@ internal class ServerRemoteHostUserInterface : PSHostUserInterface, IHostUISuppo /// internal ServerRemoteHostUserInterface(ServerRemoteHost remoteHost) { - Dbg.Assert(remoteHost != null, "Expected remoteHost != null"); + Dbg.Assert(remoteHost is not null, "Expected remoteHost is not null"); ServerRemoteHost = remoteHost; Dbg.Assert(!remoteHost.HostInfo.IsHostUINull, "Expected !remoteHost.HostInfo.IsHostUINull"); @@ -93,7 +93,7 @@ public override Dictionary Prompt(string caption, string messa foreach (FieldDescription description in descriptions) { Type requestedType = InternalHostUserInterface.GetFieldType(description); - if (requestedType != null) + if (requestedType is not null) { PSObject valueFromClient; if (results.TryGetValue(description.Name, out valueFromClient)) @@ -101,7 +101,7 @@ public override Dictionary Prompt(string caption, string messa object conversionResult; if (LanguagePrimitives.TryConvertTo(valueFromClient, requestedType, CultureInfo.InvariantCulture, out conversionResult)) { - if (conversionResult != null) + if (conversionResult is not null) { results[description.Name] = PSObject.AsPSObject(conversionResult); } diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRemotingProtocol2.cs b/src/System.Management.Automation/engine/remoting/server/ServerRemotingProtocol2.cs index 36e11e2d386..dad2484cff8 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRemotingProtocol2.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRemotingProtocol2.cs @@ -120,7 +120,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) { case RemotingDataType.CreatePowerShell: { - Dbg.Assert(CreateAndInvokePowerShell != null, + Dbg.Assert(CreateAndInvokePowerShell is not null, "The ServerRunspacePoolDriver should subscribe to all data structure handler events"); CreateAndInvokePowerShell.SafeInvoke(this, new RemoteDataEventArgs>(receivedData)); @@ -130,7 +130,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) case RemotingDataType.GetCommandMetadata: { - Dbg.Assert(GetCommandMetadata != null, + Dbg.Assert(GetCommandMetadata is not null, "The ServerRunspacePoolDriver should subscribe to all data structure handler events"); GetCommandMetadata.SafeInvoke(this, new RemoteDataEventArgs>(receivedData)); @@ -140,7 +140,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) case RemotingDataType.RemoteRunspaceHostResponseData: { - Dbg.Assert(HostResponseReceived != null, + Dbg.Assert(HostResponseReceived is not null, "The ServerRunspacePoolDriver should subscribe to all data structure handler events"); RemoteHostResponse remoteHostResponse = RemoteHostResponse.Decode(receivedData.Data); @@ -156,7 +156,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) case RemotingDataType.SetMaxRunspaces: { - Dbg.Assert(SetMaxRunspacesReceived != null, + Dbg.Assert(SetMaxRunspacesReceived is not null, "The ServerRunspacePoolDriver should subscribe to all data structure handler events"); SetMaxRunspacesReceived.SafeInvoke(this, new RemoteDataEventArgs(receivedData.Data)); @@ -166,7 +166,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) case RemotingDataType.SetMinRunspaces: { - Dbg.Assert(SetMinRunspacesReceived != null, + Dbg.Assert(SetMinRunspacesReceived is not null, "The ServerRunspacePoolDriver should subscribe to all data structure handler events"); SetMinRunspacesReceived.SafeInvoke(this, new RemoteDataEventArgs(receivedData.Data)); @@ -176,7 +176,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) case RemotingDataType.AvailableRunspaces: { - Dbg.Assert(GetAvailableRunspacesReceived != null, + Dbg.Assert(GetAvailableRunspacesReceived is not null, "The ServerRunspacePoolDriver should subscribe to all data structure handler events"); GetAvailableRunspacesReceived.SafeInvoke(this, new RemoteDataEventArgs(receivedData.Data)); @@ -186,7 +186,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) case RemotingDataType.ResetRunspaceState: { - Dbg.Assert(ResetRunspaceState != null, + Dbg.Assert(ResetRunspaceState is not null, "The ServerRunspacePoolDriver should subscribe to all data structure handler events."); ResetRunspaceState.SafeInvoke(this, new RemoteDataEventArgs(receivedData.Data)); @@ -213,7 +213,7 @@ internal ServerPowerShellDataStructureHandler CreatePowerShellDataStructureHandl if (instanceId != Guid.Empty) { cmdTransportManager = _transportManager.GetCommandTransportManager(instanceId); - Dbg.Assert(cmdTransportManager.TypeTable != null, "This should be already set in managed C++ code"); + Dbg.Assert(cmdTransportManager.TypeTable is not null, "This should be already set in managed C++ code"); } ServerPowerShellDataStructureHandler dsHandler = @@ -244,7 +244,7 @@ internal ServerPowerShellDataStructureHandler GetPowerShellDataStructureHandler( foreach (object o in _associatedShells.Values) { ServerPowerShellDataStructureHandler result = o as ServerPowerShellDataStructureHandler; - if (result != null) + if (result is not null) { return result; } @@ -266,7 +266,7 @@ internal void DispatchMessageToPowerShell(RemoteDataObject rcvdData) // if data structure handler is not found, then association has already been // removed, discard message - if (dsHandler != null) + if (dsHandler is not null) { dsHandler.ProcessReceivedData(rcvdData); } @@ -355,7 +355,7 @@ internal TypeTable TypeTable /// data structure handler class private void SendDataAsync(RemoteDataObject data) { - Dbg.Assert(data != null, "Cannot send null object."); + Dbg.Assert(data is not null, "Cannot send null object."); _transportManager.SendDataToClient(data, true); } @@ -463,7 +463,7 @@ internal ServerPowerShellDataStructureHandler(Guid instanceId, Guid runspacePool _streamSerializationOptions = remoteStreamOptions; transportManager.Closing += HandleTransportClosing; - if (localPowerShell != null) + if (localPowerShell is not null) { localPowerShell.RunspaceAssigned += LocalPowerShell_RunspaceAssigned; } @@ -627,7 +627,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) { case RemotingDataType.StopPowerShell: { - Dbg.Assert(StopPowerShellReceived != null, + Dbg.Assert(StopPowerShellReceived is not null, "ServerPowerShellDriver should subscribe to all data structure handler events"); StopPowerShellReceived.SafeInvoke(this, EventArgs.Empty); } @@ -636,7 +636,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) case RemotingDataType.PowerShellInput: { - Dbg.Assert(InputReceived != null, + Dbg.Assert(InputReceived is not null, "ServerPowerShellDriver should subscribe to all data structure handler events"); InputReceived.SafeInvoke(this, new RemoteDataEventArgs(receivedData.Data)); } @@ -645,7 +645,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) case RemotingDataType.PowerShellInputEnd: { - Dbg.Assert(InputEndReceived != null, + Dbg.Assert(InputEndReceived is not null, "ServerPowerShellDriver should subscribe to all data structure handler events"); InputEndReceived.SafeInvoke(this, EventArgs.Empty); } @@ -654,7 +654,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) case RemotingDataType.RemotePowerShellHostResponseData: { - Dbg.Assert(HostResponseReceived != null, + Dbg.Assert(HostResponseReceived is not null, "ServerPowerShellDriver should subscribe to all data structure handler events"); RemoteHostResponse remoteHostResponse = RemoteHostResponse.Decode(receivedData.Data); @@ -678,7 +678,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) /// internal void RaiseRemoveAssociationEvent() { - Dbg.Assert(RemoveAssociation != null, @"The ServerRunspacePoolDataStructureHandler should subscribe + Dbg.Assert(RemoveAssociation is not null, @"The ServerRunspacePoolDataStructureHandler should subscribe to the RemoveAssociation event of ServerPowerShellDataStructureHandler"); RemoveAssociation.SafeInvoke(this, EventArgs.Empty); } @@ -791,7 +791,7 @@ internal Runspace RunspaceUsedToInvokePowerShell /// data structure handler class private void SendDataAsync(RemoteDataObject data) { - Dbg.Assert(data != null, "Cannot send null object."); + Dbg.Assert(data is not null, "Cannot send null object."); // this is from a command execution..let transport manager collect // as much data as possible and send bigger buffer to client. _transportManager.SendDataToClient(data, false); diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs b/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs index 44c7f88feef..a91b1d39762 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs @@ -142,7 +142,7 @@ internal ServerRunspacePoolDriver( string configurationName, string initialLocation) { - Dbg.Assert(configData != null, "ConfigurationData cannot be null"); + Dbg.Assert(configData is not null, "ConfigurationData cannot be null"); _serverCapability = serverCapability; _clientPSVersion = psClientVersion; @@ -272,7 +272,7 @@ internal void SendApplicationPrivateDataToClient() _applicationPrivateData = new PSPrimitiveDictionary(); } - if (_serverRemoteDebugger != null) + if (_serverRemoteDebugger is not null) { // Current debug mode. DebugModes debugMode = _serverRemoteDebugger.DebugMode; @@ -342,11 +342,11 @@ internal void Close() { _isClosed = true; - if ((_remoteHost != null) && (_remoteHost.IsRunspacePushed)) + if ((_remoteHost is not null) && (_remoteHost.IsRunspacePushed)) { Runspace runspaceToDispose = _remoteHost.PushedRunspace; _remoteHost.PopRunspace(); - if (runspaceToDispose != null) + if (runspaceToDispose is not null) { runspaceToDispose.Dispose(); } @@ -360,7 +360,7 @@ internal void Close() RunspacePool.Dispose(); RunspacePool = null; - if (_rsToUseForSteppablePipeline != null) + if (_rsToUseForSteppablePipeline is not null) { _rsToUseForSteppablePipeline.Close(); _rsToUseForSteppablePipeline.Dispose(); @@ -413,7 +413,7 @@ public void ExitNestedPipeline() /// public bool HandleStopSignal() { - if (_serverRemoteDebugger != null) + if (_serverRemoteDebugger is not null) { return _serverRemoteDebugger.HandleStopSignal(); } @@ -442,7 +442,7 @@ private void HandleRunspaceCreatedForTypeTable(object sender, RunspaceCreatedEve { // Client is requesting a configured session. // Create a configured remote runspace and push onto host stack. - if ((_remoteHost != null) && !(_remoteHost.IsRunspacePushed)) + if ((_remoteHost is not null) && !(_remoteHost.IsRunspacePushed)) { // Let exceptions propagate. RemoteRunspace remoteRunspace = HostUtilities.CreateConfiguredRunspace(_configurationName, _remoteHost); @@ -473,9 +473,9 @@ private void SetupRemoteDebugger(Runspace runspace) // Remote debugger is created only when client version is PSVersion (4.0) // or greater, and remote session supports debugging. - if ((_driverNestedInvoker != null) && - (_clientPSVersion != null && _clientPSVersion >= PSVersionInfo.PSV4Version) && - (runspace != null && runspace.Debugger != null)) + if ((_driverNestedInvoker is not null) && + (_clientPSVersion is not null && _clientPSVersion >= PSVersionInfo.PSV4Version) && + (runspace is not null && runspace.Debugger is not null)) { _serverRemoteDebugger = new ServerRemoteDebugger(this, runspace, runspace.Debugger); _remoteHost.ServerDebugger = _serverRemoteDebugger; @@ -484,7 +484,7 @@ private void SetupRemoteDebugger(Runspace runspace) private void DisposeRemoteDebugger() { - if (_serverRemoteDebugger != null) + if (_serverRemoteDebugger is not null) { _serverRemoteDebugger.Dispose(); } @@ -498,7 +498,7 @@ private void DisposeRemoteDebugger() /// private PSDataCollection InvokeScript(Command cmdToRun, RunspaceCreatedEventArgs args) { - Debug.Assert(cmdToRun != null, "cmdToRun shouldn't be null"); + Debug.Assert(cmdToRun is not null, "cmdToRun shouldn't be null"); // Don't invoke initialization script as trusted (CommandOrigin == Internal) if the system is in lock down mode. cmdToRun.CommandOrigin = (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) ? CommandOrigin.Runspace : CommandOrigin.Internal; @@ -518,7 +518,7 @@ private PSDataCollection InvokeScript(Command cmdToRun, RunspaceCreate /// private PSDataCollection InvokePowerShell(PowerShell powershell, RunspaceCreatedEventArgs args) { - Debug.Assert(powershell != null, "powershell shouldn't be null"); + Debug.Assert(powershell is not null, "powershell shouldn't be null"); // run the startup script on the runspace's host HostInfo hostInfo = _remoteHost.HostInfo; @@ -548,16 +548,16 @@ private PSDataCollection InvokePowerShell(PowerShell powershell, Runsp { string exceptionThrown; ErrorRecord lastErrorRecord = errorList[0] as ErrorRecord; - if (lastErrorRecord != null) + if (lastErrorRecord is not null) { exceptionThrown = lastErrorRecord.ToString(); } else { Exception lastException = errorList[0] as Exception; - if (lastException != null) + if (lastException is not null) { - exceptionThrown = (lastException.Message != null) ? lastException.Message : string.Empty; + exceptionThrown = (lastException.Message is not null) ? lastException.Message : string.Empty; } else { @@ -635,7 +635,7 @@ private void InvokeStartupScripts(RunspaceCreatedEventArgs args) cmdToRun = new Command(_configData.InitializationScriptForOutOfProcessRunspace, true, false); } - if (cmdToRun != null) + if (cmdToRun is not null) { InvokeScript(cmdToRun, args); @@ -644,7 +644,7 @@ private void InvokeStartupScripts(RunspaceCreatedEventArgs args) if (RunspacePool.RunspacePoolStateInfo.State == RunspacePoolState.Opening) { object privateDataVariable = args.Runspace.SessionStateProxy.PSVariable.GetValue("global:PSApplicationPrivateData"); - if (privateDataVariable != null) + if (privateDataVariable is not null) { _applicationPrivateData = (PSPrimitiveDictionary)LanguagePrimitives.ConvertTo( privateDataVariable, @@ -730,7 +730,7 @@ private void HandleCreateAndInvokePowerShell(object _, RemoteDataEventArgs publicGetCommandEntries = iss .Commands["Get-Command"] .Where(entry => entry.Visibility == SessionStateEntryVisibility.Public); SessionStateFunctionEntry getCommandProxy = publicGetCommandEntries.OfType().FirstOrDefault(); - if (getCommandProxy != null) + if (getCommandProxy is not null) { if (getCommandProxy.ScriptBlock.ParameterMetadata.BindableParameters.ContainsKey("ListImported")) { @@ -972,7 +972,7 @@ private bool DoesInitialSessionStateIncludeGetCommandWithListImportedSwitch() else { SessionStateCmdletEntry getCommandCmdlet = publicGetCommandEntries.OfType().FirstOrDefault(); - if ((getCommandCmdlet != null) && (getCommandCmdlet.ImplementingType.Equals(typeof(Microsoft.PowerShell.Commands.GetCommandCommand)))) + if ((getCommandCmdlet is not null) && (getCommandCmdlet.ImplementingType.Equals(typeof(Microsoft.PowerShell.Commands.GetCommandCommand)))) { newValue = true; } @@ -1318,7 +1318,7 @@ private static PreProcessCommandResult PreProcessDebuggerCommand( DebuggerResumeAction? resumeAction = null; PSObject resumeObject = command.Parameters[0].Value as PSObject; - if (resumeObject != null) + if (resumeObject is not null) { try { @@ -1346,7 +1346,7 @@ private static PreProcessCommandResult PreProcessDebuggerCommand( DebugModes? mode = null; PSObject modeObject = command.Parameters[0].Value as PSObject; - if (modeObject != null) + if (modeObject is not null) { try { @@ -1389,7 +1389,7 @@ private static PreProcessCommandResult PreProcessDebuggerCommand( UnhandledBreakpointProcessingMode? mode = null; PSObject modeObject = command.Parameters[0].Value as PSObject; - if (modeObject != null) + if (modeObject is not null) { try { @@ -1446,7 +1446,7 @@ private static PreProcessCommandResult PreProcessDebuggerCommand( // Any collection comes through remoting as an ArrayList of Objects so we convert each object // into a breakpoint and add it to the list. var bps = new List(); - if (breakpoints != null) + if (breakpoints is not null) { foreach (object obj in breakpoints) { @@ -1501,7 +1501,7 @@ breakpoint is null TryGetParameter(command, "RunspaceId", out int? runspaceId); Breakpoint bp = serverRemoteDebugger.GetBreakpoint(breakpointId, runspaceId); - if (bp != null) + if (bp is not null) { preProcessOutput.Add(serverRemoteDebugger.EnableBreakpoint(bp, runspaceId)); } @@ -1519,7 +1519,7 @@ breakpoint is null TryGetParameter(command, "RunspaceId", out int? runspaceId); Breakpoint bp = serverRemoteDebugger.GetBreakpoint(breakpointId, runspaceId); - if (bp != null) + if (bp is not null) { preProcessOutput.Add(serverRemoteDebugger.DisableBreakpoint(bp, runspaceId)); } @@ -1626,7 +1626,7 @@ public bool IsAvailable pump = null; } - return (pump != null) ? !(pump.IsBusy) : false; + return (pump is not null) ? !(pump.IsBusy) : false; } } @@ -1732,7 +1732,7 @@ public void Start() } } - if (driver != null) + if (driver is not null) { try { @@ -1996,7 +1996,7 @@ public override DebuggerCommandResults ProcessCommand(PSCommand command, PSDataC return _wrappedDebugger.Value.ProcessCommand(command, output); } - if (!InBreakpoint || (_threadCommandProcessing != null)) + if (!InBreakpoint || (_threadCommandProcessing is not null)) { throw new PSInvalidOperationException( StringUtil.Format(DebuggerStrings.CannotProcessDebuggerCommandNotStopped)); @@ -2029,7 +2029,7 @@ public override void StopProcessCommand() } ThreadCommandProcessing threadCommandProcessing = _threadCommandProcessing; - if (threadCommandProcessing != null) + if (threadCommandProcessing is not null) { threadCommandProcessing.Stop(); } @@ -2230,12 +2230,12 @@ public void Dispose() ExitDebugMode(DebuggerResumeAction.Stop); } - if (_nestedDebugStopCompleteEvent != null) + if (_nestedDebugStopCompleteEvent is not null) { _nestedDebugStopCompleteEvent.Dispose(); } - if (_processCommandCompleteEvent != null) + if (_processCommandCompleteEvent is not null) { _processCommandCompleteEvent.Dispose(); } @@ -2290,7 +2290,7 @@ public DebuggerCommandResults Invoke(ManualResetEventSlim startInvokeEvent) _commandCompleteEvent.Wait(); _commandCompleteEvent.Reset(); #if !UNIX - if (_identityToImpersonate != null) + if (_identityToImpersonate is not null) { _identityToImpersonate.Dispose(); _identityToImpersonate = null; @@ -2298,7 +2298,7 @@ public DebuggerCommandResults Invoke(ManualResetEventSlim startInvokeEvent) #endif // Propagate exception. - if (_exception != null) + if (_exception is not null) { throw _exception; } @@ -2310,7 +2310,7 @@ public DebuggerCommandResults Invoke(ManualResetEventSlim startInvokeEvent) public void Stop() { Debugger debugger = _wrappedDebugger; - if (debugger != null) + if (debugger is not null) { debugger.StopProcessCommand(); } @@ -2321,7 +2321,7 @@ internal void DoInvoke() try { #if !UNIX - if (_identityToImpersonate != null) + if (_identityToImpersonate is not null) { _results = WindowsIdentity.RunImpersonated( _identityToImpersonate.AccessToken, @@ -2351,9 +2351,9 @@ internal void DoInvoke() /// private void SetDebuggerCallbacks() { - if (_runspace != null && - _runspace.ExecutionContext != null && - _wrappedDebugger.Value != null) + if (_runspace is not null && + _runspace.ExecutionContext is not null && + _wrappedDebugger.Value is not null) { SubscribeWrappedDebugger(_wrappedDebugger.Value); @@ -2391,9 +2391,9 @@ private void SetDebuggerCallbacks() /// private void RemoveDebuggerCallbacks() { - if (_runspace != null && - _runspace.ExecutionContext != null && - _wrappedDebugger.Value != null) + if (_runspace is not null && + _runspace.ExecutionContext is not null && + _wrappedDebugger.Value is not null) { UnsubscribeWrappedDebugger(_wrappedDebugger.Value); @@ -2441,7 +2441,7 @@ private void HandleDebuggerStop(object sender, DebuggerStopEventArgs e) contextHost = _runspace.ExecutionContext.InternalHost.ExternalHost; // Forward event to remote client. - Dbg.Assert(_runspace != null, "Runspace cannot be null."); + Dbg.Assert(_runspace is not null, "Runspace cannot be null."); _runspace.ExecutionContext.Events.GenerateEvent( sourceIdentifier: RemoteDebugger.RemoteDebuggerStopEvent, sender: null, @@ -2486,7 +2486,7 @@ private void HandleBreakpointUpdated(object sender, BreakpointUpdatedEventArgs e try { // Forward event to remote client. - Dbg.Assert(_runspace != null, "Runspace cannot be null."); + Dbg.Assert(_runspace is not null, "Runspace cannot be null."); _runspace.ExecutionContext.Events.GenerateEvent( sourceIdentifier: RemoteDebugger.RemoteDebuggerBreakpointUpdatedEvent, sender: null, @@ -2572,7 +2572,7 @@ private void OnEnterDebugMode(ManualResetEventSlim debugModeCompletedEvent) debugModeCompletedEvent.Wait(); debugModeCompletedEvent.Reset(); - if (_threadCommandProcessing != null) + if (_threadCommandProcessing is not null) { // Process command. _threadCommandProcessing.DoInvoke(); @@ -2631,10 +2631,10 @@ private bool IsDebuggingSupported() { // Restriction only occurs on a (non-pushed) local runspace. LocalRunspace localRunspace = _runspace as LocalRunspace; - if (localRunspace != null) + if (localRunspace is not null) { CmdletInfo cmdletInfo = localRunspace.ExecutionContext.EngineSessionState.GetCmdlet(SetPSBreakCommandText); - if ((cmdletInfo != null) && (cmdletInfo.Visibility != SessionStateEntryVisibility.Public)) + if ((cmdletInfo is not null) && (cmdletInfo.Visibility != SessionStateEntryVisibility.Public)) { return false; } @@ -2654,7 +2654,7 @@ private bool IsDebuggingSupported() internal bool HandleStopSignal() { // If in pushed mode then stop any running command. - if (IsPushed && (_threadCommandProcessing != null)) + if (IsPushed && (_threadCommandProcessing is not null)) { StopProcessCommand(); return true; @@ -2700,7 +2700,7 @@ internal void StartPowerShellCommand( { // For nested debugger command processing, invoke command on new local runspace since // the root script debugger runspace is unavailable (it is running a PS script). - Runspace runspace = (remoteHost != null) ? + Runspace runspace = (remoteHost is not null) ? RunspaceFactory.CreateRunspace(remoteHost) : RunspaceFactory.CreateRunspace(); runspace.Open(); @@ -2762,7 +2762,7 @@ private void HandlePowerShellInvocationStateChanged(object sender, PSInvocationS internal int GetBreakpointCount() { ScriptDebugger scriptDebugger = _wrappedDebugger.Value as ScriptDebugger; - if (scriptDebugger != null) + if (scriptDebugger is not null) { return scriptDebugger.GetBreakpoints().Count; } diff --git a/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineDriver.cs b/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineDriver.cs index 403af84fb83..5c1b6005787 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineDriver.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineDriver.cs @@ -22,7 +22,7 @@ internal class ExecutionContextForStepping : IDisposable private ExecutionContextForStepping(ExecutionContext ctxt) { - Dbg.Assert(ctxt != null, "ExecutionContext cannot be null."); + Dbg.Assert(ctxt is not null, "ExecutionContext cannot be null."); _executionContext = ctxt; } @@ -241,7 +241,7 @@ internal void Start() _eventSubscriber.FireStartSteppablePipeline(this); - if (_powershellInput != null) + if (_powershellInput is not null) { _powershellInput.Pulse(); } @@ -262,7 +262,7 @@ internal void HandleInputEndReceived(object sender, EventArgs eventArgs) CheckAndPulseForProcessing(true); - if (_powershellInput != null) + if (_powershellInput is not null) { _powershellInput.Pulse(); } @@ -272,7 +272,7 @@ private void HandleSessionConnected(object sender, EventArgs eventArgs) { // Close input if its active. no need to synchronize as input stream would have already been processed // when connect call came into PS plugin - if (Input != null) + if (Input is not null) { Input.Complete(); } @@ -302,7 +302,7 @@ private void HandleStopReceived(object sender, EventArgs eventArgs) PerformStop(); - if (_powershellInput != null) + if (_powershellInput is not null) { _powershellInput.Pulse(); } @@ -317,7 +317,7 @@ private void HandleInputReceived(object sender, RemoteDataEventArgs even { Dbg.Assert(!NoInput, "Input data should not be received for powershells created with no input"); - if (Input != null) + if (Input is not null) { lock (SyncObject) { @@ -326,7 +326,7 @@ private void HandleInputReceived(object sender, RemoteDataEventArgs even CheckAndPulseForProcessing(false); - if (_powershellInput != null) + if (_powershellInput is not null) { _powershellInput.Pulse(); } diff --git a/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineSubscriber.cs b/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineSubscriber.cs index 788cf2fe83e..7fcb0a136ac 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineSubscriber.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineSubscriber.cs @@ -45,7 +45,7 @@ internal void SubscribeEvents(ServerSteppablePipelineDriver driver) { _eventManager = (object)driver.LocalPowerShell.Runspace.Events as PSLocalEventManager; - if (_eventManager != null) + if (_eventManager is not null) { _startSubscriber = _eventManager.SubscribeEvent(this, "StartSteppablePipeline", Guid.NewGuid().ToString(), null, new PSEventReceivedEventHandler(this.HandleStartEvent), true, false, true); @@ -102,7 +102,7 @@ private void HandleStartEvent(object sender, PSEventArgs args) exceptionOccurred = e; } - if (exceptionOccurred != null) + if (exceptionOccurred is not null) { driver.SetState(PSInvocationState.Failed, exceptionOccurred); } @@ -259,7 +259,7 @@ private void HandleProcessRecord(object sender, PSEventArgs args) } } - if (exceptionOccurred != null) + if (exceptionOccurred is not null) { driver.SetState(PSInvocationState.Failed, exceptionOccurred); } @@ -273,7 +273,7 @@ internal void FireStartSteppablePipeline(ServerSteppablePipelineDriver driver) { lock (_syncObject) { - if (_eventManager != null) + if (_eventManager is not null) { _eventManager.GenerateEvent(_startSubscriber.SourceIdentifier, this, new object[1] { new ServerSteppablePipelineDriverEventArg(driver) }, null, true, false); @@ -289,7 +289,7 @@ internal void FireHandleProcessRecord(ServerSteppablePipelineDriver driver) { lock (_syncObject) { - if (_eventManager != null) + if (_eventManager is not null) { _eventManager.GenerateEvent(_processSubscriber.SourceIdentifier, this, new object[1] { new ServerSteppablePipelineDriverEventArg(driver) }, null, true, false); diff --git a/src/System.Management.Automation/engine/remoting/server/WSManChannelEvents.cs b/src/System.Management.Automation/engine/remoting/server/WSManChannelEvents.cs index 3b1174f0fff..f3e64236934 100644 --- a/src/System.Management.Automation/engine/remoting/server/WSManChannelEvents.cs +++ b/src/System.Management.Automation/engine/remoting/server/WSManChannelEvents.cs @@ -31,7 +31,7 @@ public static class WSManServerChannelEvents internal static void RaiseShuttingDownEvent() { EventHandler handler = ShuttingDown; - if (handler != null) + if (handler is not null) { handler(null, EventArgs.Empty); } @@ -43,7 +43,7 @@ internal static void RaiseShuttingDownEvent() internal static void RaiseActiveSessionsChangedEvent(ActiveSessionsChangedEventArgs eventArgs) { EventHandler handler = ActiveSessionsChanged; - if (handler != null) + if (handler is not null) { handler(null, eventArgs); } diff --git a/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs b/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs index f61187784ba..44f15bb5aa0 100644 --- a/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs +++ b/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs @@ -124,7 +124,7 @@ internal ServerRemoteSession(PSSenderInfo senderInfo, string initializationParameters, AbstractServerSessionTransportManager transportManager) { - Dbg.Assert(transportManager != null, "transportManager cannot be null."); + Dbg.Assert(transportManager is not null, "transportManager cannot be null."); // let input,output and error from native commands redirect as we have // to send (or receive) them back to client for action. @@ -196,7 +196,7 @@ internal static ServerRemoteSession CreateServerRemoteSession( string initialLocation = null) { Dbg.Assert( - (senderInfo != null) && (senderInfo.UserInfo != null), + (senderInfo is not null) && (senderInfo.UserInfo is not null), "senderInfo and userInfo cannot be null."); s_trace.WriteLine("Finding InitialSessionState provider for id : {0}", configurationProviderId); @@ -497,7 +497,7 @@ internal void SendEncryptedSessionKey() internal void Close(RemoteSessionStateMachineEventArgs reasonForClose) { Closed.SafeInvoke(this, reasonForClose); - if (_runspacePoolDriver != null) + if (_runspacePoolDriver is not null) _runspacePoolDriver.Closed -= HandleResourceClosing; } @@ -642,7 +642,7 @@ internal void ExecuteConnect(byte[] connectData, out byte[] connectResponseData) int clientRequestedMinRunspaces = -1; int clientRequestedMaxRunspaces = -1; bool clientRequestedRunspaceCount = false; - if (connectRunspacePoolObject.Data.Properties[RemoteDataNameStrings.MinRunspaces] != null && connectRunspacePoolObject.Data.Properties[RemoteDataNameStrings.MaxRunspaces] != null) + if (connectRunspacePoolObject.Data.Properties[RemoteDataNameStrings.MinRunspaces] is not null && connectRunspacePoolObject.Data.Properties[RemoteDataNameStrings.MaxRunspaces] is not null) { try { @@ -704,7 +704,7 @@ internal void ExecuteConnect(byte[] connectData, out byte[] connectResponseData) runspacepoolInitData.Serialize(stream, fragmentor); stream.Exit(); byte[] outbuffer = stream.Read(); - Dbg.Assert(outbuffer != null, "connect response data should be serialized"); + Dbg.Assert(outbuffer is not null, "connect response data should be serialized"); stream.Dispose(); // we are done connectResponseData = outbuffer; @@ -725,7 +725,7 @@ internal void ExecuteConnect(byte[] connectData, out byte[] connectResponseData) // pass on application private data when session is connected from new client internal void HandlePostConnect() { - if (_runspacePoolDriver != null) + if (_runspacePoolDriver is not null) { _runspacePoolDriver.SendApplicationPrivateDataToClient(); } @@ -747,11 +747,11 @@ private void HandleCreateRunspacePool(object sender, RemoteDataEventArgs createR } RemoteDataObject rcvdData = createRunspaceEventArg.ReceivedData; - Dbg.Assert(rcvdData != null, "rcvdData must be non-null"); + Dbg.Assert(rcvdData is not null, "rcvdData must be non-null"); // set the PSSenderInfo sent in the first packets // This is used by the initial session state configuration providers like Exchange. - if (Context != null) + if (Context is not null) { _senderInfo.ClientTimeZone = Context.ClientCapability.TimeZone; } @@ -792,7 +792,7 @@ private void HandleCreateRunspacePool(object sender, RemoteDataEventArgs createR InitialSessionState rsSessionStateToUse = null; - if (configurationData.SessionConfigurationData != null) + if (configurationData.SessionConfigurationData is not null) { try { @@ -827,15 +827,15 @@ private void HandleCreateRunspacePool(object sender, RemoteDataEventArgs createR // check if the current scenario is Win7(client) to Win8(server). Add back the PSv2 version TabExpansion // function if necessary. Version psClientVersion = null; - if (_senderInfo.ApplicationArguments != null && _senderInfo.ApplicationArguments.ContainsKey("PSversionTable")) + if (_senderInfo.ApplicationArguments is not null && _senderInfo.ApplicationArguments.ContainsKey("PSversionTable")) { var value = PSObject.Base(_senderInfo.ApplicationArguments["PSversionTable"]) as PSPrimitiveDictionary; - if (value != null) + if (value is not null) { if (value.ContainsKey("WSManStackVersion")) { var wsmanStackVersion = PSObject.Base(value["WSManStackVersion"]) as Version; - if (wsmanStackVersion != null && wsmanStackVersion.Major < 3) + if (wsmanStackVersion is not null && wsmanStackVersion.Major < 3) { // The client side is PSv2. This is the Win7 to Win8 scenario. We need to add the PSv2 // TabExpansion function back in to keep the tab expansion functionable on the client side. @@ -871,7 +871,7 @@ private void HandleCreateRunspacePool(object sender, RemoteDataEventArgs createR ApartmentState apartmentState = RemotingDecoder.GetApartmentState(rcvdData.Data); HostInfo hostInfo = RemotingDecoder.GetHostInfo(rcvdData.Data); - if (_runspacePoolDriver != null) + if (_runspacePoolDriver is not null) { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.RunspaceAlreadyExists, _runspacePoolDriver.InstanceId); @@ -961,14 +961,14 @@ private void HandleNegotiationReceived(object sender, RemoteSessionNegotiationEv /// private void HandleSessionDSHandlerClosing(object sender, EventArgs eventArgs) { - if (_runspacePoolDriver != null) + if (_runspacePoolDriver is not null) { _runspacePoolDriver.Close(); } // dispose the session configuration object..this will let them // clean their resources. - if (_sessionConfigProvider != null) + if (_sessionConfigProvider is not null) { _sessionConfigProvider.Dispose(); _sessionConfigProvider = null; @@ -1009,7 +1009,7 @@ private void HandleResourceClosing(object sender, EventArgs args) /// private bool RunServerNegotiationAlgorithm(RemoteSessionCapability clientCapability, bool onConnect) { - Dbg.Assert(clientCapability != null, "Client capability cache must be non-null"); + Dbg.Assert(clientCapability is not null, "Client capability cache must be non-null"); Version clientProtocolVersion = clientCapability.ProtocolVersion; Version serverProtocolVersion = Context.ServerCapability.ProtocolVersion; @@ -1166,7 +1166,7 @@ internal ServerRunspacePoolDriver GetRunspacePoolDriver(Guid clientRunspacePoolI /// internal void ApplyQuotaOnCommandTransportManager(AbstractServerTransportManager cmdTransportManager) { - Dbg.Assert(cmdTransportManager != null, "cmdTransportManager cannot be null"); + Dbg.Assert(cmdTransportManager is not null, "cmdTransportManager cannot be null"); cmdTransportManager.ReceivedDataCollection.MaximumReceivedDataSize = _maxRecvdDataSizeCommand; cmdTransportManager.ReceivedDataCollection.MaximumReceivedObjectSize = _maxRecvdObjectSize; } diff --git a/src/System.Management.Automation/engine/remoting/server/serverremotesessionstatemachine.cs b/src/System.Management.Automation/engine/remoting/server/serverremotesessionstatemachine.cs index bdb4dc8e4a9..09044b3017d 100644 --- a/src/System.Management.Automation/engine/remoting/server/serverremotesessionstatemachine.cs +++ b/src/System.Management.Automation/engine/remoting/server/serverremotesessionstatemachine.cs @@ -262,7 +262,7 @@ private void RaiseEventPrivate(RemoteSessionStateMachineEventArgs fsmEventArg) } EventHandler handler = _stateMachineHandle[(int)_state, (int)fsmEventArg.StateEvent]; - if (handler != null) + if (handler is not null) { s_trace.WriteLine("Before calling state machine event handler: state = {0}, event = {1}", _state, fsmEventArg.StateEvent); @@ -357,7 +357,7 @@ private void DoNegotiationReceived(object sender, RemoteSessionStateMachineEvent } Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.NegotiationReceived, "StateEvent must be NegotiationReceived"); - Dbg.Assert(fsmEventArg.RemoteSessionCapability != null, "RemoteSessioncapability must be non-null"); + Dbg.Assert(fsmEventArg.RemoteSessionCapability is not null, "RemoteSessioncapability must be non-null"); Dbg.Assert(_state == RemoteSessionState.NegotiationPending, "state must be in NegotiationPending state"); if (fsmEventArg.StateEvent != RemoteSessionEvent.NegotiationReceived) @@ -536,7 +536,7 @@ internal void DoMessageReceived(object sender, RemoteSessionStateMachineEventArg clientRunspacePoolId = fsmEventArg.RemoteData.RunspacePoolId; runspacePoolDriver = _session.GetRunspacePoolDriver(clientRunspacePoolId); - if (runspacePoolDriver != null) + if (runspacePoolDriver is not null) { runspacePoolDriver.DataStructureHandler.ProcessReceivedData(fsmEventArg.RemoteData); } @@ -916,7 +916,7 @@ private void DoKeyExchange(object sender, RemoteSessionStateMachineEventArgs eve { // reset the timer Timer tmp = Interlocked.Exchange(ref _keyExchangeTimer, null); - if (tmp != null) + if (tmp is not null) { tmp.Dispose(); } @@ -987,7 +987,7 @@ private void HandleKeyExchangeTimeout(object sender) Dbg.Assert(_state == RemoteSessionState.EstablishedAndKeyRequested, "timeout should only happen when waiting for a key"); Timer tmp = Interlocked.Exchange(ref _keyExchangeTimer, null); - if (tmp != null) + if (tmp is not null) { tmp.Dispose(); } diff --git a/src/System.Management.Automation/engine/remoting/server/serverremotingprotocolimplementation.cs b/src/System.Management.Automation/engine/remoting/server/serverremotingprotocolimplementation.cs index b8c6d0fd15e..41de346e287 100644 --- a/src/System.Management.Automation/engine/remoting/server/serverremotingprotocolimplementation.cs +++ b/src/System.Management.Automation/engine/remoting/server/serverremotingprotocolimplementation.cs @@ -36,8 +36,8 @@ internal override AbstractServerSessionTransportManager TransportManager internal ServerRemoteSessionDSHandlerImpl(ServerRemoteSession session, AbstractServerSessionTransportManager transportManager) { - Dbg.Assert(session != null, "session cannot be null."); - Dbg.Assert(transportManager != null, "transportManager cannot be null."); + Dbg.Assert(session is not null, "session cannot be null."); + Dbg.Assert(transportManager is not null, "transportManager cannot be null."); _session = session; _stateMachine = new ServerRemoteSessionDSHandlerStateMachine(session); @@ -217,7 +217,7 @@ internal override void RaiseDataReceivedEvent(RemoteDataEventArgs dataArg) capabilityArg.RemoteSessionCapability = capability; _stateMachine.RaiseEvent(capabilityArg); - if (NegotiationReceived != null) + if (NegotiationReceived is not null) { RemoteSessionNegotiationEventArgs negotiationArg = new RemoteSessionNegotiationEventArgs(capability); negotiationArg.RemoteData = rcvdData; diff --git a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs index ed6ee5e89bb..81c2a118083 100644 --- a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs +++ b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs @@ -90,7 +90,7 @@ internal static BindingRestrictions GetSimpleTypeRestriction(this DynamicMetaObj internal static BindingRestrictions PSGetMethodArgumentRestriction(this DynamicMetaObject obj) { var baseValue = PSObject.Base(obj.Value); - if (baseValue != null && baseValue.GetType() == typeof(object[])) + if (baseValue is not null && baseValue.GetType() == typeof(object[])) { var effectiveArgType = Adapter.EffectiveArgumentType(obj.Value); var methodInfo = !(effectiveArgType == typeof(object[])) @@ -272,7 +272,7 @@ internal static Expression CastOrConvertMethodArgument(this DynamicMetaObject ta if (parameterType.IsByRefLike && allowCastingToByRefLikeType) { var conversionResult = PSConvertBinder.ConvertToByRefLikeTypeViaCasting(target, parameterType); - if (conversionResult != null) + if (conversionResult is not null) { return conversionResult; } @@ -373,7 +373,7 @@ internal static DynamicMetaObject DeferForPSObject(this DynamicMetaObjectBinder internal static DynamicMetaObject DeferForPSObject(this DynamicMetaObjectBinder binder, DynamicMetaObject[] args, bool targetIsComObject = false) { - Diagnostics.Assert(args != null && args.Length > 0, "args should not be null or empty"); + Diagnostics.Assert(args is not null && args.Length > 0, "args should not be null or empty"); Diagnostics.Assert(args.Any(mo => mo.Value is PSObject), "At least one arg must be a psobject"); Expression[] exprs = new Expression[args.Length]; @@ -615,7 +615,7 @@ public override DynamicMetaObject FallbackConvert(DynamicMetaObject target, Dyna // // DataRowCollection rows; // DataTable table = (DataTable)obj; - // if ((rows = table.Rows) != null) + // if ((rows = table.Rows) is not null) // return rows.GetEnumerator(); // else // return null; @@ -655,7 +655,7 @@ public override DynamicMetaObject FallbackConvert(DynamicMetaObject target, Dyna } var enumerable = targetValue as IEnumerable; - if (enumerable != null) + if (enumerable is not null) { // Normally it's safe to just call IEnumerable.GetEnumerator, but in some rare cases, the // non-generic implementation throws or returns null, so we'll just avoid that problem and @@ -680,7 +680,7 @@ public override DynamicMetaObject FallbackConvert(DynamicMetaObject target, Dyna } var enumerator = targetValue as IEnumerator; - if (enumerator != null) + if (enumerator is not null) { return (new DynamicMetaObject( MaybeDebase(this, e => e.Cast(typeof(IEnumerator)), target), @@ -748,7 +748,7 @@ private static IEnumerator NotEnumerableRule(CallSite site, object obj) private static IEnumerator PSObjectNotEnumerableRule(CallSite site, object obj) { var psobj = obj as PSObject; - return psobj != null && obj != AutomationNull.Value + return psobj is not null && obj != AutomationNull.Value ? NotEnumerableRule(site, PSObject.Base(obj)) : ((CallSite>)site).Update(site, obj); } @@ -756,7 +756,7 @@ private static IEnumerator PSObjectNotEnumerableRule(CallSite site, object obj) private static IEnumerator ArrayRule(CallSite site, object obj) { var array = obj as Array; - if (array != null) return array.GetEnumerator(); + if (array is not null) return array.GetEnumerator(); return ((CallSite>)site).Update(site, obj); } @@ -768,7 +768,7 @@ private static IEnumerator StringRule(CallSite site, object obj) private static IEnumerator PSObjectStringRule(CallSite site, object obj) { var psobj = obj as PSObject; - if (psobj != null && PSObject.Base(psobj) is string) return null; + if (psobj is not null && PSObject.Base(psobj) is string) return null; return ((CallSite>)site).Update(site, obj); } } @@ -971,7 +971,7 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje } var iList = target.Value as IList; - if (iList != null) + if (iList is not null) { // 3 possibilities - too few, exact, or too many elements. @@ -1133,7 +1133,7 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje } IList pipelineResult = target.Value as IList; - Diagnostics.Assert(pipelineResult != null, "Pipeline result is always an IList"); + Diagnostics.Assert(pipelineResult is not null, "Pipeline result is always an IList"); var ilistExpr = target.Expression; if (!(typeof(IList) == ilistExpr.Type)) @@ -1198,7 +1198,7 @@ internal static PSInvokeDynamicMemberBinder Get(CallInfo callInfo, TypeDefinitio { PSInvokeDynamicMemberBinder result; - var classScope = classScopeAst != null ? classScopeAst.Type : null; + var classScope = classScopeAst is not null ? classScopeAst.Type : null; lock (s_binderCache) { var key = Tuple.Create(callInfo, constraints, propertySetter, @static, classScope); @@ -1220,7 +1220,7 @@ internal static PSInvokeDynamicMemberBinder Get(CallInfo callInfo, TypeDefinitio private PSInvokeDynamicMemberBinder(CallInfo callInfo, bool @static, bool propertySetter, PSMethodInvocationConstraints constraints, Type classScope) { - Diagnostics.Assert(callInfo != null, "callers make sure 'callInfo' is not null"); + Diagnostics.Assert(callInfo is not null, "callers make sure 'callInfo' is not null"); _callInfo = callInfo; _static = @static; @@ -1241,7 +1241,7 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje Expression bindingStrExpr; var memberName = memberNameValue as string; - if (memberName != null) + if (memberName is not null) { if (memberNameArg.Value is PSObject) { @@ -1292,7 +1292,7 @@ internal static PSGetDynamicMemberBinder Get(TypeDefinitionAst classScope, bool PSGetDynamicMemberBinder binder; lock (s_binderCache) { - var type = classScope != null ? classScope.Type : null; + var type = classScope is not null ? classScope.Type : null; var tuple = Tuple.Create(type, @static); if (!s_binderCache.TryGetValue(tuple, out binder)) { @@ -1327,7 +1327,7 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje Expression bindingStrExpr; BindingRestrictions restrictions; var memberName = memberNameValue as string; - if (memberName != null) + if (memberName is not null) { if (memberNameArg.Value is PSObject) { @@ -1402,7 +1402,7 @@ internal static PSSetDynamicMemberBinder Get(TypeDefinitionAst classScope, bool PSSetDynamicMemberBinder binder; lock (s_binderCache) { - var type = classScope != null ? classScope.Type : null; + var type = classScope is not null ? classScope.Type : null; var tuple = Tuple.Create(type, @static); if (!s_binderCache.TryGetValue(tuple, out binder)) { @@ -1436,7 +1436,7 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje Expression bindingStrExpr; var memberName = memberNameValue as string; - if (memberName != null) + if (memberName is not null) { if (memberNameArg.Value is PSObject) { @@ -1683,7 +1683,7 @@ public override DynamicMetaObject FallbackCreateInstance(DynamicMetaObject targe // This inconsistent behavior affects OneCore powershell because we are using the extension method here when compiling // against CoreCLR. So we need to add a null check until this is fixed in CLR. var paramArrayAttrs = parameterInfo[argIndex].GetCustomAttributes(typeof(ParamArrayAttribute), true); - if (paramArrayAttrs != null && paramArrayAttrs.Length > 0 && expandParamsOnBest) + if (paramArrayAttrs is not null && paramArrayAttrs.Length > 0 && expandParamsOnBest) { var elementType = parameterInfo[argIndex].ParameterType.GetElementType(); var paramsArray = new List(); @@ -1733,7 +1733,7 @@ public override DynamicMetaObject FallbackCreateInstance(DynamicMetaObject targe Expression lhs; Type propertyType; var propertyInfo = member as PropertyInfo; - if (propertyInfo != null) + if (propertyInfo is not null) { if (propertyInfo.GetSetMethod() is null) { @@ -1845,7 +1845,7 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje } var toType = target.Value as Type; - Diagnostics.Assert(toType != null, "target must be a type"); + Diagnostics.Assert(toType is not null, "target must be a type"); var bindingRestrictions = BindingRestrictions.GetInstanceRestriction(target.Expression, toType).Merge(arg.PSGetTypeRestriction()); @@ -1893,13 +1893,13 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje } var psobj = value as PSObject; - if (psobj != null) + if (psobj is not null) { var restrictions = BindingRestrictions.GetTypeRestriction(target.Expression, psobj.GetType()); var expr = target.Expression; var baseObject = psobj.BaseObject; var baseObjExpr = Expression.Property(expr.Cast(typeof(PSObject)), CachedReflectionInfo.PSObject_BaseObject); - if (baseObject != null) + if (baseObject is not null) { var baseObjType = baseObject.GetType(); restrictions = restrictions.Merge(BindingRestrictions.GetTypeRestriction(baseObjExpr, baseObjType)); @@ -2019,7 +2019,7 @@ private static object ObjectRule(CallSite site, object obj) private static object PSObjectStringRule(CallSite site, object obj) { var psobj = obj as PSObject; - if (psobj != null && psobj.BaseObject is string) return obj; + if (psobj is not null && psobj.BaseObject is string) return obj; return ((CallSite>)site).Update(site, obj); } @@ -2180,7 +2180,7 @@ public override DynamicMetaObject FallbackBinaryOperation(DynamicMetaObject targ { // When adding to an array, we don't want to unwrap the RHS - it's unnecessary, // and in the case of strings, we actually lose instance members on the PSObject. - if (!(Operation == ExpressionType.Add && PSEnumerableBinder.IsEnumerable(target) != null)) + if (!(Operation == ExpressionType.Add && PSEnumerableBinder.IsEnumerable(target) is not null)) { // Defer when the object is wrapped, but not for empty objects. return this.DeferForPSObject(target, arg).WriteToDebugLog(this); @@ -2280,7 +2280,7 @@ private static DynamicMetaObject CallImplicitOp(string methodName, DynamicMetaOb // are trying to generate the expression that calls the override to DynamicObject.TryBinaryOperation. // We get called twice for the same target object, once with a null errorSuggestion (in which case we'll have // returned the result below), and then a second time with a non-null errorSuggestion, which we return as is. - if (errorSuggestion != null && target.Value is DynamicObject) + if (errorSuggestion is not null && target.Value is DynamicObject) { return errorSuggestion; } @@ -2654,7 +2654,7 @@ private DynamicMetaObject BinaryAdd(DynamicMetaObject target, DynamicMetaObject if (target.LimitType.IsNumericOrPrimitive() && !(target.LimitType == typeof(char))) { var numericArg = GetArgAsNumericOrPrimitive(arg, target.LimitType); - if (numericArg != null) + if (numericArg is not null) { return BinaryNumericOp("Add", target, numericArg); } @@ -2678,7 +2678,7 @@ private DynamicMetaObject BinaryAdd(DynamicMetaObject target, DynamicMetaObject ExpressionCache.Constant(1)); } - if (lhsStringExpr != null) + if (lhsStringExpr is not null) { // For string concatenation, simply add the 2 strings, possibly converting the rhs first. return new DynamicMetaObject( @@ -2691,13 +2691,13 @@ private DynamicMetaObject BinaryAdd(DynamicMetaObject target, DynamicMetaObject } var lhsEnumerator = PSEnumerableBinder.IsEnumerable(target); - if (lhsEnumerator != null) + if (lhsEnumerator is not null) { // target is enumerable, so we're creating a new array. var rhsEnumerator = PSEnumerableBinder.IsEnumerable(arg); Expression call; - if (rhsEnumerator != null) + if (rhsEnumerator is not null) { // Adding 2 lists call = Expression.Call(CachedReflectionInfo.EnumerableOps_AddEnumerable, @@ -2751,7 +2751,7 @@ private DynamicMetaObject BinaryMultiply(DynamicMetaObject target, DynamicMetaOb if (target.LimitType.IsNumeric()) { var numericArg = GetArgAsNumericOrPrimitive(arg, target.LimitType); - if (numericArg != null) + if (numericArg is not null) { return BinaryNumericOp("Multiply", target, numericArg); } @@ -2776,7 +2776,7 @@ private DynamicMetaObject BinaryMultiply(DynamicMetaObject target, DynamicMetaOb } var lhsEnumerator = PSEnumerableBinder.IsEnumerable(target); - if (lhsEnumerator != null) + if (lhsEnumerator is not null) { Expression argExpr = arg.LimitType == typeof(string) ? ConvertStringToNumber(arg.Expression, typeof(int)).Convert(typeof(uint)) @@ -2828,7 +2828,7 @@ private DynamicMetaObject BinarySubDivOrRem(DynamicMetaObject target, if (target.LimitType.IsNumericOrPrimitive()) { var numericArg = GetArgAsNumericOrPrimitive(arg, target.LimitType); - if (numericArg != null) + if (numericArg is not null) { return BinaryNumericOp(numericOpMethodName, target, numericArg); } @@ -2995,7 +2995,7 @@ private DynamicMetaObject BinaryBitwiseOp(DynamicMetaObject target, // Because we use unsigned for -bnot, to be consistent, we promote to unsigned here too (-band,-bor,-xor) opType = GetBitwiseOpType((int)leftTypeCode >= (int)rightTypeCode ? leftTypeCode : rightTypeCode); - if (numericTarget != null && numericArg != null) + if (numericTarget is not null && numericArg is not null) { var expr = exprGenerator(numericTarget.Expression.Cast(numericTarget.LimitType).Cast(opType), numericArg.Expression.Cast(numericArg.LimitType).Cast(opType)); @@ -3172,7 +3172,7 @@ private DynamicMetaObject CompareLT(DynamicMetaObject target, Expression result = target.LimitType.IsNumeric() ? CompareWithZero(target, Expression.LessThan) : arg.LimitType.IsNumeric() ? CompareWithZero(arg, Expression.GreaterThanOrEqual) - : arg.Value != null ? ExpressionCache.BoxedTrue + : arg.Value is not null ? ExpressionCache.BoxedTrue : ExpressionCache.BoxedFalse; return new DynamicMetaObject(result, target.CombineRestrictions(arg)); @@ -3192,7 +3192,7 @@ private DynamicMetaObject CompareLE(DynamicMetaObject target, Expression result = target.LimitType.IsNumeric() ? CompareWithZero(target, Expression.LessThan) : arg.LimitType.IsNumeric() ? CompareWithZero(arg, Expression.GreaterThanOrEqual) - : target.Value != null ? ExpressionCache.BoxedFalse + : target.Value is not null ? ExpressionCache.BoxedFalse : ExpressionCache.BoxedTrue; return new DynamicMetaObject(result, target.CombineRestrictions(arg)); @@ -3214,7 +3214,7 @@ private DynamicMetaObject CompareGT(DynamicMetaObject target, Expression result = target.LimitType.IsNumeric() ? CompareWithZero(target, Expression.GreaterThanOrEqual) : arg.LimitType.IsNumeric() ? CompareWithZero(arg, Expression.LessThan) - : target.Value != null ? ExpressionCache.BoxedTrue + : target.Value is not null ? ExpressionCache.BoxedTrue : ExpressionCache.BoxedFalse; return new DynamicMetaObject(result, target.CombineRestrictions(arg)); @@ -3236,7 +3236,7 @@ private DynamicMetaObject CompareGE(DynamicMetaObject target, Expression result = target.LimitType.IsNumeric() ? CompareWithZero(target, Expression.GreaterThanOrEqual) : arg.LimitType.IsNumeric() ? CompareWithZero(arg, Expression.LessThan) - : arg.Value != null ? ExpressionCache.BoxedFalse + : arg.Value is not null ? ExpressionCache.BoxedFalse : ExpressionCache.BoxedTrue; return new DynamicMetaObject(result, target.CombineRestrictions(arg)); @@ -3356,7 +3356,7 @@ private DynamicMetaObject BinaryComparison(DynamicMetaObject target, DynamicMeta private DynamicMetaObject BinaryComparisonCommon(DynamicMetaObject targetAsEnumerator, DynamicMetaObject target, DynamicMetaObject arg) { - if (targetAsEnumerator != null && !_scalarCompare) + if (targetAsEnumerator is not null && !_scalarCompare) { // If the target is enumerable, the we generate an object[] result with elements matching. // The iteration will be done in a pre-compiled method, but the comparison is done with @@ -3372,7 +3372,7 @@ private DynamicMetaObject BinaryComparisonCommon(DynamicMetaObject targetAsEnume if (target.LimitType.IsNumeric()) { var numericArg = GetArgAsNumericOrPrimitive(arg, target.LimitType); - if (numericArg != null) + if (numericArg is not null) { string numericMethod = null; switch (Operation) @@ -3524,7 +3524,7 @@ internal DynamicMetaObject BNot(DynamicMetaObject target, DynamicMetaObject erro // If the type implements the operator, prefer that. var method = target.LimitType.GetMethod("op_OnesComplement", BindingFlags.Static | BindingFlags.Public, null, new Type[] { target.LimitType }, null); - if (method != null) + if (method is not null) { return new DynamicMetaObject( Expression.OnesComplement(target.Expression.Cast(target.LimitType), method).Cast(typeof(object)), @@ -3600,7 +3600,7 @@ internal DynamicMetaObject BNot(DynamicMetaObject target, DynamicMetaObject erro } } - if (targetExpr != null) + if (targetExpr is not null) { Expression result = Expression.OnesComplement(targetExpr); if (target.LimitType.IsEnum) @@ -3769,7 +3769,7 @@ public override DynamicMetaObject FallbackConvert(DynamicMetaObject target, Dyna // ConstrainedLanguage, then start baking in the language mode to the binding rules. var conversion = LanguagePrimitives.FigureConversion(target.Value, resultType, out debase); - if (errorSuggestion != null && target.Value is DynamicObject) + if (errorSuggestion is not null && target.Value is DynamicObject) { return errorSuggestion.WriteToDebugLog(this); } @@ -3836,7 +3836,7 @@ internal static Expression ConvertToByRefLikeTypeViaCasting(DynamicMetaObject ar var baseObject = PSObject.Base(argument.Value); // Source value cannot be null or AutomationNull, and it cannot be a pure PSObject. - if (baseObject != null && !(baseObject is PSObject)) + if (baseObject is not null && !(baseObject is PSObject)) { Type fromType = baseObject.GetType(); ConversionRank rank = ConversionRank.None; @@ -4023,7 +4023,7 @@ public override DynamicMetaObject FallbackGetIndex(DynamicMetaObject target, Dyn if (i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IDictionary<,>)) { var result = GetIndexDictionary(target, indexes, i); - if (result != null) + if (result is not null) { return result.WriteToDebugLog(this); } @@ -4035,14 +4035,14 @@ public override DynamicMetaObject FallbackGetIndex(DynamicMetaObject target, Dyn if (defaultMember is null) { defaultMember = i.GetCustomAttributes(inherit: false).FirstOrDefault(); - if (defaultMember != null) + if (defaultMember is not null) { lengthProperty = i.GetProperty("Count") ?? i.GetProperty("Length"); } } } - if (defaultMember != null) + if (defaultMember is not null) { return InvokeIndexer(target, indexes, errorSuggestion, defaultMember.MemberName, lengthProperty).WriteToDebugLog(this); } @@ -4093,7 +4093,7 @@ private DynamicMetaObject GetIndexDictionary(DynamicMetaObject target, } var tryGetValue = idictionary.GetMethod("TryGetValue"); - Diagnostics.Assert(tryGetValue != null, "IDictionary has TryGetValue"); + Diagnostics.Assert(tryGetValue is not null, "IDictionary has TryGetValue"); var parameters = tryGetValue.GetParameters(); bool debase; @@ -4243,7 +4243,7 @@ private DynamicMetaObject GetIndexArray(DynamicMetaObject target, DynamicMetaObj } var slicingResult = CheckForSlicing(target, indexes); - if (slicingResult != null) + if (slicingResult is not null) { return slicingResult; } @@ -4305,7 +4305,7 @@ private DynamicMetaObject GetIndexMultiDimensionArray(DynamicMetaObject target, target.CombineRestrictions(indexes)); } - var intIndexes = indexes.Select(index => ConvertIndex(index, typeof(int))).Where(i => i != null).ToArray(); + var intIndexes = indexes.Select(index => ConvertIndex(index, typeof(int))).Where(i => i is not null).ToArray(); if (intIndexes.Length != indexes.Length) { if (!_allowSlicing) @@ -4354,7 +4354,7 @@ private DynamicMetaObject InvokeIndexer(DynamicMetaObject target, { // The getter takes a single argument, so first check if we're slicing. var slicingResult = CheckForSlicing(target, indexes); - if (slicingResult != null) + if (slicingResult is not null) { return slicingResult; } @@ -4400,7 +4400,7 @@ private DynamicMetaObject InvokeIndexer(DynamicMetaObject target, target.LimitType.GetProperty("Length"); } - if (lengthProperty != null) + if (lengthProperty is not null) { return IndexWithNegativeChecks( new DynamicMetaObject(target.Expression.Cast(target.LimitType), @@ -4448,7 +4448,7 @@ private DynamicMetaObject CheckForSlicing(DynamicMetaObject target, DynamicMetaO } var enumerableIndex = PSEnumerableBinder.IsEnumerable(indexes[0]); - if (enumerableIndex != null) + if (enumerableIndex is not null) { return new DynamicMetaObject( Expression.Call(CachedReflectionInfo.EnumerableOps_SlicingIndex, @@ -4600,7 +4600,7 @@ public override DynamicMetaObject FallbackSetIndex( } var defaultMember = target.LimitType.GetCustomAttributes(true).FirstOrDefault(); - if (defaultMember != null) + if (defaultMember is not null) { return (InvokeIndexer(target, indexes, value, errorSuggestion, defaultMember.MemberName)).WriteToDebugLog(this); } @@ -4682,7 +4682,7 @@ private DynamicMetaObject InvokeIndexer( PropertyInfo lengthProperty = target.LimitType.GetProperty("Length") ?? target.LimitType.GetProperty("Count"); - if (lengthProperty != null) + if (lengthProperty is not null) { return IndexWithNegativeChecks( new DynamicMetaObject(target.Expression.Cast(target.LimitType), @@ -4935,7 +4935,7 @@ public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, Dy break; } - Diagnostics.Assert(mi != null, "ReservedMemberBinder doesn't support member Name"); + Diagnostics.Assert(mi is not null, "ReservedMemberBinder doesn't support member Name"); return new DynamicMetaObject(WrapGetMemberInTry(Expression.Call(mi, targetExpr)), target.PSGetTypeRestriction()); } @@ -5064,7 +5064,7 @@ internal static void TypeTableMemberPossiblyUpdated(string memberName) public static PSGetMemberBinder Get(string memberName, TypeDefinitionAst classScope, bool @static) { - return Get(memberName, classScope != null ? classScope.Type : null, @static, false); + return Get(memberName, classScope is not null ? classScope.Type : null, @static, false); } public static PSGetMemberBinder Get(string memberName, Type classScope, bool @static) @@ -5151,7 +5151,7 @@ public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, Dy if (target.Value is PSObject && (PSObject.Base(target.Value) != target.Value)) { object baseObject = PSObject.Base(target.Value); - if (baseObject != null && Marshal.IsComObject(baseObject)) + if (baseObject is not null && Marshal.IsComObject(baseObject)) { // We unwrap only if the 'base' is a COM object. It's unnecessary to unwrap in other cases, // especially in the case of strings, we would lose instance members on the PSObject. @@ -5227,14 +5227,14 @@ public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, Dy restrictions).WriteToDebugLog(this); } - if (memberInfo != null) + if (memberInfo is not null) { Diagnostics.Assert(memberInfo.instance is 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. var propertyInfo = memberInfo as PSPropertyInfo; - if (propertyInfo != null) + if (propertyInfo is not null) { if (!propertyInfo.IsGettable) { @@ -5242,10 +5242,10 @@ public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, Dy } var property = propertyInfo as PSProperty; - if (property != null) + if (property is not null) { var adapterData = property.adapterData as DotNetAdapter.PropertyCacheEntry; - Diagnostics.Assert(adapterData != null, "We have an unknown PSProperty that we aren't correctly optimizing."); + Diagnostics.Assert(adapterData is not null, "We have an unknown PSProperty that we aren't correctly optimizing."); if (adapterData.member.DeclaringType.IsGenericTypeDefinition || adapterData.propertyType.IsByRefLike) { @@ -5259,7 +5259,7 @@ public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, Dy // because target.Expression is typeof(object) because this is a dynamic site. var targetExpr = _static ? null : GetTargetExpr(target, adapterData.member.DeclaringType); var propertyAccessor = adapterData.member as PropertyInfo; - if (propertyAccessor != null) + if (propertyAccessor is not null) { if (propertyAccessor.GetMethod.IsFamily && (_classScope is null || !_classScope.IsSubclassOf(propertyAccessor.DeclaringType))) @@ -5279,16 +5279,16 @@ public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, Dy } var scriptProperty = propertyInfo as PSScriptProperty; - if (scriptProperty != null) + if (scriptProperty is not null) { expr = Expression.Call(Expression.Constant(scriptProperty, typeof(PSScriptProperty)), CachedReflectionInfo.PSScriptProperty_InvokeGetter, target.Expression.Cast(typeof(object))); } var codeProperty = propertyInfo as PSCodeProperty; - if (codeProperty != null) + if (codeProperty is not null) { - Diagnostics.Assert(codeProperty.GetterCodeReference != null, "CodeProperty isn't gettable, should have generated error code above."); + Diagnostics.Assert(codeProperty.GetterCodeReference is not null, "CodeProperty isn't gettable, should have generated error code above."); Diagnostics.Assert(codeProperty.GetterCodeReference.IsStatic, "CodeProperty should be a static method."); expr = PSInvokeMemberBinder.InvokeMethod(codeProperty.GetterCodeReference, null, new[] { target }, @@ -5296,15 +5296,15 @@ public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, Dy } var noteProperty = propertyInfo as PSNoteProperty; - if (noteProperty != null) + if (noteProperty is not null) { Diagnostics.Assert(!noteProperty.IsSettable, "If the note is settable, incorrect code is generated."); expr = Expression.Property(Expression.Constant(propertyInfo, typeof(PSNoteProperty)), CachedReflectionInfo.PSNoteProperty_Value); } - Diagnostics.Assert(expr != null, "Unexpected property type encountered"); + Diagnostics.Assert(expr is not null, "Unexpected property type encountered"); - if (aliasConversionType != null) + if (aliasConversionType is not null) { expr = expr.Convert(aliasConversionType); } @@ -5322,7 +5322,7 @@ public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, Dy Type genericTypeArg = null; bool isGeneric = IsGenericDictionary(targetValue, ref genericTypeArg); - if (!isGeneric || genericTypeArg != null) + if (!isGeneric || genericTypeArg is not null) { var temp = Expression.Variable(typeof(object)); if (expr is null) @@ -5344,7 +5344,7 @@ public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, Dy } } - return expr != null + return expr is not null ? new DynamicMetaObject(WrapGetMemberInTry(expr), restrictions).WriteToDebugLog(this) : (errorSuggestion ?? PropertyDoesntExist(target, restrictions)).WriteToDebugLog(this); } @@ -5389,20 +5389,20 @@ internal static Expression GetTargetExpr(DynamicMetaObject target, Type castToTy // If the target value is actually a deserialized PSObject, we should use the original value var psobj = value as PSObject; - if (psobj != null && psobj != AutomationNull.Value && !psobj.IsDeserialized) + if (psobj is not null && psobj != AutomationNull.Value && !psobj.IsDeserialized) { expr = Expression.Call(CachedReflectionInfo.PSObject_Base, expr); value = PSObject.Base(value); } - var type = castToType ?? ((value != null) ? value.GetType() : typeof(object)); + var type = castToType ?? ((value is not null) ? value.GetType() : typeof(object)); // Assemblies in CoreCLR might not allow reflection execution on their internal types. In such case, we walk up // the derivation chain to find the first public parent, and use reflection methods on the public parent. if (!TypeResolver.IsPublic(type) && DotNetAdapter.DisallowPrivateReflection(type)) { var publicType = DotNetAdapter.GetFirstPublicParentType(type); - if (publicType != null) + if (publicType is not null) { type = publicType; } @@ -5416,7 +5416,7 @@ internal static Expression GetTargetExpr(DynamicMetaObject target, Type castToTy // get the underlying value by default. So "GetTargetExpr(target).Cast(typeof(object))" is actually the same as // "GetTargetExpr(target, typeof(object))". expr = type.IsValueType - ? (Nullable.GetUnderlyingType(expr.Type) != null + ? (Nullable.GetUnderlyingType(expr.Type) is not null ? (Expression)Expression.Property(expr, "Value") : Expression.Unbox(expr, type)) : expr.Cast(type); @@ -5445,7 +5445,7 @@ private DynamicMetaObject PropertyDoesntExist(DynamicMetaObject target, BindingR if (!_nonEnumerating && target.Value != AutomationNull.Value) { var enumerable = PSEnumerableBinder.IsEnumerable(target); - if (enumerable != null) + if (enumerable is not null) { return new DynamicMetaObject( Expression.Call(CachedReflectionInfo.EnumerableOps_PropertyGetter, @@ -5488,7 +5488,7 @@ private Expression ThrowPropertyNotFoundStrict() internal static DynamicMetaObject EnsureAllowedInLanguageMode(ExecutionContext context, DynamicMetaObject target, object targetValue, string name, bool isStatic, DynamicMetaObject[] args, BindingRestrictions moreTests, string errorID, string resourceString) { - if (context != null && context.LanguageMode == PSLanguageMode.ConstrainedLanguage) + if (context is not null && context.LanguageMode == PSLanguageMode.ConstrainedLanguage) { if (!IsAllowedInConstrainedLanguage(targetValue, name, isStatic)) { @@ -5554,7 +5554,7 @@ private static Expression WrapGetMemberInTry(Expression expr) private PSMemberInfo ResolveAlias(PSAliasProperty alias, DynamicMetaObject target, HashSet aliases, List aliasRestrictions) { - Diagnostics.Assert(aliasRestrictions != null, "aliasRestrictions cannot be null"); + Diagnostics.Assert(aliasRestrictions is not null, "aliasRestrictions cannot be null"); if (aliases is null) { aliases = new HashSet { alias.Name }; @@ -5622,15 +5622,15 @@ internal PSMemberInfo GetPSMemberInfo(DynamicMetaObject target, PSMemberInfo memberInfo = null; ConsolidatedString typenames = null; var context = LocalPipeline.GetExecutionContextFromTLS(); - var typeTable = context != null ? context.TypeTable : null; + var typeTable = context is not null ? context.TypeTable : null; if (hasTypeTableMember) { typenames = PSObject.GetTypeNames(target.Value); - if (typeTable != null) + if (typeTable is not null) { memberInfo = typeTable.GetMembers(typenames)[Name]; - if (memberInfo != null) + if (memberInfo is not null) { canOptimize = true; } @@ -5653,7 +5653,7 @@ internal PSMemberInfo GetPSMemberInfo(DynamicMetaObject target, // // - If not, we want to use the base object, so that we might generate optimized code. var psobj = target.Value as PSObject; - bool isTargetDeserializedObject = (psobj != null) && (psobj.IsDeserialized); + bool isTargetDeserializedObject = (psobj is not null) && (psobj.IsDeserialized); object value = isTargetDeserializedObject ? target.Value : PSObject.Base(target.Value); var adapterSet = PSObject.GetMappedAdapter(value, typeTable); @@ -5667,7 +5667,7 @@ internal PSMemberInfo GetPSMemberInfo(DynamicMetaObject target, } } - if (memberInfo is null && canOptimize && adapterSet.DotNetAdapter != null) + if (memberInfo is null && canOptimize && adapterSet.DotNetAdapter is not null) { memberInfo = adapterSet.DotNetAdapter.BaseGetMember(value, Name); } @@ -5677,13 +5677,13 @@ internal PSMemberInfo GetPSMemberInfo(DynamicMetaObject target, restrictions = versionRestriction; // When returning aliasRestrictions always include the version restriction - if (aliasRestrictions != null) + if (aliasRestrictions is not null) { aliasRestrictions.Add(versionRestriction); } var alias = memberInfo as PSAliasProperty; - if (alias != null) + if (alias is not null) { aliasConversionType = alias.ConversionType; if (aliasRestrictions is null) @@ -5706,7 +5706,7 @@ internal PSMemberInfo GetPSMemberInfo(DynamicMetaObject target, } } - if (_classScope != null && (target.LimitType == _classScope || target.LimitType.IsSubclassOf(_classScope)) && adapterSet.OriginalAdapter == PSObject.DotNetInstanceAdapter) + if (_classScope is not null && (target.LimitType == _classScope || target.LimitType.IsSubclassOf(_classScope)) && adapterSet.OriginalAdapter == PSObject.DotNetInstanceAdapter) { List candidateMethods = null; foreach (var member in _classScope.GetMembers(BindingFlags.Instance | BindingFlags.FlattenHierarchy | BindingFlags.NonPublic)) @@ -5714,7 +5714,7 @@ internal PSMemberInfo GetPSMemberInfo(DynamicMetaObject target, if (this.Name.Equals(member.Name, StringComparison.OrdinalIgnoreCase)) { var propertyInfo = member as PropertyInfo; - if (propertyInfo != null) + if (propertyInfo is not null) { var getMethod = propertyInfo.GetGetMethod(nonPublic: true); var setMethod = propertyInfo.GetSetMethod(nonPublic: true); @@ -5728,7 +5728,7 @@ internal PSMemberInfo GetPSMemberInfo(DynamicMetaObject target, else { var fieldInfo = member as FieldInfo; - if (fieldInfo != null) + if (fieldInfo is not null) { if (fieldInfo.IsFamily) { @@ -5738,7 +5738,7 @@ internal PSMemberInfo GetPSMemberInfo(DynamicMetaObject target, else { var methodInfo = member as MethodInfo; - if (methodInfo != null && (methodInfo.IsPublic || methodInfo.IsFamily)) + if (methodInfo is not null && (methodInfo.IsPublic || methodInfo.IsFamily)) { if (candidateMethods is null) { @@ -5752,17 +5752,17 @@ internal PSMemberInfo GetPSMemberInfo(DynamicMetaObject target, } } - if (candidateMethods != null && candidateMethods.Count > 0) + if (candidateMethods is not null && candidateMethods.Count > 0) { var psMethodInfo = memberInfo as PSMethod; - if (psMethodInfo != null) + if (psMethodInfo is not null) { var cacheEntry = (DotNetAdapter.MethodCacheEntry)psMethodInfo.adapterData; candidateMethods.AddRange(cacheEntry.methodInformationStructures.Select(e => e.method)); memberInfo = null; } - if (memberInfo != null) + if (memberInfo is not null) { // Ambiguous, it'd be better to report an error other than "can't find member", but I'm lazy. memberInfo = null; @@ -5825,28 +5825,28 @@ internal static object GetAdaptedValue(object obj, string member) var context = LocalPipeline.GetExecutionContextFromTLS(); PSMemberInfo memberInfo = null; - if ((context != null) && (context.TypeTable != null)) + if ((context is not null) && (context.TypeTable is not null)) { ConsolidatedString typenames = PSObject.GetTypeNames(obj); memberInfo = context.TypeTable.GetMembers(typenames)[member]; - if (memberInfo != null) + if (memberInfo is not null) { memberInfo = CloneMemberInfo(memberInfo, obj); } } - var adapterSet = PSObject.GetMappedAdapter(obj, context != null ? context.TypeTable : null); + var adapterSet = PSObject.GetMappedAdapter(obj, context is not null ? context.TypeTable : null); if (memberInfo is null) { memberInfo = adapterSet.OriginalAdapter.BaseGetMember(obj, member); } - if (memberInfo is null && adapterSet.DotNetAdapter != null) + if (memberInfo is null && adapterSet.DotNetAdapter is not null) { memberInfo = adapterSet.DotNetAdapter.BaseGetMember(obj, member); } - if (memberInfo != null) + if (memberInfo is not null) { return memberInfo.Value; } @@ -5856,7 +5856,7 @@ internal static object GetAdaptedValue(object obj, string member) return 1; } - if (context != null && context.IsStrictVersion(2)) + if (context is not null && context.IsStrictVersion(2)) { // If the member is undefined and we're in strict mode, throw an exception... throw new PropertyNotFoundException("PropertyNotFoundStrict", null, ParserStrings.PropertyNotFoundStrict, @@ -5868,13 +5868,13 @@ internal static object GetAdaptedValue(object obj, string member) internal static bool IsTypeNameSame(object value, string typeName) { - return value != null && string.Equals(PSObject.GetTypeNames(value).Key, typeName, StringComparison.OrdinalIgnoreCase); + return value is not null && string.Equals(PSObject.GetTypeNames(value).Key, typeName, StringComparison.OrdinalIgnoreCase); } internal static TypeTable GetTypeTableFromTLS() { var executionContext = LocalPipeline.GetExecutionContextFromTLS(); - return executionContext != null ? executionContext.TypeTable : null; + return executionContext is not null ? executionContext.TypeTable : null; } internal static bool TryGetInstanceMember(object value, string memberName, out PSMemberInfo memberInfo) @@ -5882,7 +5882,7 @@ internal static bool TryGetInstanceMember(object value, string memberName, out P PSMemberInfoInternalCollection instanceMembers; memberInfo = PSObject.HasInstanceMembers(value, out instanceMembers) ? instanceMembers[memberName] : null; - return (memberInfo != null); + return (memberInfo is not null); } internal static bool TryGetIDictionaryValue(IDictionary hash, string memberName, out object value) @@ -5957,7 +5957,7 @@ private static readonly Dictionary public static PSSetMemberBinder Get(string memberName, TypeDefinitionAst classScopeAst, bool @static) { - var classScope = classScopeAst != null ? classScopeAst.Type : null; + var classScope = classScopeAst is not null ? classScopeAst.Type : null; return Get(memberName, classScope, @static); } @@ -6035,7 +6035,7 @@ public override DynamicMetaObject FallbackSetMember(DynamicMetaObject target, Dy (value.Value is PSObject && (PSObject.Base(value.Value) != value.Value))) { object baseObject = PSObject.Base(target.Value); - if (baseObject != null && Marshal.IsComObject(baseObject)) + if (baseObject is not null && Marshal.IsComObject(baseObject)) { // We unwrap only if the 'base' of 'target' is a COM object. It's unnecessary to unwrap in other cases, // especially in the case that 'target' is a string, we would lose instance members on the PSObject. @@ -6111,7 +6111,7 @@ public override DynamicMetaObject FallbackSetMember(DynamicMetaObject target, Dy Type genericTypeArg = null; bool isGeneric = PSGetMemberBinder.IsGenericDictionary(targetValue, ref genericTypeArg); - if (!isGeneric || genericTypeArg != null) + if (!isGeneric || genericTypeArg is not null) { // If it's a generic, we must convert our value to genericTypeArg. var hashType = isGeneric @@ -6160,7 +6160,7 @@ public override DynamicMetaObject FallbackSetMember(DynamicMetaObject target, Dy DynamicMetaObject runtimeError = PSGetMemberBinder.EnsureAllowedInLanguageMode( context, target, targetValue, Name, _static, new[] { value }, restrictions, "PropertySetterNotSupportedInConstrainedLanguage", ParserStrings.PropertySetConstrainedLanguage); - if (runtimeError != null) + if (runtimeError is not null) { return runtimeError.WriteToDebugLog(this); } @@ -6185,7 +6185,7 @@ public override DynamicMetaObject FallbackSetMember(DynamicMetaObject target, Dy } var psPropertyInfo = memberInfo as PSPropertyInfo; - if (psPropertyInfo != null) + if (psPropertyInfo is not null) { if (!psPropertyInfo.IsSettable) { @@ -6193,10 +6193,10 @@ public override DynamicMetaObject FallbackSetMember(DynamicMetaObject target, Dy } var psProperty = psPropertyInfo as PSProperty; - if (psProperty != null) + if (psProperty is not null) { var data = psProperty.adapterData as DotNetAdapter.PropertyCacheEntry; - if (data != null) + if (data is not null) { Expression expr; @@ -6253,7 +6253,7 @@ public override DynamicMetaObject FallbackSetMember(DynamicMetaObject target, Dy // For static property access, the target expr must be null. For non-static, we must convert // because target.Expression is typeof(object) because this is a dynamic site. var targetExpr = _static ? null : PSGetMemberBinder.GetTargetExpr(target, data.member.DeclaringType); - if (propertyInfo != null) + if (propertyInfo is not null) { if (propertyInfo.SetMethod.IsFamily && (_classScope is null || !_classScope.IsSubclassOf(propertyInfo.DeclaringType))) @@ -6274,7 +6274,7 @@ public override DynamicMetaObject FallbackSetMember(DynamicMetaObject target, Dy } var nullableUnderlyingType = Nullable.GetUnderlyingType(lhsType); - if (nullableUnderlyingType != null) + if (nullableUnderlyingType is not null) { if (value.Value is null) { @@ -6342,7 +6342,7 @@ public override DynamicMetaObject FallbackSetMember(DynamicMetaObject target, Dy } var codeProperty = psPropertyInfo as PSCodeProperty; - if (codeProperty != null) + if (codeProperty is not null) { var setterMethod = codeProperty.SetterCodeReference; var parameters = setterMethod.GetParameters(); @@ -6381,7 +6381,7 @@ public override DynamicMetaObject FallbackSetMember(DynamicMetaObject target, Dy } var scriptProperty = psPropertyInfo as PSScriptProperty; - if (scriptProperty != null) + if (scriptProperty is not null) { // Invoke Setter @@ -6395,7 +6395,7 @@ public override DynamicMetaObject FallbackSetMember(DynamicMetaObject target, Dy Diagnostics.Assert(false, "The property we're trying to set was unexpected."); } - if (errorSuggestion != null) + if (errorSuggestion is not null) { return errorSuggestion.WriteToDebugLog(this); } @@ -6429,28 +6429,28 @@ internal static object SetAdaptedValue(object obj, string member, object value) var context = LocalPipeline.GetExecutionContextFromTLS(); PSMemberInfo memberInfo = null; - if ((context != null) && (context.TypeTable != null)) + if ((context is not null) && (context.TypeTable is not null)) { ConsolidatedString typenames = PSObject.GetTypeNames(obj); memberInfo = context.TypeTable.GetMembers(typenames)[member]; - if (memberInfo != null) + if (memberInfo is not null) { memberInfo = PSGetMemberBinder.CloneMemberInfo(memberInfo, obj); } } - var adapterSet = PSObject.GetMappedAdapter(obj, context != null ? context.TypeTable : null); + var adapterSet = PSObject.GetMappedAdapter(obj, context is not null ? context.TypeTable : null); if (memberInfo is null) { memberInfo = adapterSet.OriginalAdapter.BaseGetMember(obj, member); } - if (memberInfo is null && adapterSet.DotNetAdapter != null) + if (memberInfo is null && adapterSet.DotNetAdapter is not null) { memberInfo = adapterSet.DotNetAdapter.BaseGetMember(obj, member); } - if (memberInfo != null) + if (memberInfo is not null) { memberInfo.Value = value; } @@ -6597,7 +6597,7 @@ public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "PSInvokeMember: {0}{1}{2} ver:{3} args:{4} constraints:<{5}>", _static ? "static " : string.Empty, _propertySetter ? "propset " : string.Empty, - Name, _getMemberBinder._version, CallInfo.ArgumentCount, _invocationConstraints != null ? _invocationConstraints.ToString() : string.Empty); + Name, _getMemberBinder._version, CallInfo.ArgumentCount, _invocationConstraints is not null ? _invocationConstraints.ToString() : string.Empty); } public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion) @@ -6612,7 +6612,7 @@ public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, args.Any(mo => mo.Value is PSObject && (PSObject.Base(mo.Value) != mo.Value))) { object baseObject = PSObject.Base(target.Value); - if (baseObject != null && Marshal.IsComObject(baseObject)) + if (baseObject is not null && Marshal.IsComObject(baseObject)) { // We unwrap only if the 'base' of 'target' is a COM object. It's unnecessary to unwrap in other cases, // especially in the case that 'target' is a string, we would lose instance members on the PSObject. @@ -6710,7 +6710,7 @@ public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, DynamicMetaObject runtimeError = PSGetMemberBinder.EnsureAllowedInLanguageMode( context, target, targetValue, Name, _static, args, restrictions, "MethodInvocationNotSupportedInConstrainedLanguage", ParserStrings.InvokeMethodConstrainedLanguage); - if (runtimeError != null) + if (runtimeError is not null) { return runtimeError.WriteToDebugLog(this); } @@ -6759,7 +6759,7 @@ public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, if (methodInfo is PSMethod || methodInfo is PSParameterizedProperty) { var psObj = target.Value as PSObject; - if (psObj != null && (targetValue.GetType() == typeof(Hashtable) || targetValue.GetType() == typeof(ArrayList))) + if (psObj is not null && (targetValue.GetType() == typeof(Hashtable) || targetValue.GetType() == typeof(ArrayList))) { // If we get here, then the target value should have 'isDeserialized == false', otherwise we cannot get a .NET methodInfo // from _getMemberBinder.GetPSMemberInfo(). This is because when 'isDeserialized' is true, we use the PSObject to find the @@ -6773,7 +6773,7 @@ public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, } var psMethod = methodInfo as PSMethod; - if (psMethod != null) + if (psMethod is not null) { var data = (DotNetAdapter.MethodCacheEntry)psMethod.adapterData; @@ -6782,7 +6782,7 @@ public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, } var scriptMethod = methodInfo as PSScriptMethod; - if (scriptMethod != null) + if (scriptMethod is not null) { return new DynamicMetaObject( Expression.Call(CachedReflectionInfo.PSScriptMethod_InvokeScript, @@ -6795,7 +6795,7 @@ public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, } var codeMethod = methodInfo as PSCodeMethod; - if (codeMethod != null) + if (codeMethod is not null) { Expression expr = InvokeMethod(codeMethod.CodeReference, null, args.Prepend(target).ToArray(), false, MethodInvocationType.Ordinary); if (codeMethod.CodeReference.ReturnType == typeof(void)) @@ -6811,7 +6811,7 @@ public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, } var parameterizedProperty = methodInfo as PSParameterizedProperty; - if (parameterizedProperty != null) + if (parameterizedProperty is not null) { var p = (DotNetAdapter.ParameterizedPropertyCacheEntry)parameterizedProperty.adapterData; return InvokeDotNetMethod(CallInfo, Name, _invocationConstraints, _propertySetter ? MethodInvocationType.Setter : MethodInvocationType.Ordinary, target, args, restrictions, @@ -6819,7 +6819,7 @@ public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, _propertySetter ? typeof(SetValueInvocationException) : typeof(GetValueInvocationException)).WriteToDebugLog(this); } - if (errorSuggestion != null) + if (errorSuggestion is not null) { return errorSuggestion.WriteToDebugLog(this); } @@ -6839,7 +6839,7 @@ public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, } var enumerableTarget = PSEnumerableBinder.IsEnumerable(target); - if (enumerableTarget != null) + if (enumerableTarget is not null) { // Try calling the method on each member of the collection. return InvokeMemberOnCollection(enumerableTarget, args, targetValue.GetType(), restrictions).WriteToDebugLog(this); @@ -6896,7 +6896,7 @@ internal static DynamicMetaObject InvokeDotNetMethod( methodInvocationType = MethodInvocationType.NonVirtual; } - if (result != null) + if (result is not null) { var methodInfo = result.method; var expr = InvokeMethod(methodInfo, target, args, expandParamsOnBest, methodInvocationType); @@ -6972,7 +6972,7 @@ internal static MethodInfo FindBestMethod(DynamicMetaObject target, MethodInfo result = null; var psMethod = PSObject.DotNetInstanceAdapter.GetDotNetMethod(PSObject.Base(target.Value), methodName); - if (psMethod != null) + if (psMethod is not null) { var data = (DotNetAdapter.MethodCacheEntry)psMethod.adapterData; @@ -6991,7 +6991,7 @@ internal static MethodInfo FindBestMethod(DynamicMetaObject target, out expandParameters, out callNonVirtually); - if (mi != null) + if (mi is not null) { result = (MethodInfo)mi.method; } @@ -7008,7 +7008,7 @@ internal static Expression InvokeMethod(MethodBase mi, DynamicMetaObject target, ConstructorInfo constructorInfo = null; MethodInfo methodInfo = mi as MethodInfo; - if (methodInfo != null) + if (methodInfo is not null) { Type returnType = methodInfo.ReturnType; if (returnType.IsByRefLike) @@ -7084,7 +7084,7 @@ internal static Expression InvokeMethod(MethodBase mi, DynamicMetaObject target, // This inconsistent behavior affects OneCore powershell because we are using the extension method here when compiling // against CoreCLR. So we need to add a null check until this is fixed in CLR. var paramArrayAttrs = parameters[i].GetCustomAttributes(typeof(ParamArrayAttribute), false); - if (paramArrayAttrs != null && paramArrayAttrs.Length > 0) + if (paramArrayAttrs is not null && paramArrayAttrs.Length > 0) { Diagnostics.Assert(i == parameters.Length - 1, "vararg parameter is not the last"); var paramElementType = parameterType.GetElementType(); @@ -7164,7 +7164,7 @@ internal static Expression InvokeMethod(MethodBase mi, DynamicMetaObject target, } Expression call; - if (constructorInfo != null) + if (constructorInfo is not null) { if (invocationType == MethodInvocationType.BaseCtor) { @@ -7355,7 +7355,7 @@ internal static bool IsHomogenousArray(object[] args) return args.All(element => { var obj = PSObject.Base(element); - return obj != null && obj.GetType().Equals(typeof(T)); + return obj is not null && obj.GetType().Equals(typeof(T)); }); } @@ -7394,14 +7394,14 @@ internal static bool IsHeterogeneousArray(object[] args) internal static object InvokeAdaptedMember(object obj, string methodName, object[] args) { var context = LocalPipeline.GetExecutionContextFromTLS(); - var adapterSet = PSObject.GetMappedAdapter(obj, context != null ? context.TypeTable : null); + var adapterSet = PSObject.GetMappedAdapter(obj, context is not null ? context.TypeTable : null); var methodInfo = adapterSet.OriginalAdapter.BaseGetMember(obj, methodName) as PSMethodInfo; - if (methodInfo is null && adapterSet.DotNetAdapter != null) + if (methodInfo is null && adapterSet.DotNetAdapter is not null) { methodInfo = adapterSet.DotNetAdapter.BaseGetMember(obj, methodName) as PSMethodInfo; } - if (methodInfo != null) + if (methodInfo is not null) { return methodInfo.Invoke(args); } @@ -7439,14 +7439,14 @@ internal static object InvokeAdaptedMember(object obj, string methodName, object internal static object InvokeAdaptedSetMember(object obj, string methodName, object[] args, object valueToSet) { var context = LocalPipeline.GetExecutionContextFromTLS(); - var adapterSet = PSObject.GetMappedAdapter(obj, context != null ? context.TypeTable : null); + var adapterSet = PSObject.GetMappedAdapter(obj, context is not null ? context.TypeTable : null); var methodInfo = adapterSet.OriginalAdapter.BaseGetMember(obj, methodName); - if (methodInfo is null && adapterSet.DotNetAdapter != null) + if (methodInfo is null && adapterSet.DotNetAdapter is not null) { methodInfo = adapterSet.DotNetAdapter.BaseGetMember(obj, methodName); } - if (methodInfo != null) + if (methodInfo is not null) { methodInfo.InvokeSet(valueToSet, args); return valueToSet; @@ -7560,7 +7560,7 @@ internal PSCreateInstanceBinder(CallInfo callInfo, PSMethodInvocationConstraints public override string ToString() { return string.Format(CultureInfo.InvariantCulture, - "PSCreateInstanceBinder: ver:{0} args:{1} constraints:<{2}>", _version, _callInfo.ArgumentCount, _constraints != null ? _constraints.ToString() : string.Empty); + "PSCreateInstanceBinder: ver:{0} args:{1} constraints:<{2}>", _version, _callInfo.ArgumentCount, _constraints is not null ? _constraints.ToString() : string.Empty); } public override DynamicMetaObject FallbackCreateInstance(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion) @@ -7624,7 +7624,7 @@ public override DynamicMetaObject FallbackCreateInstance(DynamicMetaObject targe } var context = LocalPipeline.GetExecutionContextFromTLS(); - if (context != null && context.LanguageMode == PSLanguageMode.ConstrainedLanguage && !CoreTypes.Contains(instanceType)) + if (context is not null && context.LanguageMode == PSLanguageMode.ConstrainedLanguage && !CoreTypes.Contains(instanceType)) { return target.ThrowRuntimeError(restrictions, "CannotCreateTypeConstrainedLanguage", ParserStrings.CannotCreateTypeConstrainedLanguage).WriteToDebugLog(this); } @@ -7665,7 +7665,7 @@ internal static bool IsTargetTypeNonPublic(object target) internal static string GetTargetTypeName(object target) { var targetValue = PSObject.Base(target); - Diagnostics.Assert(targetValue != null, "caller makes sure target is not null"); + Diagnostics.Assert(targetValue is not null, "caller makes sure target is not null"); var instanceType = targetValue as Type ?? targetValue.GetType(); return instanceType.FullName; diff --git a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs index f4232035963..3ea62816083 100644 --- a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs +++ b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs @@ -86,7 +86,7 @@ private void InitializeMetadata() { lock (this) { - if (_attributes != null) + if (_attributes is not null) { // Another thread must have initialized the metadata. return; @@ -117,7 +117,7 @@ private void InitializeMetadata() } } - _usesCmdletBinding = cmdletBindingAttribute != null; + _usesCmdletBinding = cmdletBindingAttribute is not null; } bool automaticPosition = cmdletBindingAttribute is null || cmdletBindingAttribute.PositionalBinding; @@ -203,7 +203,7 @@ private void PerformSecurityChecks() var scriptExtent = scriptBlockAst.Extent; var scriptFile = scriptExtent.File; - if (scriptFile != null + if (scriptFile is not null && scriptFile.EndsWith(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase) && IsScriptBlockInFactASafeHashtable()) { @@ -233,7 +233,7 @@ private void PerformSecurityChecks() throw new ParseException(new[] { parseError }); } - if (ScriptBlock.CheckSuspiciousContent(scriptBlockAst) != null) + if (ScriptBlock.CheckSuspiciousContent(scriptBlockAst) is not null) { HasSuspiciousContent = true; } @@ -246,11 +246,11 @@ bool IsScriptBlockInFactASafeHashtable() // are enhanced, such as new members added to 'ScriptBlockAst', the code here needs // to be reviewed and changed accordingly. - if (scriptBlockAst.BeginBlock != null - || scriptBlockAst.ProcessBlock != null - || scriptBlockAst.ParamBlock != null - || scriptBlockAst.DynamicParamBlock != null - || scriptBlockAst.ScriptRequirements != null + if (scriptBlockAst.BeginBlock is not null + || scriptBlockAst.ProcessBlock is not null + || scriptBlockAst.ParamBlock is not null + || scriptBlockAst.DynamicParamBlock is not null + || scriptBlockAst.ScriptRequirements is not null || scriptBlockAst.UsingStatements.Count > 0 || scriptBlockAst.Attributes.Count > 0) { @@ -258,7 +258,7 @@ bool IsScriptBlockInFactASafeHashtable() } NamedBlockAst endBlock = scriptBlockAst.EndBlock; - if (!endBlock.Unnamed || endBlock.Traps != null || endBlock.Statements.Count != 1) + if (!endBlock.Unnamed || endBlock.Traps is not null || endBlock.Statements.Count != 1) { return false; } @@ -292,7 +292,7 @@ private IParameterMetadataProvider DelayParseScriptText() { lock (this) { - if (_ast != null) + if (_ast is not null) { return _ast; } @@ -361,7 +361,7 @@ internal bool GetIsConfiguration() // If we access Ast, we may parse a "delay parsed" script block unnecessarily // if _ast is null - it can't be a configuration as there is no way to create a configuration that way var scriptBlockAst = _ast as ScriptBlockAst; - return scriptBlockAst != null && scriptBlockAst.IsConfiguration; + return scriptBlockAst is not null && scriptBlockAst.IsConfiguration; } internal bool HasSuspiciousContent @@ -387,7 +387,7 @@ internal List GetAttributes() } Diagnostics.Assert( - _attributes != null, + _attributes is not null, "after initialization, attributes is never null, must be an empty list if no attributes."); return _attributes.ToList(); } @@ -396,7 +396,7 @@ internal bool UsesCmdletBinding { get { - if (_attributes != null) + if (_attributes is not null) { return _usesCmdletBinding; } @@ -489,7 +489,7 @@ public MergedCommandParameterMetadata GetParameterMetadata(ScriptBlock scriptBlo public override string ToString() { - if (_scriptText != null) + if (_scriptText is not null) { return _scriptText; } @@ -500,7 +500,7 @@ public override string ToString() } var generatedMemberFunctionAst = _ast as CompilerGeneratedMemberFunctionAst; - if (generatedMemberFunctionAst != null) + if (generatedMemberFunctionAst is not null) { return generatedMemberFunctionAst.Extent.Text; } @@ -543,7 +543,7 @@ private ScriptBlock(CompiledScriptBlockData scriptBlockData) // InitialSessionState, etc.) should explicitly set the LanguageMode to FullLanguage // when they are created. ExecutionContext context = LocalPipeline.GetExecutionContextFromTLS(); - if (context != null) + if (context is not null) { this.LanguageMode = context.LanguageMode; } @@ -580,7 +580,7 @@ internal static ScriptBlock TryGetCachedScriptBlock(string fileName, string file } private static bool IsDynamicKeyword(Ast ast) - => ast is CommandAst cmdAst && cmdAst.DefiningKeyword != null; + => ast is CommandAst cmdAst && cmdAst.DefiningKeyword is not null; private static bool IsUsingTypes(Ast ast) => ast is UsingStatementAst cmdAst && cmdAst.IsUsingModuleOrAssembly(); @@ -600,8 +600,8 @@ internal static void CacheScriptBlock(ScriptBlock scriptBlock, string fileName, // TODO(sevoroby): we can optimize it to ignore 'using' if there are no actual type usage in locally defined types. // using is always a top-level statements in scriptBlock, we don't need to search in child blocks. - if (scriptBlock.Ast.Find(ast => IsUsingTypes(ast), false) != null - || scriptBlock.Ast.Find(ast => IsDynamicKeyword(ast), true) != null) + if (scriptBlock.Ast.Find(ast => IsUsingTypes(ast), false) is not null + || scriptBlock.Ast.Find(ast => IsDynamicKeyword(ast), true) is not null) { return; } @@ -629,7 +629,7 @@ internal static void ClearScriptBlockCache() internal static ScriptBlock Create(Parser parser, string fileName, string fileContents) { var scriptBlock = TryGetCachedScriptBlock(fileName, fileContents); - if (scriptBlock != null) + if (scriptBlock is not null) { return scriptBlock; } @@ -671,7 +671,7 @@ internal string ToStringWithDollarUsingHandling( } string sbText = sbAst.ToStringForSerialization(usingVariablesTuple, sbAst.Extent.StartOffset, sbAst.Extent.EndOffset); - if (sbAst.ParamBlock != null) + if (sbAst.ParamBlock is not null) { return sbText; } @@ -727,7 +727,7 @@ internal SteppablePipeline GetSteppablePipelineImpl(CommandOrigin commandOrigin, { var pipelineAst = GetSimplePipeline( resourceString => { throw PSTraceSource.NewInvalidOperationException(resourceString); }); - Diagnostics.Assert(pipelineAst != null, "This should be checked by GetSimplePipeline"); + Diagnostics.Assert(pipelineAst is not null, "This should be checked by GetSimplePipeline"); if (!(pipelineAst.PipelineElements[0] is CommandAst)) { @@ -758,7 +758,7 @@ private PipelineAst GetSimplePipeline(Func errorHandler) return errorHandler(AutomationExceptions.CanOnlyConvertOnePipeline); } - if (ast.Body.EndBlock.Traps != null && ast.Body.EndBlock.Traps.Count > 0) + if (ast.Body.EndBlock.Traps is not null && ast.Body.EndBlock.Traps.Count > 0) { return errorHandler(AutomationExceptions.CantConvertScriptBlockWithTrap); } @@ -792,7 +792,7 @@ internal MergedCommandParameterMetadata ParameterMetadata internal bool UsesCmdletBinding { get => _scriptBlockData.UsesCmdletBinding; } - internal bool HasDynamicParameters { get => AstInternal.Body.DynamicParamBlock != null; } + internal bool HasDynamicParameters { get => AstInternal.Body.DynamicParamBlock is not null; } /// /// DebuggerHidden. @@ -846,7 +846,7 @@ internal HelpInfo GetHelpInfo( helpUriFromDotLink = null; var commentTokens = HelpCommentsParser.GetHelpCommentTokens(AstInternal, scriptBlockTokenCache); - if (commentTokens != null) + if (commentTokens is not null) { return HelpCommentsParser.CreateFromComments( context, @@ -880,7 +880,7 @@ public void CheckRestrictedLanguage( Parser parser = new Parser(); var ast = AstInternal; - if (HasBeginBlock || HasProcessBlock || ast.Body.ParamBlock != null) + if (HasBeginBlock || HasProcessBlock || ast.Body.ParamBlock is not null) { Ast errorAst = ast.Body.BeginBlock ?? (Ast)ast.Body.ProcessBlock ?? ast.Body.ParamBlock; parser.ReportError( @@ -983,10 +983,10 @@ 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, - "When calling ScriptBlock.InvokeWithContext(), if 'functionsToDefine' != null then 'createLocalScope' must be true"); + "When calling ScriptBlock.InvokeWithContext(), if 'functionsToDefine' is not null then 'createLocalScope' must be true"); Diagnostics.Assert( createLocalScope || variablesToDefine is null, - "When calling ScriptBlock.InvokeWithContext(), if 'variablesToDefine' != null then 'createLocalScope' must be true"); + "When calling ScriptBlock.InvokeWithContext(), if 'variablesToDefine' is not null then 'createLocalScope' must be true"); if (args is null) { @@ -1055,7 +1055,7 @@ internal void InvokeWithPipeImpl( if (myInvocationInfo is null) { var callerFrame = context.Debugger.GetCallStack().LastOrDefault(); - var extent = (callerFrame != null) + var extent = (callerFrame is not null) ? callerFrame.FunctionContext.CurrentPosition : Ast.Extent; myInvocationInfo = new InvocationInfo(null, extent, context); @@ -1063,7 +1063,7 @@ internal void InvokeWithPipeImpl( locals.SetAutomaticVariable(AutomaticVariable.MyInvocation, myInvocationInfo, context); - if (SessionStateInternal != null) + if (SessionStateInternal is not null) { context.EngineSessionState = SessionStateInternal; } @@ -1089,7 +1089,7 @@ internal void InvokeWithPipeImpl( context.EngineSessionState.CurrentScope = newScope; newScope.LocalsTuple = locals; // Inject passed in functions into the scope - if (functionsToDefine != null) + if (functionsToDefine is not null) { foreach (var def in functionsToDefine) { @@ -1115,7 +1115,7 @@ internal void InvokeWithPipeImpl( } } // Inject passed in variables into the scope - if (variablesToDefine != null) + if (variablesToDefine is not null) { int index = 0; foreach (var psvar in variablesToDefine) @@ -1219,14 +1219,14 @@ internal void InvokeWithPipeImpl( { context.EngineSessionState.RemoveScope(context.EngineSessionState.CurrentScope); } - else if (backupWhenDotting != null) + else if (backupWhenDotting is not null) { context.EngineSessionState.CurrentScope.DottedScopes.Pop(); - Diagnostics.Assert(backupWhenDotting != null, "when dotting, this dictionary isn't null"); + Diagnostics.Assert(backupWhenDotting is not null, "when dotting, this dictionary isn't null"); foreach (var pair in backupWhenDotting) { - if (pair.Value != null) + if (pair.Value is not null) { context.EngineSessionState.SetVariable(pair.Value, false, CommandOrigin.Internal); } @@ -1302,7 +1302,7 @@ internal static object[] BindArgumentsForScriptblockInvoke( } bool valueSet = false; - if (dotting && backupWhenDotting != null) + if (dotting && backupWhenDotting is not null) { backupWhenDotting[parameter.Name] = context.EngineSessionState.GetVariableAtScope(parameter.Name, "local"); @@ -1460,7 +1460,7 @@ private static bool WriteScriptBlockToLog(ScriptBlock scriptBlock, int segment, ProtectedEventLogging logSetting = Utils.GetPolicySetting(Utils.SystemWideOnlyConfig); bool wasEncoded = false; - if (logSetting != null) + if (logSetting is not null) { lock (s_syncObject) { @@ -1475,7 +1475,7 @@ private static bool WriteScriptBlockToLog(ScriptBlock scriptBlock, int segment, // If we have recipients to encrypt to, then do so. // Otherwise, we'll just log the plain text version. - if (s_encryptionRecipients != null) + if (s_encryptionRecipients is not null) { // Encrypt the raw text from the scriptblock. // The user may have to deal with any control characters in the data. @@ -1489,7 +1489,7 @@ private static bool WriteScriptBlockToLog(ScriptBlock scriptBlock, int segment, out error); // Can't cache the reporting of encryption errors, as they are likely content-based. - if (error != null) + if (error is not null) { // If we got an error encrypting the content, log an error and continue // logging the (unencrypted) message anyways. Logging trumps protected logging - @@ -1608,14 +1608,14 @@ private static bool GetAndValidateEncryptionRecipients( if (logSetting.EnableProtectedEventLogging == true) { // Get the encryption certificate - if (logSetting.EncryptionCertificate != null) + if (logSetting.EncryptionCertificate is not null) { ErrorRecord error = null; ExecutionContext executionContext = LocalPipeline.GetExecutionContextFromTLS(); SessionState sessionState = null; // Use the session state from the current pipeline, if it exists. - if (executionContext != null) + if (executionContext is not null) { sessionState = executionContext.SessionState; } @@ -1634,7 +1634,7 @@ private static bool GetAndValidateEncryptionRecipients( ResetCertificateCacheIfNeeded(fullCertificateContent); // If we have valid recipients, no need for further analysis. - if (s_encryptionRecipients != null) + if (s_encryptionRecipients is not null) { return true; } @@ -1653,7 +1653,7 @@ private static bool GetAndValidateEncryptionRecipients( // If there's an error that we haven't already reported, report it in the event log. // We only do this once, as the error will always be the same for a given certificate. - if (error != null) + if (error is not null) { // If we got an error resolving the encryption certificate, log a warning and continue // logging the (unencrypted) message anyways. Logging trumps protected logging - @@ -1751,7 +1751,7 @@ private static ScriptBlockLogging GetScriptBlockLoggingSetting() internal static string CheckSuspiciousContent(Ast scriptBlockAst) { var foundSignature = SuspiciousContentChecker.Match(scriptBlockAst.Extent.Text); - if (foundSignature != null) + if (foundSignature is not null) { return foundSignature; } @@ -1765,7 +1765,7 @@ internal static string CheckSuspiciousContent(Ast scriptBlockAst) return (!ast.HasSuspiciousContent) && ast.Parent.HasSuspiciousContent; }, true); - if (foundAst != null) + if (foundAst is not null) { return foundAst.Parent.Extent.Text; } @@ -1961,7 +1961,7 @@ private static string CheckForMatches(uint[] runningHash, int upTo) for (var i = 0; i < upTo; i++) { var result = LookupHash(runningHash[i]); - if (result != null) + if (result is not null) { return result; } @@ -2032,7 +2032,7 @@ public static string Match(string text) if (++longestPossiblePattern >= 4) { var result = CheckForMatches(runningHash, longestPossiblePattern); - if (result != null) return result; + if (result is not null) return result; } } @@ -2136,11 +2136,11 @@ internal static void LogScriptBlockEnd(ScriptBlock scriptBlock, Guid runspaceId) internal Action UnoptimizedEndBlock { get => _scriptBlockData.UnoptimizedEndBlock; } - internal bool HasBeginBlock { get => AstInternal.Body.BeginBlock != null; } + internal bool HasBeginBlock { get => AstInternal.Body.BeginBlock is not null; } - internal bool HasProcessBlock { get => AstInternal.Body.ProcessBlock != null; } + internal bool HasProcessBlock { get => AstInternal.Body.ProcessBlock is not null; } - internal bool HasEndBlock { get => AstInternal.Body.EndBlock != null; } + internal bool HasEndBlock { get => AstInternal.Body.EndBlock is not null; } } [Serializable] diff --git a/src/System.Management.Automation/engine/runtime/MutableTuple.cs b/src/System.Management.Automation/engine/runtime/MutableTuple.cs index de923e2df8b..d0a8c87accc 100644 --- a/src/System.Management.Automation/engine/runtime/MutableTuple.cs +++ b/src/System.Management.Automation/engine/runtime/MutableTuple.cs @@ -369,7 +369,7 @@ internal static IEnumerable GetAccessProperties(Type tupleType, in foreach (int curIndex in GetAccessPath(size, index)) { PropertyInfo pi = tupleType.GetProperty("Item" + string.Format(CultureInfo.InvariantCulture, "{0:D3}", curIndex)); - Diagnostics.Assert(pi != null, "reflection should always find Item"); + Diagnostics.Assert(pi is not null, "reflection should always find Item"); yield return pi; tupleType = pi.PropertyType; } @@ -452,7 +452,7 @@ private static Type MakeTupleType(Type[] types, int start, int end) int size = end - start; Type type = GetTupleType(size); - if (type != null) + if (type is not null) { Type[] typeArr = new Type[type.GetGenericArguments().Length]; int index = 0; @@ -476,7 +476,7 @@ private static Type MakeTupleType(Type[] types, int start, int end) } type = MutableTuple.GetTupleType(size); - Diagnostics.Assert(type != null, "type cannot be null"); + Diagnostics.Assert(type is not null, "type cannot be null"); Type[] nestedTypes = new Type[type.GetGenericArguments().Length]; for (int i = 0; i < size; i++) { @@ -520,7 +520,7 @@ private static int PowerOfTwoRound(int value) internal static Expression CreateNew(Type tupleType, int start, int end, Expression[] values) { int size = end - start; - Diagnostics.Assert(tupleType != null, "tupleType cannot be null"); + Diagnostics.Assert(tupleType is not null, "tupleType cannot be null"); Diagnostics.Assert(tupleType.IsSubclassOf(typeof(MutableTuple)), "tupleType must be derived from MutableTuple"); Expression[] newValues; diff --git a/src/System.Management.Automation/engine/runtime/Operations/ArrayOps.cs b/src/System.Management.Automation/engine/runtime/Operations/ArrayOps.cs index c532bd66532..c34b4870e47 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/ArrayOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/ArrayOps.cs @@ -43,7 +43,7 @@ internal static object[] SlicingIndex(object target, object[] indexes, FuncCollection multiplied by integer. internal static T[] Multiply(T[] array, uint times) { - Diagnostics.Assert(array != null, "Caller should verify the arguments for array multiplication"); + Diagnostics.Assert(array is not null, "Caller should verify the arguments for array multiplication"); if (times == 1) { @@ -56,7 +56,7 @@ internal static T[] Multiply(T[] array, uint times) } var context = LocalPipeline.GetExecutionContextFromTLS(); - if (context != null && + if (context is not null && context.LanguageMode == PSLanguageMode.RestrictedLanguage && (array.Length * times) > 1024) { throw InterpreterError.NewInterpreterException(times, typeof(RuntimeException), @@ -117,7 +117,7 @@ internal static object GetMDArrayValue(Array array, int[] indexes, bool slicing) { // In strict mode, don't return, fall through and let Array.GetValue raise an exception. var context = LocalPipeline.GetExecutionContextFromTLS(); - if (context != null && !context.IsStrictVersion(3)) + if (context is not null && !context.IsStrictVersion(3)) { // If we're slicing, return AutomationNull.Value to signal no result) return slicing ? AutomationNull.Value : null; @@ -144,7 +144,7 @@ internal static object GetMDArrayValueOrSlice(Array array, object indexes) whyFailed = ice; } - if (indexArray != null) + if (indexArray is not null) { if (indexArray.Length != array.Rank) { @@ -172,7 +172,7 @@ internal static object GetMDArrayValueOrSlice(Array array, object indexes) if (indexArray is null || indexArray.Length != array.Rank) { - if (whyFailed != null) + if (whyFailed is not null) { // If the first fails, report the original exception and all indices ReportIndexingError(array, indexes, whyFailed); @@ -271,7 +271,7 @@ internal static object GetNonIndexable(object target, object[] indices) if (indices.Length == 1) { var index = indices[0]; - if (index != null && (LanguagePrimitives.Equals(0, index) || LanguagePrimitives.Equals(-1, index))) + if (index is not null && (LanguagePrimitives.Equals(0, index) || LanguagePrimitives.Equals(-1, index))) { return target; } diff --git a/src/System.Management.Automation/engine/runtime/Operations/ClassOps.cs b/src/System.Management.Automation/engine/runtime/Operations/ClassOps.cs index 8e7cc34df52..c45f343eefb 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/ClassOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/ClassOps.cs @@ -85,7 +85,7 @@ public object GetSessionState() // a PowerShell class by using reflection on a thread without DefaultRunspace. // Make sure we call 'TryGetValue' with a non-null key, otherwise ArgumentNullException will be thrown. Runspace defaultRunspace = Runspace.DefaultRunspace; - if (defaultRunspace != null) + if (defaultRunspace is not null) { _stateMap.TryGetValue(defaultRunspace, out ss); } @@ -195,7 +195,7 @@ internal void InitAtRuntime() private void PrepareScriptBlockToInvoke(object instance, object sessionStateInternal) { SessionStateInternal sessionStateToUse = null; - if (instance != null) + if (instance is not null) { // Use the SessionState passed in, which is the one associated with the instance. sessionStateToUse = (SessionStateInternal)sessionStateInternal; diff --git a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs index c729061ba63..0242e08ffc1 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs @@ -33,7 +33,7 @@ private static CommandProcessorBase AddCommand(PipelineProcessor pipe, ExecutionContext context) { var commandAst = commandBaseAst as CommandAst; - var invocationToken = commandAst != null ? commandAst.InvocationOperator : TokenKind.Unknown; + var invocationToken = commandAst is not null ? commandAst.InvocationOperator : TokenKind.Unknown; bool dotSource = invocationToken == TokenKind.Dot; SessionStateInternal commandSessionState = null; int commandIndex = 0; @@ -41,7 +41,7 @@ private static CommandProcessorBase AddCommand(PipelineProcessor pipe, Diagnostics.Assert(commandElements[0].ArgumentSpecified && !commandElements[0].ParameterNameSpecified, "Compiler will pass first parameter as an argument."); var mi = PSObject.Base(commandElements[0].ArgumentValue) as PSModuleInfo; - if (mi != null) + if (mi is not null) { if (mi.ModuleType == ModuleType.Binary && mi.SessionState is null) { @@ -90,14 +90,14 @@ private static CommandProcessorBase AddCommand(PipelineProcessor pipe, string invocationName = (dotSource) ? "." : invocationToken == TokenKind.Ampersand ? "&" : null; CommandProcessorBase commandProcessor; var scriptBlock = command as ScriptBlock; - if (scriptBlock != null) + if (scriptBlock is not null) { commandProcessor = CommandDiscovery.CreateCommandProcessorForScript(scriptBlock, context, !dotSource, commandSessionState); } else { var commandInfo = command as CommandInfo; - if (commandInfo != null) + if (commandInfo is not null) { commandProcessor = context.CommandDiscovery.LookupCommandProcessor(commandInfo, context.EngineSessionState.CurrentScope.ScopeOrigin, !dotSource, commandSessionState); } @@ -122,7 +122,7 @@ private static CommandProcessorBase AddCommand(PipelineProcessor pipe, // See if we need to resolve the command in a different session state // as will be the case with modules... // BUGBUG - this can be cleaned up by fixing the overload on execution context (but not easily.) - if (commandSessionState != null) + if (commandSessionState is not null) { SessionStateInternal oldSessionState = context.EngineSessionState; try @@ -205,7 +205,7 @@ private static CommandProcessorBase AddCommand(PipelineProcessor pipe, bool redirectedVerbose = false; bool redirectedDebug = false; bool redirectedInformation = false; - if (redirections != null) + if (redirections is not null) { foreach (var redirection in redirections) { @@ -246,7 +246,7 @@ private static CommandProcessorBase AddCommand(PipelineProcessor pipe, // Pipe redirection can also be specified via the ExecutionContext pipes. if (!redirectedError) { - if (context.ShellFunctionErrorOutputPipe != null) + if (context.ShellFunctionErrorOutputPipe is not null) { commandProcessor.CommandRuntime.ErrorOutputPipe = context.ShellFunctionErrorOutputPipe; } @@ -256,53 +256,53 @@ private static CommandProcessorBase AddCommand(PipelineProcessor pipe, } } - if (!redirectedWarning && (context.ExpressionWarningOutputPipe != null)) + if (!redirectedWarning && (context.ExpressionWarningOutputPipe is not null)) { commandProcessor.CommandRuntime.WarningOutputPipe = context.ExpressionWarningOutputPipe; redirectedWarning = true; } - if (!redirectedVerbose && (context.ExpressionVerboseOutputPipe != null)) + if (!redirectedVerbose && (context.ExpressionVerboseOutputPipe is not null)) { commandProcessor.CommandRuntime.VerboseOutputPipe = context.ExpressionVerboseOutputPipe; redirectedVerbose = true; } - if (!redirectedDebug && (context.ExpressionDebugOutputPipe != null)) + if (!redirectedDebug && (context.ExpressionDebugOutputPipe is not null)) { commandProcessor.CommandRuntime.DebugOutputPipe = context.ExpressionDebugOutputPipe; redirectedDebug = true; } - if (!redirectedInformation && (context.ExpressionInformationOutputPipe != null)) + if (!redirectedInformation && (context.ExpressionInformationOutputPipe is not null)) { commandProcessor.CommandRuntime.InformationOutputPipe = context.ExpressionInformationOutputPipe; redirectedInformation = true; } // Warning, Verbose, Debug should pick up any redirection information from its parent command runtime object. - if (context.CurrentCommandProcessor != null && context.CurrentCommandProcessor.CommandRuntime != null) + if (context.CurrentCommandProcessor is not null && context.CurrentCommandProcessor.CommandRuntime is not null) { if (!redirectedWarning && - context.CurrentCommandProcessor.CommandRuntime.WarningOutputPipe != null) + context.CurrentCommandProcessor.CommandRuntime.WarningOutputPipe is not null) { commandProcessor.CommandRuntime.WarningOutputPipe = context.CurrentCommandProcessor.CommandRuntime.WarningOutputPipe; } if (!redirectedVerbose && - context.CurrentCommandProcessor.CommandRuntime.VerboseOutputPipe != null) + context.CurrentCommandProcessor.CommandRuntime.VerboseOutputPipe is not null) { commandProcessor.CommandRuntime.VerboseOutputPipe = context.CurrentCommandProcessor.CommandRuntime.VerboseOutputPipe; } if (!redirectedDebug && - context.CurrentCommandProcessor.CommandRuntime.DebugOutputPipe != null) + context.CurrentCommandProcessor.CommandRuntime.DebugOutputPipe is not null) { commandProcessor.CommandRuntime.DebugOutputPipe = context.CurrentCommandProcessor.CommandRuntime.DebugOutputPipe; } if (!redirectedInformation && - context.CurrentCommandProcessor.CommandRuntime.InformationOutputPipe != null) + context.CurrentCommandProcessor.CommandRuntime.InformationOutputPipe is not null) { commandProcessor.CommandRuntime.InformationOutputPipe = context.CurrentCommandProcessor.CommandRuntime.InformationOutputPipe; } @@ -324,7 +324,7 @@ internal static IEnumerable Splat(object splattedValue } IDictionary splattedTable = splattedValue as IDictionary; - if (splattedTable != null) + if (splattedTable is not null) { foreach (DictionaryEntry de in splattedTable) { @@ -345,7 +345,7 @@ internal static IEnumerable Splat(object splattedValue else { IEnumerable enumerableValue = splattedValue as IEnumerable; - if (enumerableValue != null) + if (enumerableValue is not null) { foreach (object obj in enumerableValue) { @@ -367,11 +367,11 @@ internal static IEnumerable Splat(object splattedValue private static CommandParameterInternal SplatEnumerableElement(object splattedArgument, Ast splatAst) { var psObject = splattedArgument as PSObject; - if (psObject != null) + if (psObject is not null) { var prop = psObject.Properties[ScriptParameterBinderController.NotePropertyNameForSplattingParametersInArgs]; var baseObj = psObject.BaseObject; - if (prop != null && prop.Value is string && baseObj is string) + if (prop is not null && prop.Value is string && baseObj is string) { return CommandParameterInternal.CreateParameter((string)prop.Value, (string)baseObj, splatAst); } @@ -382,7 +382,7 @@ private static CommandParameterInternal SplatEnumerableElement(object splattedAr private static string GetParameterText(string parameterName) { - Diagnostics.Assert(parameterName != null, "caller makes sure the parameterName is not null"); + Diagnostics.Assert(parameterName is not null, "caller makes sure the parameterName is not null"); int endPosition = parameterName.Length; while ((endPosition > 0) && char.IsWhiteSpace(parameterName[endPosition - 1])) { @@ -421,7 +421,7 @@ internal static void InvokePipeline(object input, try { - if (context.Events != null) + if (context.Events is not null) { context.Events.ProcessPendingActions(); } @@ -444,7 +444,7 @@ internal static void InvokePipeline(object input, for (int i = 0; i < pipeElements.Length; i++) { - commandRedirection = commandRedirections != null ? commandRedirections[i] : null; + commandRedirection = commandRedirections is not null ? commandRedirections[i] : null; commandProcessor = AddCommand(pipelineProcessor, pipeElements[i], pipeElementAsts[i], commandRedirection, context); } @@ -470,12 +470,12 @@ internal static void InvokePipeline(object input, } } - if (commandProcessor != null && !commandProcessor.CommandRuntime.OutputPipe.IsRedirected) + if (commandProcessor is not null && !commandProcessor.CommandRuntime.OutputPipe.IsRedirected) { pipelineProcessor.LinkPipelineSuccessOutput(outputPipe ?? new Pipe(new List())); // Fix up merge redirection bindings on last command processor. - if (commandRedirection != null) + if (commandRedirection is not null) { foreach (CommandRedirection redirection in commandRedirection) { @@ -514,7 +514,7 @@ internal static void InvokePipelineInBackground( try { - if (context.Events != null) + if (context.Events is not null) { context.Events.ProcessPendingActions(); } @@ -609,12 +609,12 @@ internal static object CheckAutomationNullInCommandArgument(object obj) } var objAsArray = obj as object[]; - return objAsArray != null ? CheckAutomationNullInCommandArgumentArray(objAsArray) : obj; + return objAsArray is not null ? CheckAutomationNullInCommandArgumentArray(objAsArray) : obj; } internal static object[] CheckAutomationNullInCommandArgumentArray(object[] objArray) { - if (objArray != null) + if (objArray is not null) { for (int i = 0; i < objArray.Length; ++i) { @@ -652,7 +652,7 @@ internal static SteppablePipeline GetSteppablePipeline(PipelineAst pipelineAst, // * Arguments are provided // * The ScriptBlock has parameters // If the script block has no parameter, RuntimeDefinedParameters.Data will be set to RuntimeDefinedParameterDictionary.EmptyParameterArray - bool useParameter = (args != null && args.Length > 0) && + bool useParameter = (args is not null && args.Length > 0) && scriptBlock.RuntimeDefinedParameters.Data != RuntimeDefinedParameterDictionary.EmptyParameterArray; try @@ -686,7 +686,7 @@ internal static SteppablePipeline GetSteppablePipeline(PipelineAst pipelineAst, foreach (var commandElement in commandAst.CommandElements) { var commandParameterAst = commandElement as CommandParameterAst; - if (commandParameterAst != null) + if (commandParameterAst is not null) { commandParameters.Add(GetCommandParameter(commandParameterAst, isTrusted, context)); continue; @@ -734,7 +734,7 @@ internal static SteppablePipeline GetSteppablePipeline(PipelineAst pipelineAst, if (callStack.Length > 1) { var displayPosition = callStack[1].Position; - if (displayPosition != null && displayPosition != PositionUtilities.EmptyExtent) + if (displayPosition is not null && displayPosition != PositionUtilities.EmptyExtent) { myInvocation.DisplayScriptPosition = displayPosition; } @@ -742,7 +742,7 @@ internal static SteppablePipeline GetSteppablePipeline(PipelineAst pipelineAst, } // Set the data stream merge properties based on ExecutionContext. - if (context.CurrentCommandProcessor != null && context.CurrentCommandProcessor.CommandRuntime != null) + if (context.CurrentCommandProcessor is not null && context.CurrentCommandProcessor.CommandRuntime is not null) { commandProcessor.CommandRuntime.SetMergeFromRuntime(context.CurrentCommandProcessor.CommandRuntime); } @@ -772,7 +772,7 @@ private static CommandParameterInternal GetCommandParameter(CommandParameterAst private static CommandRedirection GetCommandRedirection(RedirectionAst redirectionAst, bool isTrusted, ExecutionContext context) { var fileRedirection = redirectionAst as FileRedirectionAst; - if (fileRedirection != null) + if (fileRedirection is not null) { object fileName = Compiler.GetExpressionValue(fileRedirection.Location, isTrusted, context); return new FileRedirection(fileRedirection.FromStream, fileRedirection.Append, fileName.ToString()); @@ -829,7 +829,7 @@ internal static ExitException GetExitException(object exitCodeObj) internal static void CheckForInterrupts(ExecutionContext context) { - if (context.Events != null) + if (context.Events is not null) { context.Events.ProcessPendingActions(); } @@ -1053,7 +1053,7 @@ internal override void Bind(PipelineProcessor pipelineProcessor, CommandProcesso // Normally, context.CurrentCommandProcessor will not be null. But in legacy DRTs from ParserTest.cs, // a scriptblock may be invoked through 'DoInvokeReturnAsIs' using .NET reflection. In that case, // context.CurrentCommandProcessor will be null. We don't try passing along variable lists in such case. - if (context.CurrentCommandProcessor != null) + if (context.CurrentCommandProcessor is not null) { context.CurrentCommandProcessor.CommandRuntime.OutputPipe.SetVariableListForTemporaryPipe(pipe); } @@ -1067,7 +1067,7 @@ internal override void Bind(PipelineProcessor pipelineProcessor, CommandProcesso break; case RedirectionStream.Output: // Since a temp output pipe is going to be used, we should pass along the error and warning variable list. - if (context.CurrentCommandProcessor != null) + if (context.CurrentCommandProcessor is not null) { context.CurrentCommandProcessor.CommandRuntime.OutputPipe.SetVariableListForTemporaryPipe(pipe); } @@ -1160,7 +1160,7 @@ internal Pipe GetRedirectionPipe(ExecutionContext context, PipelineProcessor par } CommandProcessorBase commandProcessor = context.CreateCommand("out-file", false); - Diagnostics.Assert(commandProcessor != null, "CreateCommand returned null"); + Diagnostics.Assert(commandProcessor is not null, "CreateCommand returned null"); // Previously, we mandated Unicode encoding here // Now, We can take what ever has been set if PSDefaultParameterValues @@ -1202,7 +1202,7 @@ internal Pipe GetRedirectionPipe(ExecutionContext context, PipelineProcessor par throw; } - if (parentPipelineProcessor != null) + if (parentPipelineProcessor is not null) { // I think this is only necessary for calling Dispose on the commands in the redirection pipe. parentPipelineProcessor.AddRedirectionPipe(PipelineProcessor); @@ -1222,7 +1222,7 @@ internal Pipe GetRedirectionPipe(ExecutionContext context, PipelineProcessor par internal void CallDoCompleteForExpression() { // The pipe returned from 'GetRedirectionPipe' could be a NullPipe - if (PipelineProcessor != null) + if (PipelineProcessor is not null) { PipelineProcessor.DoComplete(); } @@ -1243,7 +1243,7 @@ private void Dispose(bool disposing) if (disposing) { - if (PipelineProcessor != null) + if (PipelineProcessor is not null) { PipelineProcessor.Dispose(); } @@ -1439,7 +1439,7 @@ private static void FindAndProcessHandler(Type[] types, int[] ranks, Exception exception, ErrorRecord errorRecord) { - Diagnostics.Assert(current != null, "Caller makes sure 'current' is not null."); + Diagnostics.Assert(current is not null, "Caller makes sure 'current' is not null."); int handler = FindMatchingHandlerByType(exception.GetType(), types); // If no handler was found, return without changing the current result. @@ -1483,7 +1483,7 @@ internal static int FindMatchingHandler(MutableTuple tuple, RuntimeException rte ErrorRecord errorRecordToPass = rte.ErrorRecord; Exception inner = rte.InnerException; - if (inner != null) + if (inner is not null) { FindAndProcessHandler(types, ranks, current, inner, errorRecordToPass); } @@ -1504,24 +1504,24 @@ internal static int FindMatchingHandler(MutableTuple tuple, RuntimeException rte if (current.Rank > 0) { var apse = rte as ActionPreferenceStopException; - if (apse != null) + if (apse is not null) { var exceptionToPass = apse.ErrorRecord.Exception; // If it's again a RuntimeException, we repeat the search using it rte = exceptionToPass as RuntimeException; - if (rte != null) + if (rte is not null) { continueToSearch = true; } - else if (exceptionToPass != null) + else if (exceptionToPass is not null) { FindAndProcessHandler(types, ranks, current, exceptionToPass, errorRecordToPass); } } - else if (rte is CmdletInvocationException && inner != null) + else if (rte is CmdletInvocationException && inner is not null) { - if (inner.InnerException != null) + if (inner.InnerException is not null) { FindAndProcessHandler(types, ranks, current, inner.InnerException, errorRecordToPass); } @@ -1575,7 +1575,7 @@ private static int FindMatchingHandlerByType(Type exceptionType, Type[] types) internal static bool SuspendStoppingPipeline(ExecutionContext context) { LocalPipeline lpl = (LocalPipeline)context.CurrentRunspace.GetCurrentlyRunningPipeline(); - if (lpl != null) + if (lpl is not null) { bool oldIsStopping = lpl.Stopper.IsStopping; lpl.Stopper.IsStopping = false; @@ -1588,7 +1588,7 @@ internal static bool SuspendStoppingPipeline(ExecutionContext context) internal static void RestoreStoppingPipeline(ExecutionContext context, bool oldIsStopping) { LocalPipeline lpl = (LocalPipeline)context.CurrentRunspace.GetCurrentlyRunningPipeline(); - if (lpl != null) + if (lpl is not null) { lpl.Stopper.IsStopping = oldIsStopping; } @@ -1637,7 +1637,7 @@ context.CurrentExceptionBeingHandled is null && // A null action script is only used to indicate when exceptions // should be thrown up to a higher level, and doesn't count as an // actual trap handler in the function context. - bool anyTrapHandlers = funcContext._traps.Count > 0 && funcContext._traps[funcContext._traps.Count - 1].Item2 != null; + bool anyTrapHandlers = funcContext._traps.Count > 0 && funcContext._traps[funcContext._traps.Count - 1].Item2 is not null; if (anyTrapHandlers) { @@ -1692,7 +1692,7 @@ private static ActionPreference ProcessTraps(FunctionContext funcContext, var types = funcContext._traps.Last().Item1; var handlers = funcContext._traps.Last().Item2; - if (inner != null) + if (inner is not null) { handler = FindMatchingHandlerByType(inner.GetType(), types); exception = inner; @@ -1713,7 +1713,7 @@ private static ActionPreference ProcessTraps(FunctionContext funcContext, if (handler != -1) { - Diagnostics.Assert(exception != null, "Exception object can't be null."); + Diagnostics.Assert(exception is not null, "Exception object can't be null."); var context = funcContext._executionContext; @@ -1722,7 +1722,7 @@ private static ActionPreference ProcessTraps(FunctionContext funcContext, ErrorRecord err = rte.ErrorRecord; // CurrentCommandProcessor is normally not null, but it is null // when executing some unit tests through reflection. - if (context.CurrentCommandProcessor != null) + if (context.CurrentCommandProcessor is not null) { context.CurrentCommandProcessor.ForgetScriptException(); } @@ -1901,7 +1901,7 @@ internal static void SetErrorVariables(IScriptExtent extent, RuntimeException rt Exception e = rte; int i = 0; - while (e != null && i++ < 10) + while (e is not null && i++ < 10) { if (!string.IsNullOrEmpty(e.StackTrace)) { @@ -1913,13 +1913,13 @@ internal static void SetErrorVariables(IScriptExtent extent, RuntimeException rt context.SetVariable(SpecialVariables.StackTraceVarPath, stack); - Diagnostics.Assert(rte.ErrorRecord != null, "The runtime exception's error record was null"); + Diagnostics.Assert(rte.ErrorRecord is not null, "The runtime exception's error record was null"); InterpreterError.UpdateExceptionErrorRecordPosition(rte, extent); ErrorRecord errRec = rte.ErrorRecord.WrapException(rte); if (!(rte is PipelineStoppedException)) { - if (outputPipe != null) + if (outputPipe is not null) { outputPipe.AppendVariableList(VariableStreamKind.Error, errRec); } @@ -1949,9 +1949,9 @@ internal static bool ReportErrorRecord(IScriptExtent extent, RuntimeException rt if (context.ShellFunctionErrorOutputPipe is null) return false; - Diagnostics.Assert(rte.ErrorRecord != null, "The runtime exception's error record was null"); + Diagnostics.Assert(rte.ErrorRecord is not null, "The runtime exception's error record was null"); - if (rte.ErrorRecord.InvocationInfo is null && extent != null && extent != PositionUtilities.EmptyExtent) + if (rte.ErrorRecord.InvocationInfo is null && extent is not null && extent != PositionUtilities.EmptyExtent) rte.ErrorRecord.SetInvocationInfo(new InvocationInfo(null, extent, context)); PSObject errorWrap = PSObject.AsPSObject(new ErrorRecord(rte.ErrorRecord, rte)); @@ -1977,7 +1977,7 @@ internal static RuntimeException ConvertToException(object result, IScriptExtent result = PSObject.Base(result); RuntimeException runtimeException = result as RuntimeException; - if (runtimeException != null) + if (runtimeException is not null) { InterpreterError.UpdateExceptionErrorRecordPosition(runtimeException, extent); runtimeException.WasThrownFromThrowStatement = true; @@ -1986,7 +1986,7 @@ internal static RuntimeException ConvertToException(object result, IScriptExtent } ErrorRecord er = result as ErrorRecord; - if (er != null) + if (er is not null) { runtimeException = new RuntimeException(er.ToString(), er.Exception, er) { WasThrownFromThrowStatement = true, WasRethrown = rethrow }; InterpreterError.UpdateExceptionErrorRecordPosition(runtimeException, extent); @@ -1995,7 +1995,7 @@ internal static RuntimeException ConvertToException(object result, IScriptExtent } Exception exception = result as Exception; - if (exception != null) + if (exception is not null) { er = new ErrorRecord(exception, exception.Message, ErrorCategory.OperationStopped, null); runtimeException = new RuntimeException(exception.Message, exception, er) { WasThrownFromThrowStatement = true, WasRethrown = rethrow }; @@ -2022,7 +2022,7 @@ internal static RuntimeException ConvertToRuntimeException(Exception exception, if (runtimeException is null) { var icer = exception as IContainsErrorRecord; - var er = icer != null + var er = icer is not null ? icer.ErrorRecord : new ErrorRecord(exception, exception.GetType().FullName, ErrorCategory.OperationStopped, null); runtimeException = new RuntimeException(exception.Message, exception, er); @@ -2106,10 +2106,10 @@ internal static Type ResolveTypeName(ITypeName typeName, IScriptExtent errorPos) if (result is null) { - if (exception != null) + if (exception is not null) { if (exception is InvalidCastException && - exception.InnerException != null && + exception.InnerException is not null && exception.InnerException is TypeResolver.AmbiguousTypeException) { throw exception; @@ -2126,14 +2126,14 @@ internal static Type ResolveTypeName(ITypeName typeName, IScriptExtent errorPos) // then we just throw on the top level typeName. var genericTypeName = typeName as GenericTypeName; - if (genericTypeName != null) + if (genericTypeName is not null) { var generic = genericTypeName.GetGenericType(ResolveTypeName(genericTypeName.TypeName, errorPos)); var typeArgs = (from arg in genericTypeName.GenericArguments select ResolveTypeName(arg, errorPos)).ToArray(); try { - if (generic != null && generic.ContainsGenericParameters) + if (generic is not null && generic.ContainsGenericParameters) generic.MakeGenericType(typeArgs); } catch (Exception e) @@ -2147,7 +2147,7 @@ internal static Type ResolveTypeName(ITypeName typeName, IScriptExtent errorPos) var arrayTypeName = typeName as ArrayTypeName; - if (arrayTypeName != null) + if (arrayTypeName is not null) { ResolveTypeName(arrayTypeName.ElementType, errorPos); } @@ -2279,7 +2279,7 @@ internal static void AddPowerShellTypesToTheScope(Dictionary"); - Diagnostics.Assert(helperType != null, "no corresponding " + t.Type.FullName + "_ type found"); + Diagnostics.Assert(helperType is not null, "no corresponding " + t.Type.FullName + "_ type found"); foreach (var p in helperType.GetFields(BindingFlags.Static | BindingFlags.NonPublic)) { var field = p.GetValue(null); // field can be one of two types: SessionStateKeeper or ScriptBlockMemberMethodWrapper var methodWrapper = field as ScriptBlockMemberMethodWrapper; - if (methodWrapper != null) + if (methodWrapper is not null) { methodWrapper.InitAtRuntime(); } @@ -2337,7 +2337,7 @@ internal static bool ConditionSatisfiedWildcard(bool caseSensitive, ExecutionContext context) { WildcardPattern wildcard = condition as WildcardPattern; - if (wildcard != null) + if (wildcard is not null) { // If case sensitivity doesn't agree between the existing wildcard pattern and the switch mode, // make a new wildcard pattern that agrees with the switch. @@ -2373,7 +2373,7 @@ internal static bool ConditionSatisfiedRegex(bool caseSensitive, Regex regex = condition as Regex; // Check if the regex agrees with the switch w.r.t. case sensitivity, if not, // we must build a new regex. - if (regex != null && (((regex.Options & RegexOptions.IgnoreCase) != 0) != caseSensitive)) + if (regex is not null && (((regex.Options & RegexOptions.IgnoreCase) != 0) != caseSensitive)) { m = regex.Match(str); } @@ -2397,7 +2397,7 @@ internal static bool ConditionSatisfiedRegex(bool caseSensitive, if (groups.Count > 0) { - Diagnostics.Assert(regex != null, "Logic above ensures regex is not null."); + Diagnostics.Assert(regex is not null, "Logic above ensures regex is not null."); Hashtable h = new Hashtable(StringComparer.CurrentCultureIgnoreCase); @@ -2435,7 +2435,7 @@ internal static string ResolveFilePath(IScriptExtent errorExtent, object obj, Ex try { FileInfo file = obj as FileInfo; - string filePath = file != null ? file.FullName : PSObject.ToStringParser(context, obj); + string filePath = file is not null ? file.FullName : PSObject.ToStringParser(context, obj); if (string.IsNullOrEmpty(filePath)) { @@ -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 is not null && rte.ErrorRecord.InvocationInfo is null) rte.ErrorRecord.SetInvocationInfo(new InvocationInfo(null, errorExtent, context)); throw; } @@ -2534,7 +2534,7 @@ internal static class EnumerableOps /// internal static object Where(IEnumerator enumerator, ScriptBlock expressionSB, WhereOperatorSelectionMode selectionMode, int numberToReturn) { - Diagnostics.Assert(enumerator != null, "The Where() operator should never receive a null enumerator value from the runtime."); + Diagnostics.Assert(enumerator is not null, "The Where() operator should never receive a null enumerator value from the runtime."); if (numberToReturn < 0) { @@ -2767,8 +2767,8 @@ internal static object Where(IEnumerator enumerator, ScriptBlock expressionSB, W /// An object array containing the results of the expression evaluation. internal static object ForEach(IEnumerator enumerator, object expression, object[] arguments) { - 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."); + Diagnostics.Assert(enumerator is not null, "The ForEach() operator should never receive a null enumerator value from the runtime."); + Diagnostics.Assert(arguments is not null, "The ForEach() operator should never receive a null value for the 'arguments' parameter from the runtime."); if (expression is null) { throw new ArgumentNullException(nameof(expression)); @@ -2780,11 +2780,11 @@ internal static object ForEach(IEnumerator enumerator, object expression, object // if the target type is a collection or array, then the result will be a collection of exactly // that type. If the target type is not a collection type then return a generic collection of that type. Type targetType = expression as Type; - if (targetType != null) + if (targetType is not null) { dynamic resultCollection = null; - if (targetType.GetInterface("System.Collections.ICollection") != null) + if (targetType.GetInterface("System.Collections.ICollection") is not null) { // If the target type is an array, accumulate all the elements // then use the PowerShell type converter to turn it into an array @@ -2849,7 +2849,7 @@ internal static object ForEach(IEnumerator enumerator, object expression, object // once on each element. var result = new Collection(); ScriptBlock sb = expression as ScriptBlock; - if (sb != null) + if (sb is not null) { Pipe outputPipe = new Pipe(result); if (sb.HasBeginBlock) @@ -2886,7 +2886,7 @@ internal static object ForEach(IEnumerator enumerator, object expression, object object current = Current(enumerator); object basedCurrent = PSObject.Base(current); Hashtable ht = basedCurrent as Hashtable; - if (ht != null) + if (ht is not null) { // special case hashtables since we don't want to hit a method name switch (numArgs) @@ -2894,7 +2894,7 @@ internal static object ForEach(IEnumerator enumerator, object expression, object case 0: // No args so do a set object element = ht[name]; - result.Add(element != null ? PSObject.AsPSObject(element) : null); + result.Add(element is not null ? PSObject.AsPSObject(element) : null); break; case 1: @@ -2959,7 +2959,7 @@ internal static object ForEach(IEnumerator enumerator, object expression, object } var method = member as PSMethodInfo; - if (method != null) + if (method is not null) { // It's a method so check language modes to see if it's allowed. @@ -3015,7 +3015,7 @@ internal static object ForEach(IEnumerator enumerator, object expression, object internal static object SlicingIndex(object target, IEnumerator indexes, Func indexer) { var fakeEnumerator = indexes as NonEnumerableObjectEnumerator; - if (fakeEnumerator != null) + if (fakeEnumerator is not null) { // We have a non-enumerable object, we're trying to slice index with it. It really should have // been a single index, so we don't want to return an array, we just want to return the indexed value. @@ -3038,7 +3038,7 @@ internal static object SlicingIndex(object target, IEnumerator indexes, Func result) { var e = LanguagePrimitives.GetEnumerator(o); - if (e != null) + if (e is not null) { while (e.MoveNext()) { @@ -3073,7 +3073,7 @@ private static void PropertyGetterWorker(CallSite { // Recurse through collections if current didn't have the property. var nestedEnumerator = LanguagePrimitives.GetEnumerator(current); - if (nestedEnumerator != null) + if (nestedEnumerator is not null) { PropertyGetterWorker(getMemberBinderSite, nestedEnumerator, context, result); } @@ -3147,10 +3147,10 @@ private static void MethodInvokerWorker(CallSite invokeMemberSite, { // If we tried to invoke a method that didn't exist, then we'll try enumerating the object and call the method on it's members. RuntimeException rte = tie.InnerException as RuntimeException; - if (rte != null && rte.ErrorRecord.FullyQualifiedErrorId.Equals(ParserOps.MethodNotFoundErrorId, StringComparison.Ordinal)) + if (rte is not null && rte.ErrorRecord.FullyQualifiedErrorId.Equals(ParserOps.MethodNotFoundErrorId, StringComparison.Ordinal)) { var nestedEnumerator = LanguagePrimitives.GetEnumerator(current); - if (nestedEnumerator != null) + if (nestedEnumerator is not null) { MethodInvokerWorker(invokeMemberSite, nestedEnumerator, args, context, result, ref foundMethod); continue; @@ -3206,7 +3206,7 @@ internal static object MethodInvoker(PSInvokeMemberBinder binder, internal static object Multiply(IEnumerator enumerator, uint times) { var fakeEnumerator = enumerator as NonEnumerableObjectEnumerator; - if (fakeEnumerator != null) + if (fakeEnumerator is not null) { // We have a non-enumerable object, we're trying to multiply something to it. Generate an error // (or on the off chance that there is an implicit op, call that). @@ -3302,7 +3302,7 @@ internal static IEnumerator GetCOMEnumerator(object obj) try { var enumerator = (targetValue as IEnumerable)?.GetEnumerator(); - if (enumerator != null) + if (enumerator is not null) { return enumerator; } @@ -3348,7 +3348,7 @@ internal static bool MoveNext(ExecutionContext context, IEnumerator enumerator) try { // Check to see if we're stopping... - if (context != null && context.CurrentPipelineStopping) + if (context is not null && context.CurrentPipelineStopping) throw new PipelineStoppedException(); return enumerator.MoveNext(); @@ -3408,14 +3408,14 @@ internal static object AddFakeEnumerable(NonEnumerableObjectEnumerator fakeEnume // (or on the off chance that there is an implicit op, call that). var fakeEnumerator2 = rhs as NonEnumerableObjectEnumerator; return ParserOps.ImplicitOp(fakeEnumerator.GetNonEnumerableObject(), - fakeEnumerator2 != null ? fakeEnumerator2.GetNonEnumerableObject() : rhs, + fakeEnumerator2 is not null ? fakeEnumerator2.GetNonEnumerableObject() : rhs, "op_Addition", null, "+"); } internal static object AddEnumerable(ExecutionContext context, IEnumerator lhs, IEnumerator rhs) { var fakeEnumerator = lhs as NonEnumerableObjectEnumerator; - if (fakeEnumerator != null) + if (fakeEnumerator is not null) { return AddFakeEnumerable(fakeEnumerator, rhs); } @@ -3438,7 +3438,7 @@ internal static object AddEnumerable(ExecutionContext context, IEnumerator lhs, internal static object AddObject(ExecutionContext context, IEnumerator lhs, object rhs) { var fakeEnumerator = lhs as NonEnumerableObjectEnumerator; - if (fakeEnumerator != null) + if (fakeEnumerator is not null) { return AddFakeEnumerable(fakeEnumerator, rhs); } @@ -3458,7 +3458,7 @@ internal static object AddObject(ExecutionContext context, IEnumerator lhs, obje internal static object Compare(IEnumerator enumerator, object valueToCompareTo, Func compareDelegate) { var fakeEnumerator = enumerator as NonEnumerableObjectEnumerator; - if (fakeEnumerator != null) + if (fakeEnumerator is not null) { return compareDelegate(fakeEnumerator.GetNonEnumerableObject(), valueToCompareTo) ? Boxed.True : Boxed.False; } @@ -3490,7 +3490,7 @@ internal static void WriteEnumerableToPipe(IEnumerator enumerator, Pipe pipe, Ex if (dispose) { var disposable = enumerator as IDisposable; - if (disposable != null) + if (disposable is not null) { disposable.Dispose(); } diff --git a/src/System.Management.Automation/engine/runtime/Operations/StringOps.cs b/src/System.Management.Automation/engine/runtime/Operations/StringOps.cs index 0c4658cc14d..2337ecd7dbc 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/StringOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/StringOps.cs @@ -26,7 +26,7 @@ internal static string Add(string lhs, char rhs) internal static string Multiply(string s, int times) { - Diagnostics.Assert(s != null, "caller to verify argument is not null"); + Diagnostics.Assert(s is not null, "caller to verify argument is not null"); if (times < 0) { @@ -40,7 +40,7 @@ internal static string Multiply(string s, int times) } var context = LocalPipeline.GetExecutionContextFromTLS(); - if (context != null && + if (context is not null && context.LanguageMode == PSLanguageMode.RestrictedLanguage && (s.Length * times) > 1024) { throw InterpreterError.NewInterpreterException(times, typeof(RuntimeException), @@ -70,7 +70,7 @@ internal static string FormatOperator(string formatString, object formatArgs) try { object[] formatArgsArray = formatArgs as object[]; - return formatArgsArray != null + return formatArgsArray is not null ? StringUtil.Format(formatString, formatArgsArray) : StringUtil.Format(formatString, formatArgs); } @@ -92,7 +92,7 @@ internal static string FormatOperator(string formatString, object formatArgs) /// internal static int Compare(string strA, string strB, CultureInfo culture, CompareOptions option) { - Diagnostics.Assert(culture != null, "Caller makes sure that 'culture' is not null."); + Diagnostics.Assert(culture is not null, "Caller makes sure that 'culture' is not null."); return culture.CompareInfo.Compare(strA, strB, option); } @@ -104,7 +104,7 @@ internal static int Compare(string strA, string strB, CultureInfo culture, Compa /// internal static bool Equals(string strA, string strB, CultureInfo culture, CompareOptions option) { - Diagnostics.Assert(culture != null, "Caller makes sure that 'culture' is not null."); + Diagnostics.Assert(culture is not null, "Caller makes sure that 'culture' is not null."); return culture.CompareInfo.Compare(strA, strB, option) == 0; } } diff --git a/src/System.Management.Automation/engine/runtime/Operations/VariableOps.cs b/src/System.Management.Automation/engine/runtime/Operations/VariableOps.cs index a2c6cc93a97..06a7c616c19 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/VariableOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/VariableOps.cs @@ -57,7 +57,7 @@ internal static object SetVariableValue(VariablePath variablePath, object value, } else { - if (attributeAsts != null) + if (attributeAsts is not null) { // Use bytewise operation directly instead of 'var.IsReadOnly || var.IsConstant' on // a hot path (setting variable with type constraint) to get better performance. @@ -81,7 +81,7 @@ internal static object SetVariableValue(VariablePath variablePath, object value, null, Metadata.InvalidValueFailure, var.Name, - ((value != null) ? value.ToString() : "$null")); + ((value is not null) ? value.ToString() : "$null")); throw e; } @@ -130,7 +130,7 @@ private static bool ThrowStrictModeUndefinedVariable(ExecutionContext executionC if (executionContext.IsStrictVersion(1)) { var parent = varAst.Parent; - while (parent != null) + while (parent is not null) { if (parent is ExpandableStringExpressionAst) { @@ -187,7 +187,7 @@ internal static object GetVariableValue(VariablePath variablePath, ExecutionCont SessionStateScope scope; PSVariable var = sessionState.GetVariableItem(variablePath, out scope, origin); - if (var != null) + if (var is not null) { return var.Value; } @@ -224,10 +224,10 @@ internal static PSReference GetVariableAsRef(VariablePath variablePath, Executio } object value = var.Value; - if (staticType is null && value != null) + if (staticType is null && value is not null) { value = PSObject.Base(value); - if (value != null) + if (value is not null) { staticType = value.GetType(); } @@ -236,7 +236,7 @@ internal static PSReference GetVariableAsRef(VariablePath variablePath, Executio if (staticType is null) { var declaredType = var.Attributes.OfType().FirstOrDefault(); - staticType = declaredType != null ? declaredType.TargetType : typeof(LanguagePrimitives.Null); + staticType = declaredType is not null ? declaredType.TargetType : typeof(LanguagePrimitives.Null); } return PSReference.CreateInstance(var, staticType); @@ -257,10 +257,10 @@ private static UsingResult GetUsingValueFromTuple(MutableTuple tuple, string usi { var boundParameters = tuple.GetAutomaticVariable(AutomaticVariable.PSBoundParameters) as PSBoundParametersDictionary; - if (boundParameters != null) + if (boundParameters is not null) { var implicitUsingParameters = boundParameters.ImplicitUsingParameters; - if (implicitUsingParameters != null) + if (implicitUsingParameters is not null) { if (implicitUsingParameters.Contains(usingExpressionKey)) { @@ -285,16 +285,16 @@ private class UsingResult internal static object GetUsingValue(MutableTuple tuple, string usingExpressionKey, int index, ExecutionContext context) { UsingResult result = GetUsingValueFromTuple(tuple, usingExpressionKey, index); - if (result != null) + if (result is not null) { return result.Value; } var scope = context.EngineSessionState.CurrentScope; - while (scope != null) + while (scope is not null) { result = GetUsingValueFromTuple(scope.LocalsTuple, usingExpressionKey, index); - if (result != null) + if (result is not null) { return result.Value; } @@ -302,7 +302,7 @@ internal static object GetUsingValue(MutableTuple tuple, string usingExpressionK foreach (var dottedScope in scope.DottedScopes) { result = GetUsingValueFromTuple(dottedScope, usingExpressionKey, index); - if (result != null) + if (result is not null) { return result.Value; } diff --git a/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs b/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs index 4db40c9de8d..7201efb59fb 100644 --- a/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs +++ b/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs @@ -175,7 +175,7 @@ internal class UsingExpressionAstSearcher : AstSearcher { internal static IEnumerable FindAllUsingExpressionExceptForWorkflow(Ast ast) { - Diagnostics.Assert(ast != null, "caller to verify arguments"); + Diagnostics.Assert(ast is not null, "caller to verify arguments"); var searcher = new UsingExpressionAstSearcher(astParam => astParam is UsingExpressionAst, stopOnFirst: false, searchNestedScriptBlocks: true); ast.InternalVisit(searcher); @@ -239,13 +239,13 @@ internal static PowerShell Convert(ScriptBlockAst body, string errorId; string errorMsg; body.GetSimplePipeline(true, out errorId, out errorMsg); - if (errorId != null) + if (errorId is not null) { throw new ScriptBlockToPowerShellNotSupportedException(errorId, null, errorMsg); } var checker = new ScriptBlockToPowerShellChecker { ScriptBeingConverted = body }; - if (functionParameters != null) + if (functionParameters is not null) { foreach (var parameter in functionParameters) { @@ -286,7 +286,7 @@ internal static PowerShell Convert(ScriptBlockAst body, // If 'functionParameters' is not null, then the ScriptBlockAst is actually the body of a FunctionDefinitionAst, and it doesn't have a ParamBlock. // If 'functionParameters' is null, then the ScriptBlockAst may have parameters defined in its ParamBlock. bool usesCmdletBinding = false; - var parameters = functionParameters != null + var parameters = functionParameters is not null ? Compiler.GetParameterMetaData(functionParameters, true, ref usesCmdletBinding) : ((IParameterMetadataProvider)body).GetParameterMetadata(true, ref usesCmdletBinding); object[] remainingArgs = ScriptBlock.BindArgumentsForScriptblockInvoke( @@ -344,12 +344,12 @@ internal static object[] GetUsingValuesAsArray(ScriptBlock scriptBlock, bool isT /// private static Tuple, object[]> GetUsingValues(Ast body, bool isTrustedInput, ExecutionContext context, Dictionary variables, bool filterNonUsingVariables) { - Diagnostics.Assert(context != null || variables != null, "can't retrieve variables with no context and no variables"); + Diagnostics.Assert(context is not null || variables is not null, "can't retrieve variables with no context and no variables"); var usingAsts = UsingExpressionAstSearcher.FindAllUsingExpressionExceptForWorkflow(body).ToList(); var usingValueArray = new object[usingAsts.Count]; var usingValueMap = new Dictionary(usingAsts.Count); - HashSet usingVarNames = (variables != null && filterNonUsingVariables) ? new HashSet() : null; + HashSet usingVarNames = (variables is not null && filterNonUsingVariables) ? new HashSet() : null; // Used to check if the PSv3/PSv4 way of handling UsingExpression can continue to be used. bool hasUsingExprInDifferentScope = false; @@ -359,7 +359,7 @@ private static Tuple, object[]> GetUsingValues(Ast bo Version oldStrictVersion = null; try { - if (context != null) + if (context is not null) { oldStrictVersion = context.EngineSessionState.CurrentScope.StrictModeVersion; context.EngineSessionState.CurrentScope.StrictModeVersion = PSVersionInfo.PSVersion; @@ -384,7 +384,7 @@ private static Tuple, object[]> GetUsingValues(Ast bo hasUsingExprInDifferentScope = true; } - if (variables != null) + if (variables is not null) { var variableAst = usingAst.SubExpression as VariableExpressionAst; if (variableAst is null) @@ -394,7 +394,7 @@ private static Tuple, object[]> GetUsingValues(Ast bo } string varName = variableAst.VariablePath.UserPath; - if (varName != null && variables.TryGetValue(varName, out value) && usingVarNames != null) + if (varName is not null && variables.TryGetValue(varName, out value) && usingVarNames is not null) { usingVarNames.Add(varName); } @@ -426,13 +426,13 @@ private static Tuple, object[]> GetUsingValues(Ast bo } finally { - if (context != null) + if (context is not null) { context.EngineSessionState.CurrentScope.StrictModeVersion = oldStrictVersion; } } - if (usingVarNames != null) + if (usingVarNames is not null) { string[] keys = variables.Keys.ToArray(); foreach (string key in keys) @@ -474,7 +474,7 @@ private static bool HasUsingExpressionsInDifferentScopes(UsingExpressionAst usin current = current.Parent; var sbAst = current as ScriptBlockAst; - if (sbAst != null) + if (sbAst is not null) { // We find the closest parent ScriptBlockAst of the current UsingExpression, which represents the scope // that the current UsingExpression is in. @@ -497,7 +497,7 @@ private static bool HasUsingExpressionsInDifferentScopes(UsingExpressionAst usin } var funcAst = current as FunctionDefinitionAst; - if (funcAst != null) + if (funcAst is not null) { // The parent chain of the current UsingExpression reaches a FunctionDefinitionAst, then the UsingExpression // must be in 'Parameters' property of this FunctionDefinitionAst. @@ -590,21 +590,21 @@ private void ConvertCommand(CommandAst commandAst, bool isTrustedInput) foreach (var ast in commandAst.CommandElements.Skip(1)) { var exprAst = ast as ExpressionAst; - if (exprAst != null) + if (exprAst is not null) { VariableExpressionAst variableAst = null; var usingExprAst = ast as UsingExpressionAst; - if (usingExprAst != null) + if (usingExprAst is not null) { string usingAstKey = PsUtils.GetUsingExpressionKey(usingExprAst); object usingValue = _usingValueMap[usingAstKey]; variableAst = usingExprAst.SubExpression as VariableExpressionAst; - if (variableAst != null && variableAst.Splatted) + if (variableAst is not null && variableAst.Splatted) { // Support the splatting of a dictionary var parameters = usingValue as System.Collections.IDictionary; - if (parameters != null) + if (parameters is not null) { _powershell.AddParameters(parameters); } @@ -612,7 +612,7 @@ private void ConvertCommand(CommandAst commandAst, bool isTrustedInput) { // Support the splatting of an array var arguments = usingValue as System.Collections.IEnumerable; - if (arguments != null) + if (arguments is not null) { foreach (object argument in arguments) { @@ -635,7 +635,7 @@ private void ConvertCommand(CommandAst commandAst, bool isTrustedInput) } variableAst = ast as VariableExpressionAst; - if (variableAst != null && variableAst.Splatted) + if (variableAst is not null && variableAst.Splatted) { GetSplattedVariable(variableAst); } @@ -643,7 +643,7 @@ private void ConvertCommand(CommandAst commandAst, bool isTrustedInput) { var constantExprAst = ast as ConstantExpressionAst; object argument; - if (constantExprAst != null + if (constantExprAst is not null && (LanguagePrimitives.IsNumeric(LanguagePrimitives.GetTypeCode(constantExprAst.StaticType)) || constantExprAst.StaticType == typeof(System.Numerics.BigInteger))) { @@ -694,7 +694,7 @@ private string GetCommandName(CommandElementAst commandNameAst, bool isTrustedIn { var exprAst = commandNameAst as ExpressionAst; string commandName; - if (exprAst != null) + if (exprAst is not null) { var value = GetExpressionValue(exprAst, isTrustedInput); if (value is null) @@ -774,7 +774,7 @@ private void AddParameter(CommandParameterAst commandParameterAst, bool isTruste { string nameSuffix; object argument; - if (commandParameterAst.Argument != null) + if (commandParameterAst.Argument is not null) { var arg = commandParameterAst.Argument; var errorPos = commandParameterAst.ErrorPosition; diff --git a/src/System.Management.Automation/engine/scriptparameterbinder.cs b/src/System.Management.Automation/engine/scriptparameterbinder.cs index c9944678ad8..ece5dcac4ad 100644 --- a/src/System.Management.Automation/engine/scriptparameterbinder.cs +++ b/src/System.Management.Automation/engine/scriptparameterbinder.cs @@ -40,7 +40,7 @@ internal ScriptParameterBinder( InternalCommand command, SessionStateScope localScope) : base(invocationInfo, context, command) { - Diagnostics.Assert(script != null, "caller to verify script is not null."); + Diagnostics.Assert(script is not null, "caller to verify script is not null."); this.Script = script; this.LocalScope = localScope; @@ -105,12 +105,12 @@ internal override void BindParameter(string name, object value, CompiledCommandP value = null; } - Diagnostics.Assert(name != null, "The caller should verify that name is not null"); + Diagnostics.Assert(name is not null, "The caller should verify that name is not null"); var varPath = new VariablePath(name, VariablePathFlags.Variable); // If the parameter was allocated in the LocalsTuple, we can avoid creating a PSVariable, - if (LocalScope != null + if (LocalScope is not null && varPath.IsAnyLocal() && LocalScope.TrySetLocalParameterValue(varPath.UnqualifiedPath, CopyMutableValues(value))) { @@ -144,7 +144,7 @@ internal object GetDefaultScriptParameterValue(RuntimeDefinedParameter parameter object result = parameter.Value; var compiledDefault = result as Compiler.DefaultValueExpressionWrapper; - if (compiledDefault != null) + if (compiledDefault is not null) { result = compiledDefault.GetValue(Context, Script.SessionStateInternal, implicitUsingParameters); } diff --git a/src/System.Management.Automation/engine/scriptparameterbindercontroller.cs b/src/System.Management.Automation/engine/scriptparameterbindercontroller.cs index b3f0f6757d1..5d7db63c4e5 100644 --- a/src/System.Management.Automation/engine/scriptparameterbindercontroller.cs +++ b/src/System.Management.Automation/engine/scriptparameterbindercontroller.cs @@ -166,7 +166,7 @@ internal override Collection BindParameters(Collection // If the parameter is not in the specified parameter set, // throw a binding exception - if (parameter != null) + if (parameter is not null) { // Now check to make sure it hasn't already been // bound by looking in the boundParameters collection diff --git a/src/System.Management.Automation/engine/serialization.cs b/src/System.Management.Automation/engine/serialization.cs index 6094310cbb7..677ececa403 100644 --- a/src/System.Management.Automation/engine/serialization.cs +++ b/src/System.Management.Automation/engine/serialization.cs @@ -552,7 +552,7 @@ private void Start() // Read version attribute and validate it. string versionAttribute = _reader.GetAttribute(SerializationStrings.VersionAttribute); - if (versionAttribute != null) + if (versionAttribute is not null) { version = versionAttribute; } @@ -649,7 +649,7 @@ internal object Deserialize(out string streamName) /// internal static void AddDeserializationPrefix(ref string type) { - Dbg.Assert(type != null, "caller should validate the parameter"); + Dbg.Assert(type is not null, "caller should validate the parameter"); if (!type.StartsWith(Deserializer.DeserializationTypeNamePrefix, StringComparison.OrdinalIgnoreCase)) { type = type.Insert(0, Deserializer.DeserializationTypeNamePrefix); @@ -696,10 +696,10 @@ internal static bool IsDeserializedInstanceOfType(object o, Type type) } PSObject pso = o as PSObject; - if (pso != null) + if (pso is not null) { IEnumerable typeNames = pso.InternalTypeNames; - if (typeNames != null) + if (typeNames is not null) { foreach (string typeName in typeNames) { @@ -744,7 +744,7 @@ internal static string MaskDeserializationPrefix(string typeName) /// internal static Collection MaskDeserializationPrefix(Collection typeNames) { - Dbg.Assert(typeNames != null, "typeNames cannot be null"); + Dbg.Assert(typeNames is not null, "typeNames cannot be null"); bool atleastOneDeserializedTypeFound = false; @@ -830,8 +830,8 @@ internal class InternalSerializer internal InternalSerializer(XmlWriter writer, SerializationContext context) { - Dbg.Assert(writer != null, "caller should validate the parameter"); - Dbg.Assert(context != null, "caller should validate the parameter"); + Dbg.Assert(writer is not null, "caller should validate the parameter"); + Dbg.Assert(context is not null, "caller should validate the parameter"); _writer = writer; _context = context; @@ -908,7 +908,7 @@ internal static bool IsPrimitiveKnownType(Type input) { // Check if source is of primitive known type TypeSerializationInfo pktInfo = KnownTypes.GetTypeSerializationInfo(input); - return (pktInfo != null); + return (pktInfo is not null); } /// @@ -966,7 +966,7 @@ int depth // Object is not of primitive known type. Check if this has // already been serialized. string refId = _objectRefIdHandler.GetRefId(source); - if (refId != null) + if (refId is not null) { WritePSObjectReference(streamName, property, refId); return; @@ -1036,11 +1036,11 @@ private bool HandlePrimitiveKnownType string property ) { - Dbg.Assert(source != null, "caller should validate the parameter"); + Dbg.Assert(source is not null, "caller should validate the parameter"); // Check if source is of primitive known type TypeSerializationInfo pktInfo = KnownTypes.GetTypeSerializationInfo(source.GetType()); - if (pktInfo != null) + if (pktInfo is not null) { WriteOnePrimitiveKnownType(this, streamName, property, source, pktInfo); return true; @@ -1067,10 +1067,10 @@ private bool HandlePrimitiveKnownTypeByConvertingToPSObject( int depth ) { - Dbg.Assert(source != null, "caller should validate the parameter"); + Dbg.Assert(source is not null, "caller should validate the parameter"); // Check if source is of primitive known type TypeSerializationInfo pktInfo = KnownTypes.GetTypeSerializationInfo(source.GetType()); - if (pktInfo != null) + if (pktInfo is not null) { PSObject pktInfoPSObject = PSObject.AsPSObject(source); return HandlePrimitiveKnownTypePSObject(pktInfoPSObject, streamName, property, depth); @@ -1087,13 +1087,13 @@ int depth /// private bool HandleSecureString(object source, string streamName, string property) { - Dbg.Assert(source != null, "caller should validate the parameter"); + Dbg.Assert(source is not null, "caller should validate the parameter"); SecureString secureString = null; secureString = source as SecureString; PSObject moSource; - if (secureString != null) + if (secureString is not null) { moSource = PSObject.AsPSObject(secureString); } @@ -1102,11 +1102,11 @@ private bool HandleSecureString(object source, string streamName, string propert moSource = source as PSObject; } - if (moSource != null && !moSource.ImmediateBaseObjectIsEmpty) + if (moSource is not null && !moSource.ImmediateBaseObjectIsEmpty) { // check if source is of type secure string secureString = moSource.ImmediateBaseObject as SecureString; - if (secureString != null) + if (secureString is not null) { // the principle used in serialization is that serialization // never throws, and if something can't be serialized nothing @@ -1114,7 +1114,7 @@ private bool HandleSecureString(object source, string streamName, string propert // However, in the case for non-Windows where secure string encryption // is not yet supported, a PSCryptoException will be thrown. string encryptedString; - if (_context.cryptoHelper != null) + if (_context.cryptoHelper is not null) { encryptedString = _context.cryptoHelper.EncryptSecureString(secureString); } @@ -1123,7 +1123,7 @@ private bool HandleSecureString(object source, string streamName, string propert encryptedString = Microsoft.PowerShell.SecureStringHelper.Protect(secureString); } - if (property != null) + if (property is not null) { WriteStartElement(SerializationStrings.SecureStringTag); WriteNameAttribute(property); @@ -1133,7 +1133,7 @@ private bool HandleSecureString(object source, string streamName, string propert WriteStartElement(SerializationStrings.SecureStringTag); } - if (streamName != null) + if (streamName is not null) { WriteAttribute(SerializationStrings.StreamNameAttribute, streamName); } @@ -1170,16 +1170,16 @@ private bool HandlePrimitiveKnownTypePSObject int depth ) { - Dbg.Assert(source != null, "caller should validate the parameter"); + Dbg.Assert(source is not null, "caller should validate the parameter"); bool sourceHandled = false; PSObject moSource = source as PSObject; - if (moSource != null && !moSource.ImmediateBaseObjectIsEmpty) + if (moSource is not null && !moSource.ImmediateBaseObjectIsEmpty) { // Check if baseObject is primitive known type object baseObject = moSource.ImmediateBaseObject; TypeSerializationInfo pktInfo = KnownTypes.GetTypeSerializationInfo(baseObject.GetType()); - if (pktInfo != null) + if (pktInfo is not null) { WritePrimitiveTypePSObject(moSource, baseObject, pktInfo, streamName, property, depth); sourceHandled = true; @@ -1197,7 +1197,7 @@ private bool HandleKnownContainerTypes int depth ) { - Dbg.Assert(source != null, "caller should validate the parameter"); + Dbg.Assert(source is not null, "caller should validate the parameter"); ContainerType ct = ContainerType.None; PSObject mshSource = source as PSObject; @@ -1205,13 +1205,13 @@ int depth IDictionary dictionary = null; // If passed in object is PSObject with no baseobject, return false. - if (mshSource != null && mshSource.ImmediateBaseObjectIsEmpty) + if (mshSource is not null && mshSource.ImmediateBaseObjectIsEmpty) { return false; } // Check if source (or baseobject in mshSource) is known container type - SerializationUtilities.GetKnownContainerTypeInfo(mshSource != null ? mshSource.ImmediateBaseObject : source, out ct, + SerializationUtilities.GetKnownContainerTypeInfo(mshSource is not null ? mshSource.ImmediateBaseObject : source, out ct, out dictionary, out enumerable); if (ct == ContainerType.None) @@ -1254,7 +1254,7 @@ int depth // So on roundtrip it will show up as List. // We serialize properties of enumerable and on deserialization mark the object as Deserialized. // So if object is marked deserialized, we should write properties. - if (ct == ContainerType.Enumerable || (mshSource != null && mshSource.IsDeserialized)) + if (ct == ContainerType.Enumerable || (mshSource is not null && mshSource.IsDeserialized)) { PSObject sourceAsPSObject = PSObject.AsPSObject(source); PSMemberInfoInternalCollection specificPropertiesToSerialize = SerializationUtilities.GetSpecificPropertiesToSerialize(sourceAsPSObject, AllPropertiesCollection, _typeTable); @@ -1262,7 +1262,7 @@ int depth SerializeExtendedProperties(sourceAsPSObject, depth, specificPropertiesToSerialize); } // always serialize instance properties if there are any - else if (mshSource != null) + else if (mshSource is not null) { SerializeInstanceProperties(mshSource, depth); } @@ -1288,12 +1288,12 @@ string refId Dbg.Assert(!string.IsNullOrEmpty(refId), "caller should validate the parameter"); WriteStartElement(SerializationStrings.ReferenceTag); - if (streamName != null) + if (streamName is not null) { WriteAttribute(SerializationStrings.StreamNameAttribute, streamName); } - if (property != null) + if (property is not null) { WriteNameAttribute(property); } @@ -1352,12 +1352,12 @@ private void WritePrimitiveTypePSObject int depth ) { - Dbg.Assert(source != null, "Caller should validate source != null"); + Dbg.Assert(source is not null, "Caller should validate source is not null"); string toStringValue = SerializationUtilities.GetToStringForPrimitiveObject(source); bool hasModifiedTypesCollection = PSObjectHasModifiedTypesCollection(source); bool hasNotes = PSObjectHasNotes(source); - bool hasModifiedToString = (toStringValue != null); + bool hasModifiedToString = (toStringValue is not null); if (hasNotes || hasModifiedTypesCollection || hasModifiedToString) { @@ -1374,7 +1374,7 @@ int depth } else { - if (primitive != null) + if (primitive is not null) { WriteOnePrimitiveKnownType(this, streamName, property, primitive, pktInfo); return; @@ -1419,8 +1419,8 @@ private void WritePrimitiveTypePSObjectWithNotes int depth ) { - Dbg.Assert(source != null, "caller should validate the parameter"); - Dbg.Assert(pktInfo != null, "Caller should validate pktInfo != null"); + Dbg.Assert(source is not null, "caller should validate the parameter"); + Dbg.Assert(pktInfo is not null, "Caller should validate pktInfo is not null"); string refId = _objectRefIdHandler.SetRefId(source); WriteStartOfPSObject( @@ -1432,7 +1432,7 @@ int depth toStringValue); // preserve ToString information only if got it from deserialization or overridden by PSObject // (example where preservation of TypeNames and ToString is needed: enums serialized as ints, help string with custom type names (HelpInfoShort)) - if (pktInfo != null) + if (pktInfo is not null) { WriteOnePrimitiveKnownType(this, streamName, null, primitive, pktInfo); } @@ -1452,7 +1452,7 @@ private void HandleComplexTypePSObject int depth ) { - Dbg.Assert(source != null, "caller should validate the parameter"); + Dbg.Assert(source is not null, "caller should validate the parameter"); PSObject mshSource = PSObject.AsPSObject(source); // Figure out what kind of object we are dealing with @@ -1467,14 +1467,14 @@ int depth do // false loop { CimInstance cimInstance = mshSource.ImmediateBaseObject as CimInstance; - if (cimInstance != null) + if (cimInstance is not null) { isCimInstance = true; break; } ErrorRecord errorRecord = mshSource.ImmediateBaseObject as ErrorRecord; - if (errorRecord != null) + if (errorRecord is not null) { errorRecord.ToPSObjectForRemoting(mshSource); isErrorRecord = true; @@ -1482,7 +1482,7 @@ int depth } InformationalRecord informationalRecord = mshSource.ImmediateBaseObject as InformationalRecord; - if (informationalRecord != null) + if (informationalRecord is not null) { informationalRecord.ToPSObjectForRemoting(mshSource); isInformationalRecord = true; @@ -1553,7 +1553,7 @@ private void PrepareCimInstanceForSerialization(PSObject psObject, CimInstance c // CREATE SERIALIZED FORM OF THE CLASS METADATA // ArrayList psoClasses = new ArrayList(); - for (CimClass cimClass = cimInstance.CimClass; cimClass != null; cimClass = cimClass.CimSuperClass) + for (CimClass cimClass = cimInstance.CimClass; cimClass is not null; cimClass = cimClass.CimSuperClass) { PSObject psoClass = new PSObject(); psoClass.TypeNames.Clear(); @@ -1594,7 +1594,7 @@ private void PrepareCimInstanceForSerialization(PSObject psObject, CimInstance c // ATTACH CLASS METADATA TO THE OBJECT BEING SERIALIZED // PSPropertyInfo classMetadataProperty = psObject.Properties[InternalDeserializer.CimClassMetadataProperty]; - if (classMetadataProperty != null) + if (classMetadataProperty is not null) { classMetadataProperty.Value = psoClasses; } @@ -1617,7 +1617,7 @@ private void PrepareCimInstanceForSerialization(PSObject psObject, CimInstance c { PSObject instanceMetadata = new PSObject(); PSPropertyInfo instanceMetadataProperty = psObject.Properties[InternalDeserializer.CimInstanceMetadataProperty]; - if (instanceMetadataProperty != null) + if (instanceMetadataProperty is not null) { instanceMetadataProperty.Value = instanceMetadata; } @@ -1656,22 +1656,22 @@ private void WriteStartOfPSObject string toStringValue ) { - Dbg.Assert(mshObject != null, "caller should validate the parameter"); + Dbg.Assert(mshObject is not null, "caller should validate the parameter"); // Write PSObject start element. WriteStartElement(SerializationStrings.PSObjectTag); - if (streamName != null) + if (streamName is not null) { WriteAttribute(SerializationStrings.StreamNameAttribute, streamName); } - if (property != null) + if (property is not null) { WriteNameAttribute(property); } - if (refId != null) + if (refId is not null) { WriteAttribute(SerializationStrings.ReferenceIdAttribute, refId); } @@ -1689,7 +1689,7 @@ string toStringValue // Create a new refId and write it as attribute string tnRefId = _typeRefIdHandler.SetRefId(typeNames); - Dbg.Assert(tnRefId != null, "SetRefId should always succeed for strings"); + Dbg.Assert(tnRefId is not null, "SetRefId should always succeed for strings"); WriteAttribute(SerializationStrings.ReferenceIdAttribute, tnRefId); foreach (string type in typeNames) @@ -1708,7 +1708,7 @@ string toStringValue } } - if (toStringValue != null) + if (toStringValue is not null) { WriteEncodedElementString(SerializationStrings.ToStringElementTag, toStringValue); } @@ -1724,8 +1724,8 @@ string toStringValue /// private static bool PSObjectHasNotes(PSObject source) { - Dbg.Assert(source != null, "Caller should validate the parameter"); - if (source.InstanceMembers != null && source.InstanceMembers.Count > 0) + Dbg.Assert(source is not null, "Caller should validate the parameter"); + if (source.InstanceMembers is not null && source.InstanceMembers.Count > 0) { return true; } @@ -1767,7 +1767,7 @@ private void WriteMemberInfoCollection bool writeEnclosingMemberSetElementTag ) { - Dbg.Assert(me != null, "caller should validate the parameter"); + Dbg.Assert(me is not null, "caller should validate the parameter"); bool enclosingTagWritten = false; foreach (PSMemberInfo info in me) @@ -1821,7 +1821,7 @@ private void WriteMemberSet int depth ) { - Dbg.Assert(set != null, "Caller should validate the parameter"); + Dbg.Assert(set is not null, "Caller should validate the parameter"); if (!set.ShouldSerialize) { @@ -1848,13 +1848,13 @@ private void WritePSObjectProperties IEnumerable specificPropertiesToSerialize ) { - Dbg.Assert(source != null, "caller should validate the information"); + Dbg.Assert(source is not null, "caller should validate the information"); // Depth available for each property is one less --depth; Dbg.Assert(depth >= 0, "depth should be greater or equal to zero"); - if (specificPropertiesToSerialize != null) + if (specificPropertiesToSerialize is not null) { SerializeProperties(specificPropertiesToSerialize, SerializationStrings.AdapterProperties, depth); } @@ -1864,7 +1864,7 @@ IEnumerable specificPropertiesToSerialize { IEnumerable adapterCollection = null; adapterCollection = source.GetAdaptedProperties(); - if (adapterCollection != null) + if (adapterCollection is not null) { SerializeProperties(adapterCollection, SerializationStrings.AdapterProperties, depth); } @@ -1879,9 +1879,9 @@ int depth ) { // Serialize instanceMembers - Dbg.Assert(source != null, "caller should validate the information"); + Dbg.Assert(source is not null, "caller should validate the information"); PSMemberInfoCollection instanceMembers = source.InstanceMembers; - if (instanceMembers != null) + if (instanceMembers is not null) { WriteMemberInfoCollection(instanceMembers, depth, true); } @@ -1917,7 +1917,7 @@ private void SerializeExtendedProperties IEnumerable specificPropertiesToSerialize ) { - Dbg.Assert(source != null, "caller should validate the information"); + Dbg.Assert(source is not null, "caller should validate the information"); IEnumerable extendedMembersEnumerable = null; if (specificPropertiesToSerialize is null) @@ -1951,7 +1951,7 @@ IEnumerable specificPropertiesToSerialize } } - if (extendedMembersEnumerable != null) + if (extendedMembersEnumerable is not null) { WriteMemberInfoCollection(extendedMembersEnumerable, depth, true); } @@ -1977,7 +1977,7 @@ private void SerializeProperties int depth ) { - Dbg.Assert(propertyCollection != null, "caller should validate the parameter"); + Dbg.Assert(propertyCollection is not null, "caller should validate the parameter"); bool startElementWritten = false; foreach (PSMemberInfo info in propertyCollection) @@ -2030,7 +2030,7 @@ private void WriteEnumerable int depth ) { - Dbg.Assert(enumerable != null, "caller should validate the parameter"); + Dbg.Assert(enumerable is not null, "caller should validate the parameter"); Dbg.Assert(!string.IsNullOrEmpty(tag), "caller should validate the parameter"); // Start element @@ -2063,7 +2063,7 @@ int depth // AD has incorrect implementation of IEnumerable where they returned null // for GetEnumerator instead of empty enumerator - if (enumerator != null) + if (enumerator is not null) { while (true) { @@ -2111,7 +2111,7 @@ private void WriteDictionary int depth ) { - Dbg.Assert(dictionary != null, "caller should validate the parameter"); + Dbg.Assert(dictionary is not null, "caller should validate the parameter"); Dbg.Assert(!string.IsNullOrEmpty(tag), "caller should validate the parameter"); // Start element @@ -2132,7 +2132,7 @@ int depth exception.ToString()); } - if (dictionaryEnum != null) + if (dictionaryEnum is not null) { while (true) { @@ -2162,7 +2162,7 @@ int depth break; } - Dbg.Assert(key != null, "Dictionary keys should never be null"); + Dbg.Assert(key is not null, "Dictionary keys should never be null"); if (key is null) break; WriteStartElement(SerializationStrings.DictionaryEntryTag); @@ -2186,12 +2186,12 @@ private void HandlePSObjectAsString( string property, int depth) { - Dbg.Assert(source != null, "caller should validate the information"); + Dbg.Assert(source is not null, "caller should validate the information"); string value = GetSerializationString(source); TypeSerializationInfo pktInfo = null; - if (value != null) + if (value is not null) { pktInfo = KnownTypes.GetTypeSerializationInfo(value.GetType()); } @@ -2213,7 +2213,7 @@ private void HandlePSObjectAsString( /// private string GetSerializationString(PSObject source) { - Dbg.Assert(source != null, "caller should have validated the information"); + Dbg.Assert(source is not null, "caller should have validated the information"); PSPropertyInfo serializationProperty = null; try @@ -2226,15 +2226,15 @@ private string GetSerializationString(PSObject source) PSEventId.Serializer_ToStringFailed, PSOpcode.Exception, PSTask.Serialization, PSKeyword.Serializer | PSKeyword.UseAlwaysAnalytic, source.GetType().AssemblyQualifiedName, - e.InnerException != null ? e.InnerException.ToString() : e.ToString()); + e.InnerException is not null ? e.InnerException.ToString() : e.ToString()); } string result = null; - if (serializationProperty != null) + if (serializationProperty is not null) { bool success; object val = SerializationUtilities.GetPropertyValueInThreadSafeManner(serializationProperty, this.CanUseDefaultRunspaceInThreadSafeManner, out success); - if (success && (val != null)) + if (success && (val is not null)) { result = SerializationUtilities.GetToString(val); } @@ -2283,7 +2283,7 @@ private bool SerializeAsString(PSObject source) /// private int GetDepthOfSerialization(object source, int depth) { - Dbg.Assert(source != null, "Caller should verify source != null"); + Dbg.Assert(source is not null, "Caller should verify source is not null"); PSObject pso = PSObject.AsPSObject(source); if (pso is null) @@ -2351,12 +2351,12 @@ private void WriteNull(string streamName, string property) { WriteStartElement(SerializationStrings.NilTag); - if (streamName != null) + if (streamName is not null) { WriteAttribute(SerializationStrings.StreamNameAttribute, streamName); } - if (property != null) + if (property is not null) { WriteNameAttribute(property); } @@ -2383,11 +2383,11 @@ private static void WriteRawString TypeSerializationInfo entry ) { - Dbg.Assert(serializer != null, "caller should have validated the information"); - Dbg.Assert(raw != null, "caller should have validated the information"); - Dbg.Assert(entry != null, "caller should have validated the information"); + Dbg.Assert(serializer is not null, "caller should have validated the information"); + Dbg.Assert(raw is not null, "caller should have validated the information"); + Dbg.Assert(entry is not null, "caller should have validated the information"); - if (property != null) + if (property is not null) { serializer.WriteStartElement(entry.PropertyTag); serializer.WriteNameAttribute(property); @@ -2397,7 +2397,7 @@ TypeSerializationInfo entry serializer.WriteStartElement(entry.ItemTag); } - if (streamName != null) + if (streamName is not null) { serializer.WriteAttribute(SerializationStrings.StreamNameAttribute, streamName); } @@ -2423,16 +2423,16 @@ private static void WriteOnePrimitiveKnownType TypeSerializationInfo entry ) { - Dbg.Assert(serializer != null, "caller should have validated the information"); - Dbg.Assert(source != null, "caller should have validated the information"); - Dbg.Assert(entry != null, "caller should have validated the information"); + Dbg.Assert(serializer is not null, "caller should have validated the information"); + Dbg.Assert(source is not null, "caller should have validated the information"); + Dbg.Assert(entry is not null, "caller should have validated the information"); if (entry.Serializer is null) { // we are not using GetToString, because we assume that // ToString() for primitive types never throws string value = Convert.ToString(source, CultureInfo.InvariantCulture); - Dbg.Assert(value != null, "ToString shouldn't return null for primitive types"); + Dbg.Assert(value is not null, "ToString shouldn't return null for primitive types"); WriteRawString(serializer, streamName, property, value, entry); } else @@ -2451,9 +2451,9 @@ TypeSerializationInfo entry /// Serialization information about source. internal static void WriteDateTime(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) { - Dbg.Assert(serializer != null, "caller should have validated the information"); - Dbg.Assert(source != null, "caller should have validated the information"); - Dbg.Assert(entry != null, "caller should have validated the information"); + Dbg.Assert(serializer is not null, "caller should have validated the information"); + Dbg.Assert(source is not null, "caller should have validated the information"); + Dbg.Assert(entry is not null, "caller should have validated the information"); WriteRawString(serializer, streamName, property, XmlConvert.ToString((DateTime)source, XmlDateTimeSerializationMode.RoundtripKind), entry); } @@ -2468,10 +2468,10 @@ internal static void WriteDateTime(InternalSerializer serializer, string streamN /// Serialization information about source. internal static void WriteVersion(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) { - Dbg.Assert(serializer != null, "caller should have validated the information"); - Dbg.Assert(source != null, "caller should have validated the information"); + Dbg.Assert(serializer is not null, "caller should have validated the information"); + Dbg.Assert(source is not null, "caller should have validated the information"); Dbg.Assert(source is Version, "Caller should verify that typeof(source) is Version"); - Dbg.Assert(entry != null, "caller should have validated the information"); + Dbg.Assert(entry is not null, "caller should have validated the information"); WriteRawString(serializer, streamName, property, Convert.ToString(source, CultureInfo.InvariantCulture), entry); } @@ -2486,10 +2486,10 @@ internal static void WriteVersion(InternalSerializer serializer, string streamNa /// Serialization information about source. internal static void WriteSemanticVersion(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) { - Dbg.Assert(serializer != null, "caller should have validated the information"); - Dbg.Assert(source != null, "caller should have validated the information"); + Dbg.Assert(serializer is not null, "caller should have validated the information"); + Dbg.Assert(source is not null, "caller should have validated the information"); Dbg.Assert(source is SemanticVersion, "Caller should verify that typeof(source) is Version"); - Dbg.Assert(entry != null, "caller should have validated the information"); + Dbg.Assert(entry is not null, "caller should have validated the information"); WriteRawString(serializer, streamName, property, Convert.ToString(source, CultureInfo.InvariantCulture), entry); } @@ -2504,10 +2504,10 @@ internal static void WriteSemanticVersion(InternalSerializer serializer, string /// Serialization information about source. internal static void WriteScriptBlock(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) { - Dbg.Assert(serializer != null, "caller should have validated the information"); - Dbg.Assert(source != null, "caller should have validated the information"); + Dbg.Assert(serializer is not null, "caller should have validated the information"); + Dbg.Assert(source is not null, "caller should have validated the information"); Dbg.Assert(source is ScriptBlock, "Caller should verify that typeof(source) is ScriptBlock"); - Dbg.Assert(entry != null, "caller should have validated the information"); + Dbg.Assert(entry is not null, "caller should have validated the information"); WriteEncodedString(serializer, streamName, property, Convert.ToString(source, CultureInfo.InvariantCulture), entry); } @@ -2522,10 +2522,10 @@ internal static void WriteScriptBlock(InternalSerializer serializer, string stre /// Serialization information about source. internal static void WriteUri(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) { - Dbg.Assert(serializer != null, "caller should have validated the information"); - Dbg.Assert(source != null, "caller should have validated the information"); + Dbg.Assert(serializer is not null, "caller should have validated the information"); + Dbg.Assert(source is not null, "caller should have validated the information"); Dbg.Assert(source is Uri, "Caller should verify that typeof(source) is Uri"); - Dbg.Assert(entry != null, "caller should have validated the information"); + Dbg.Assert(entry is not null, "caller should have validated the information"); WriteEncodedString(serializer, streamName, property, Convert.ToString(source, CultureInfo.InvariantCulture), entry); } @@ -2540,12 +2540,12 @@ internal static void WriteUri(InternalSerializer serializer, string streamName, /// Serialization information about source. internal static void WriteEncodedString(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) { - Dbg.Assert(serializer != null, "caller should have validated the information"); - Dbg.Assert(source != null, "caller should have validated the information"); + Dbg.Assert(serializer is not null, "caller should have validated the information"); + Dbg.Assert(source is not null, "caller should have validated the information"); Dbg.Assert(source is string, "caller should have validated the information"); - Dbg.Assert(entry != null, "caller should have validated the information"); + Dbg.Assert(entry is not null, "caller should have validated the information"); - if (property != null) + if (property is not null) { serializer.WriteStartElement(entry.PropertyTag); serializer.WriteNameAttribute(property); @@ -2555,7 +2555,7 @@ internal static void WriteEncodedString(InternalSerializer serializer, string st serializer.WriteStartElement(entry.ItemTag); } - if (streamName != null) + if (streamName is not null) { serializer.WriteAttribute(SerializationStrings.StreamNameAttribute, streamName); } @@ -2581,9 +2581,9 @@ internal static void WriteEncodedString(InternalSerializer serializer, string st /// Serialization information about source. internal static void WriteDouble(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) { - Dbg.Assert(serializer != null, "caller should have validated the information"); - Dbg.Assert(source != null, "caller should have validated the information"); - Dbg.Assert(entry != null, "caller should have validated the information"); + Dbg.Assert(serializer is not null, "caller should have validated the information"); + Dbg.Assert(source is not null, "caller should have validated the information"); + Dbg.Assert(entry is not null, "caller should have validated the information"); WriteRawString(serializer, streamName, property, XmlConvert.ToString((double)source), entry); } @@ -2598,9 +2598,9 @@ internal static void WriteDouble(InternalSerializer serializer, string streamNam /// Serialization information about source. internal static void WriteChar(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) { - Dbg.Assert(serializer != null, "caller should have validated the information"); - Dbg.Assert(source != null, "caller should have validated the information"); - Dbg.Assert(entry != null, "caller should have validated the information"); + Dbg.Assert(serializer is not null, "caller should have validated the information"); + Dbg.Assert(source is not null, "caller should have validated the information"); + Dbg.Assert(entry is not null, "caller should have validated the information"); // Char is defined as unsigned short in schema WriteRawString(serializer, streamName, property, XmlConvert.ToString((UInt16)(char)source), entry); @@ -2616,9 +2616,9 @@ internal static void WriteChar(InternalSerializer serializer, string streamName, /// Serialization information about source. internal static void WriteBoolean(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) { - Dbg.Assert(serializer != null, "caller should have validated the information"); - Dbg.Assert(source != null, "caller should have validated the information"); - Dbg.Assert(entry != null, "caller should have validated the information"); + Dbg.Assert(serializer is not null, "caller should have validated the information"); + Dbg.Assert(source is not null, "caller should have validated the information"); + Dbg.Assert(entry is not null, "caller should have validated the information"); WriteRawString(serializer, streamName, property, XmlConvert.ToString((bool)source), entry); } @@ -2633,9 +2633,9 @@ internal static void WriteBoolean(InternalSerializer serializer, string streamNa /// Serialization information about source. internal static void WriteSingle(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) { - Dbg.Assert(serializer != null, "caller should have validated the information"); - Dbg.Assert(source != null, "caller should have validated the information"); - Dbg.Assert(entry != null, "caller should have validated the information"); + Dbg.Assert(serializer is not null, "caller should have validated the information"); + Dbg.Assert(source is not null, "caller should have validated the information"); + Dbg.Assert(entry is not null, "caller should have validated the information"); WriteRawString(serializer, streamName, property, XmlConvert.ToString((Single)source), entry); } @@ -2650,9 +2650,9 @@ internal static void WriteSingle(InternalSerializer serializer, string streamNam /// Serialization information about source. internal static void WriteTimeSpan(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) { - Dbg.Assert(serializer != null, "caller should have validated the information"); - Dbg.Assert(source != null, "caller should have validated the information"); - Dbg.Assert(entry != null, "caller should have validated the information"); + Dbg.Assert(serializer is not null, "caller should have validated the information"); + Dbg.Assert(source is not null, "caller should have validated the information"); + Dbg.Assert(entry is not null, "caller should have validated the information"); WriteRawString(serializer, streamName, property, XmlConvert.ToString((TimeSpan)source), entry); } @@ -2667,12 +2667,12 @@ internal static void WriteTimeSpan(InternalSerializer serializer, string streamN /// Serialization information about source. internal static void WriteByteArray(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) { - Dbg.Assert(serializer != null, "caller should have validated the information"); - Dbg.Assert(source != null, "caller should have validated the information"); - Dbg.Assert(entry != null, "caller should have validated the information"); + Dbg.Assert(serializer is not null, "caller should have validated the information"); + Dbg.Assert(source is not null, "caller should have validated the information"); + Dbg.Assert(entry is not null, "caller should have validated the information"); byte[] bytes = (byte[])source; - if (property != null) + if (property is not null) { serializer.WriteStartElement(entry.PropertyTag); serializer.WriteNameAttribute(property); @@ -2682,7 +2682,7 @@ internal static void WriteByteArray(InternalSerializer serializer, string stream serializer.WriteStartElement(entry.ItemTag); } - if (streamName != null) + if (streamName is not null) { serializer.WriteAttribute(SerializationStrings.StreamNameAttribute, streamName); } @@ -2693,9 +2693,9 @@ internal static void WriteByteArray(InternalSerializer serializer, string stream internal static void WriteXmlDocument(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) { - Dbg.Assert(serializer != null, "caller should have validated the information"); - Dbg.Assert(source != null, "caller should have validated the information"); - Dbg.Assert(entry != null, "caller should have validated the information"); + Dbg.Assert(serializer is not null, "caller should have validated the information"); + Dbg.Assert(source is not null, "caller should have validated the information"); + Dbg.Assert(entry is not null, "caller should have validated the information"); string xml = ((XmlDocument)source).OuterXml; WriteEncodedString(serializer, streamName, property, xml, entry); @@ -2703,18 +2703,18 @@ internal static void WriteXmlDocument(InternalSerializer serializer, string stre internal static void WriteProgressRecord(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) { - Dbg.Assert(serializer != null, "caller should have validated the information"); - Dbg.Assert(source != null, "caller should have validated the information"); - Dbg.Assert(entry != null, "caller should have validated the information"); + Dbg.Assert(serializer is not null, "caller should have validated the information"); + Dbg.Assert(source is not null, "caller should have validated the information"); + Dbg.Assert(entry is not null, "caller should have validated the information"); ProgressRecord rec = (ProgressRecord)source; serializer.WriteStartElement(entry.PropertyTag); - if (property != null) + if (property is not null) { serializer.WriteNameAttribute(property); } - if (streamName != null) + if (streamName is not null) { serializer.WriteAttribute(SerializationStrings.StreamNameAttribute, streamName); } @@ -2733,9 +2733,9 @@ internal static void WriteProgressRecord(InternalSerializer serializer, string s internal static void WriteSecureString(InternalSerializer serializer, string streamName, string property, object source, TypeSerializationInfo entry) { - Dbg.Assert(serializer != null, "caller should have validated the information"); - Dbg.Assert(source != null, "caller should have validated the information"); - Dbg.Assert(entry != null, "caller should have validated the information"); + Dbg.Assert(serializer is not null, "caller should have validated the information"); + Dbg.Assert(source is not null, "caller should have validated the information"); + Dbg.Assert(entry is not null, "caller should have validated the information"); serializer.HandleSecureString(source, streamName, property); } @@ -2769,7 +2769,7 @@ private void WriteStartElement(string elementTag) private void WriteAttribute(string name, string value) { Dbg.Assert(!string.IsNullOrEmpty(name), "Caller should validate the parameter"); - Dbg.Assert(value != null, "Caller should validate the parameter"); + Dbg.Assert(value is not null, "Caller should validate the parameter"); _writer.WriteAttributeString(name, value); } @@ -2802,7 +2802,7 @@ private void WriteNameAttribute(string value) /// internal static string EncodeString(string s) { - Dbg.Assert(s != null, "Caller should validate the parameter"); + Dbg.Assert(s is not null, "Caller should validate the parameter"); int slen = s.Length; for (int i = 0; i < slen; ++i) @@ -2836,7 +2836,7 @@ internal static string EncodeString(string s) /// Encoded string. private static string EncodeString(string s, int indexOfFirstEncodableCharacter) { - Dbg.Assert(s != null, "Caller should validate the 's' parameter"); + Dbg.Assert(s is not null, "Caller should validate the 's' parameter"); Dbg.Assert(indexOfFirstEncodableCharacter >= 0, "Caller should verify validity of indexOfFirstEncodableCharacter"); Dbg.Assert(indexOfFirstEncodableCharacter < s.Length, "Caller should verify validity of indexOfFirstEncodableCharacter"); @@ -2904,7 +2904,7 @@ private static string EncodeString(string s, int indexOfFirstEncodableCharacter) private void WriteEncodedElementString(string name, string value) { Dbg.Assert(!string.IsNullOrEmpty(name), "Caller should validate the parameter"); - Dbg.Assert(value != null, "Caller should validate the parameter"); + Dbg.Assert(value is not null, "Caller should validate the parameter"); this.CheckIfStopping(); value = EncodeString(value); @@ -2993,7 +2993,7 @@ private bool DuplicateRefIdsAllowed /// internal InternalDeserializer(XmlReader reader, DeserializationContext context) { - Dbg.Assert(reader != null, "caller should validate the parameter"); + Dbg.Assert(reader is not null, "caller should validate the parameter"); _reader = reader; _context = context; @@ -3055,7 +3055,7 @@ internal TypeTable TypeTable /// internal void ValidateVersion(string version) { - Dbg.Assert(version != null, "Caller should validate the parameter"); + Dbg.Assert(version is not null, "Caller should validate the parameter"); _version = null; Exception exceptionToRethrow = null; @@ -3072,7 +3072,7 @@ internal void ValidateVersion(string version) exceptionToRethrow = e; } - if (exceptionToRethrow != null) + if (exceptionToRethrow is not null) { throw NewXmlException(Serialization.InvalidVersion, exceptionToRethrow); } @@ -3149,7 +3149,7 @@ private object ReadOneDeserializedObject(out string streamName, out bool isKnown // Handle primitive known types TypeSerializationInfo pktInfo = KnownTypes.GetTypeSerializationInfoFromItemTag(_reader.LocalName); - if (pktInfo != null) + if (pktInfo is not null) { s_trace.WriteLine("Primitive Knowntype Element {0}", pktInfo.ItemTag); isKnownPrimitiveType = true; @@ -3202,13 +3202,13 @@ private bool RehydrateCimInstanceProperty( PSPropertyInfo deserializedProperty, HashSet namesOfModifiedProperties) { - Dbg.Assert(cimInstance != null, "Caller should make sure cimInstance != null"); - Dbg.Assert(deserializedProperty != null, "Caller should make sure deserializedProperty != null"); + Dbg.Assert(cimInstance is not null, "Caller should make sure cimInstance is not null"); + Dbg.Assert(deserializedProperty is not null, "Caller should make sure deserializedProperty is not null"); if (deserializedProperty.Name.Equals(RemotingConstants.ComputerNameNoteProperty, StringComparison.OrdinalIgnoreCase)) { string psComputerNameValue = deserializedProperty.Value as string; - if (psComputerNameValue != null) + if (psComputerNameValue is not null) { cimInstance.SetCimSessionComputerName(psComputerNameValue); } @@ -3224,7 +3224,7 @@ private bool RehydrateCimInstanceProperty( // TODO/FIXME - think if it is possible to do the array handling in a more efficient way object propertyValue = deserializedProperty.Value; - if (propertyValue != null) + if (propertyValue is not null) { PSObject psoPropertyValue = PSObject.AsPSObject(propertyValue); if (psoPropertyValue.BaseObject is ArrayList) @@ -3381,7 +3381,7 @@ private CimClass RehydrateCimClass(PSPropertyInfo classMetadataProperty) CimClassSerializationId cimClassSerializationId = new CimClassSerializationId(cimClassName, cimNamespace, computerName, hashCode); currentClass = _context.cimClassSerializationIdCache.GetCimClassFromCache(cimClassSerializationId); - if (currentClass != null) + if (currentClass is not null) { continue; } @@ -3453,12 +3453,12 @@ private PSObject RehydrateCimInstance(PSObject deserializedObject) // process __InstanceMetadata HashSet namesOfModifiedProperties = new HashSet(StringComparer.OrdinalIgnoreCase); PSPropertyInfo instanceMetadataProperty = deserializedObject.InstanceMembers[CimInstanceMetadataProperty] as PSPropertyInfo; - if ((instanceMetadataProperty != null) && (instanceMetadataProperty.Value != null)) + if ((instanceMetadataProperty is not null) && (instanceMetadataProperty.Value is not null)) { PSObject instanceMetadata = PSObject.AsPSObject(instanceMetadataProperty.Value); PSPropertyInfo modifiedPropertiesProperty = instanceMetadata.InstanceMembers[CimModifiedProperties] as PSPropertyInfo; - if ((modifiedPropertiesProperty != null) && (modifiedPropertiesProperty.Value != null)) + if ((modifiedPropertiesProperty is not null) && (modifiedPropertiesProperty.Value is not null)) { string modifiedPropertiesString = modifiedPropertiesProperty.Value.ToString(); foreach (string nameOfModifiedProperty in modifiedPropertiesString.Split(Utils.Separators.Space)) @@ -3469,7 +3469,7 @@ private PSObject RehydrateCimInstance(PSObject deserializedObject) } // process properties that were originally "adapted" properties - if (deserializedObject.AdaptedMembers != null) + if (deserializedObject.AdaptedMembers is not null) { foreach (PSMemberInfo deserializedMemberInfo in deserializedObject.AdaptedMembers) { @@ -3501,7 +3501,7 @@ private PSObject RehydrateCimInstance(PSObject deserializedObject) } // skip adapted properties - if ((deserializedObject.AdaptedMembers != null) && (deserializedObject.AdaptedMembers[deserializedProperty.Name] != null)) + if ((deserializedObject.AdaptedMembers is not null) && (deserializedObject.AdaptedMembers[deserializedProperty.Name] is not null)) { continue; } @@ -3513,7 +3513,7 @@ private PSObject RehydrateCimInstance(PSObject deserializedObject) } // skip properties re-added by the client (i.e. through types.ps1xml) - if (psoCimInstance.Properties[deserializedProperty.Name] != null) + if (psoCimInstance.Properties[deserializedProperty.Name] is not null) { continue; } @@ -3563,7 +3563,7 @@ internal object ReadOneObject(out string streamName) // Convert deserialized object to a user-defined type (specified in a types.ps1xml file) Type targetType = mshSource.GetTargetTypeForDeserialization(_typeTable); - if (targetType != null) + if (targetType is not null) { Exception rehydrationException = null; try @@ -3587,8 +3587,8 @@ internal object ReadOneObject(out string streamName) rehydrationException = e; } - Dbg.Assert(rehydrationException != null, - "The only way to get here is with rehydrationException != null"); + Dbg.Assert(rehydrationException is not null, + "The only way to get here is with rehydrationException is not null"); PSEtwLog.LogAnalyticError(PSEventId.Serializer_RehydrationFailure, PSOpcode.Rehydration, PSTask.Serialization, PSKeyword.Serializer, @@ -3667,7 +3667,7 @@ private PSObject ReadPSObject() // Check if tag is PrimaryKnownType. TypeSerializationInfo pktInfo = KnownTypes.GetTypeSerializationInfoFromItemTag(_reader.LocalName); - if (pktInfo != null) + if (pktInfo is not null) { s_trace.WriteLine("Primitive Knowntype Element {0}", pktInfo.ItemTag); baseObject = ReadPrimaryKnownType(pktInfo); @@ -3696,7 +3696,7 @@ private PSObject ReadPSObject() } } - if (baseObject != null) + if (baseObject is not null) { dso.SetCoreOnDeserialization(baseObject, overrideTypeInfo); } @@ -3706,7 +3706,7 @@ private PSObject ReadPSObject() ReadEndElement(); PSObject immediateBasePso = dso.ImmediateBaseObject as PSObject; - if (immediateBasePso != null) + if (immediateBasePso is not null) { PSObject.CopyDeserializerFields(source: immediateBasePso, target: dso); } @@ -3725,7 +3725,7 @@ private PSObject ReadAttributeAndCreatePSObject() PSObject sh = new PSObject(); // RefId is not mandatory attribute - if (refId != null) + if (refId is not null) { s_trace.WriteLine("Read PSObject with refId: {0}", refId); _objectRefIdHandler.SetRefId(sh, refId, this.DuplicateRefIdsAllowed); @@ -3742,7 +3742,7 @@ private PSObject ReadAttributeAndCreatePSObject() /// private void ReadTypeNames(PSObject dso) { - Dbg.Assert(dso != null, "caller should validate the parameter"); + Dbg.Assert(dso is not null, "caller should validate the parameter"); Dbg.Assert(_reader.NodeType == XmlNodeType.Element, "NodeType should be Element"); if (IsNextElement(SerializationStrings.TypeNamesTag)) @@ -3778,7 +3778,7 @@ private void ReadTypeNames(PSObject dso) dso.InternalTypeNames = new ConsolidatedString(typeNames); - if (refId != null) + if (refId is not null) { _typeRefIdHandler.SetRefId(dso.InternalTypeNames, refId, this.DuplicateRefIdsAllowed); } @@ -3823,7 +3823,7 @@ private void ReadTypeNames(PSObject dso) /// private void ReadProperties(PSObject dso) { - Dbg.Assert(dso != null, "caller should validate the parameter"); + Dbg.Assert(dso is not null, "caller should validate the parameter"); Dbg.Assert(_reader.NodeType == XmlNodeType.Element, "NodeType should be Element"); // Since we are adding baseobject properties as propertybag, @@ -3863,7 +3863,7 @@ private void ReadProperties(PSObject dso) /// private void ReadMemberSet(PSMemberInfoCollection collection) { - Dbg.Assert(collection != null, "caller should validate the value"); + Dbg.Assert(collection is not null, "caller should validate the value"); if (ReadStartElementAndHandleEmpty(SerializationStrings.MemberSet)) { @@ -4146,7 +4146,7 @@ private static XmlReaderSettings GetXmlReaderSettingsForUntrustedXmlDocument() internal static object DeserializeBoolean(InternalDeserializer deserializer) { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + Dbg.Assert(deserializer is not null, "Caller should validate the parameter"); try { return XmlConvert.ToBoolean(deserializer._reader.ReadElementContentAsString()); @@ -4159,7 +4159,7 @@ internal static object DeserializeBoolean(InternalDeserializer deserializer) internal static object DeserializeByte(InternalDeserializer deserializer) { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + Dbg.Assert(deserializer is not null, "Caller should validate the parameter"); Exception recognizedException = null; try { @@ -4179,7 +4179,7 @@ internal static object DeserializeByte(InternalDeserializer deserializer) internal static object DeserializeChar(InternalDeserializer deserializer) { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + Dbg.Assert(deserializer is not null, "Caller should validate the parameter"); Exception recognizedException = null; try { @@ -4199,7 +4199,7 @@ internal static object DeserializeChar(InternalDeserializer deserializer) internal static object DeserializeDateTime(InternalDeserializer deserializer) { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + Dbg.Assert(deserializer is not null, "Caller should validate the parameter"); try { return XmlConvert.ToDateTime(deserializer._reader.ReadElementContentAsString(), XmlDateTimeSerializationMode.RoundtripKind); @@ -4212,7 +4212,7 @@ internal static object DeserializeDateTime(InternalDeserializer deserializer) internal static object DeserializeDecimal(InternalDeserializer deserializer) { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + Dbg.Assert(deserializer is not null, "Caller should validate the parameter"); Exception recognizedException = null; try { @@ -4232,7 +4232,7 @@ internal static object DeserializeDecimal(InternalDeserializer deserializer) internal static object DeserializeDouble(InternalDeserializer deserializer) { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + Dbg.Assert(deserializer is not null, "Caller should validate the parameter"); Exception recognizedException = null; try { @@ -4252,7 +4252,7 @@ internal static object DeserializeDouble(InternalDeserializer deserializer) internal static object DeserializeGuid(InternalDeserializer deserializer) { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + Dbg.Assert(deserializer is not null, "Caller should validate the parameter"); Exception recognizedException = null; try { @@ -4275,7 +4275,7 @@ internal static object DeserializeGuid(InternalDeserializer deserializer) internal static object DeserializeVersion(InternalDeserializer deserializer) { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + Dbg.Assert(deserializer is not null, "Caller should validate the parameter"); Exception recognizedException = null; try { @@ -4299,7 +4299,7 @@ internal static object DeserializeVersion(InternalDeserializer deserializer) internal static object DeserializeSemanticVersion(InternalDeserializer deserializer) { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + Dbg.Assert(deserializer is not null, "Caller should validate the parameter"); Exception recognizedException = null; try { @@ -4323,7 +4323,7 @@ internal static object DeserializeSemanticVersion(InternalDeserializer deseriali internal static object DeserializeInt16(InternalDeserializer deserializer) { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + Dbg.Assert(deserializer is not null, "Caller should validate the parameter"); Exception recognizedException = null; try { @@ -4343,7 +4343,7 @@ internal static object DeserializeInt16(InternalDeserializer deserializer) internal static object DeserializeInt32(InternalDeserializer deserializer) { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + Dbg.Assert(deserializer is not null, "Caller should validate the parameter"); Exception recognizedException = null; try { @@ -4363,7 +4363,7 @@ internal static object DeserializeInt32(InternalDeserializer deserializer) internal static object DeserializeInt64(InternalDeserializer deserializer) { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + Dbg.Assert(deserializer is not null, "Caller should validate the parameter"); Exception recognizedException = null; try { @@ -4383,7 +4383,7 @@ internal static object DeserializeInt64(InternalDeserializer deserializer) internal static object DeserializeSByte(InternalDeserializer deserializer) { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + Dbg.Assert(deserializer is not null, "Caller should validate the parameter"); Exception recognizedException = null; try { @@ -4403,7 +4403,7 @@ internal static object DeserializeSByte(InternalDeserializer deserializer) internal static object DeserializeSingle(InternalDeserializer deserializer) { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + Dbg.Assert(deserializer is not null, "Caller should validate the parameter"); Exception recognizedException = null; try { @@ -4423,7 +4423,7 @@ internal static object DeserializeSingle(InternalDeserializer deserializer) internal static object DeserializeScriptBlock(InternalDeserializer deserializer) { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + Dbg.Assert(deserializer is not null, "Caller should validate the parameter"); string scriptBlockBody = deserializer.ReadDecodedElementString(SerializationStrings.ScriptBlockTag); if (DeserializationOptions.DeserializeScriptBlocks == (deserializer._context.options & DeserializationOptions.DeserializeScriptBlocks)) { @@ -4438,13 +4438,13 @@ internal static object DeserializeScriptBlock(InternalDeserializer deserializer) internal static object DeserializeString(InternalDeserializer deserializer) { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + Dbg.Assert(deserializer is not null, "Caller should validate the parameter"); return deserializer.ReadDecodedElementString(SerializationStrings.StringTag); } internal static object DeserializeTimeSpan(InternalDeserializer deserializer) { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + Dbg.Assert(deserializer is not null, "Caller should validate the parameter"); try { return XmlConvert.ToTimeSpan(deserializer._reader.ReadElementContentAsString()); @@ -4457,7 +4457,7 @@ internal static object DeserializeTimeSpan(InternalDeserializer deserializer) internal static object DeserializeUInt16(InternalDeserializer deserializer) { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + Dbg.Assert(deserializer is not null, "Caller should validate the parameter"); Exception recognizedException = null; try { @@ -4477,7 +4477,7 @@ internal static object DeserializeUInt16(InternalDeserializer deserializer) internal static object DeserializeUInt32(InternalDeserializer deserializer) { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + Dbg.Assert(deserializer is not null, "Caller should validate the parameter"); Exception recognizedException = null; try { @@ -4497,7 +4497,7 @@ internal static object DeserializeUInt32(InternalDeserializer deserializer) internal static object DeserializeUInt64(InternalDeserializer deserializer) { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + Dbg.Assert(deserializer is not null, "Caller should validate the parameter"); Exception recognizedException = null; try { @@ -4517,7 +4517,7 @@ internal static object DeserializeUInt64(InternalDeserializer deserializer) internal static object DeserializeUri(InternalDeserializer deserializer) { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + Dbg.Assert(deserializer is not null, "Caller should validate the parameter"); try { string uriString = deserializer.ReadDecodedElementString(SerializationStrings.AnyUriTag); @@ -4531,7 +4531,7 @@ internal static object DeserializeUri(InternalDeserializer deserializer) internal static object DeserializeByteArray(InternalDeserializer deserializer) { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + Dbg.Assert(deserializer is not null, "Caller should validate the parameter"); try { return Convert.FromBase64String(deserializer._reader.ReadElementContentAsString()); @@ -4613,7 +4613,7 @@ internal static XmlDocument LoadUnsafeXmlDocument(TextReader textReader, bool pr internal static object DeserializeXmlDocument(InternalDeserializer deserializer) { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + Dbg.Assert(deserializer is not null, "Caller should validate the parameter"); string docAsString = deserializer.ReadDecodedElementString(SerializationStrings.XmlDocumentTag); try @@ -4641,7 +4641,7 @@ internal static object DeserializeXmlDocument(InternalDeserializer deserializer) internal static object DeserializeProgressRecord(InternalDeserializer deserializer) { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + Dbg.Assert(deserializer is not null, "Caller should validate the parameter"); // // read deserialized elements of a progress record @@ -4676,7 +4676,7 @@ internal static object DeserializeProgressRecord(InternalDeserializer deserializ recognizedException = e; } - if (recognizedException != null) + if (recognizedException is not null) { throw deserializer.NewXmlException(Serialization.InvalidPrimitiveType, recognizedException, typeof(UInt64).FullName); } @@ -4721,7 +4721,7 @@ internal static object DeserializeProgressRecord(InternalDeserializer deserializ internal static object DeserializeSecureString(InternalDeserializer deserializer) { - Dbg.Assert(deserializer != null, "Caller should validate the parameter"); + Dbg.Assert(deserializer is not null, "Caller should validate the parameter"); // // read deserialized elements of a Secure String @@ -4830,8 +4830,8 @@ private void Skip() /// private object ReadPrimaryKnownType(TypeSerializationInfo pktInfo) { - Dbg.Assert(pktInfo != null, "Deserializer should be available"); - Dbg.Assert(pktInfo.Deserializer != null, "Deserializer should be available"); + Dbg.Assert(pktInfo is not null, "Deserializer should be available"); + Dbg.Assert(pktInfo.Deserializer is not null, "Deserializer should be available"); object result = pktInfo.Deserializer(this); _reader.MoveToContent(); return result; @@ -4844,7 +4844,7 @@ private object ReadSecureString() try { object result; - if (_context.cryptoHelper != null) + if (_context.cryptoHelper is not null) { result = _context.cryptoHelper.DecryptSecureString(encryptedString); } @@ -4885,7 +4885,7 @@ params object[] args XmlException ex = null; IXmlLineInfo xmlLineInfo = _reader as IXmlLineInfo; - if (xmlLineInfo != null) + if (xmlLineInfo is not null) { if (xmlLineInfo.HasLineInfo()) { @@ -4915,7 +4915,7 @@ private string ReadNameAttribute() private static string DecodeString(string s) { - Dbg.Assert(s != null, "Caller should validate the parameter"); + Dbg.Assert(s is not null, "Caller should validate the parameter"); return XmlConvert.DecodeName(s); } @@ -4962,7 +4962,7 @@ internal ReferenceIdHandlerForSerializer(IDictionary dictionary) /// RefId assigned to the object. internal string SetRefId(T t) { - if (_object2refId != null) + if (_object2refId is not null) { Dbg.Assert(!_object2refId.ContainsKey(t), "SetRefId shouldn't be called when the object is already assigned a ref id"); UInt64 refId = GetNewReferenceId(); @@ -4983,7 +4983,7 @@ internal string SetRefId(T t) internal string GetRefId(T t) { UInt64 refId; - if ((_object2refId != null) && (_object2refId.TryGetValue(t, out refId))) + if ((_object2refId is not null) && (_object2refId.TryGetValue(t, out refId))) { return refId.ToString(System.Globalization.CultureInfo.InvariantCulture); } @@ -5354,14 +5354,14 @@ internal static void GetKnownContainerTypeInfo( out IDictionary dictionary, out IEnumerable enumerable) { - Dbg.Assert(source != null, "caller should validate the parameter"); + Dbg.Assert(source is not null, "caller should validate the parameter"); ct = ContainerType.None; dictionary = null; enumerable = null; dictionary = source as IDictionary; - if (dictionary != null) + if (dictionary is not null) { ct = ContainerType.Dictionary; } @@ -5369,19 +5369,19 @@ internal static void GetKnownContainerTypeInfo( { ct = ContainerType.Stack; enumerable = LanguagePrimitives.GetEnumerable(source); - Dbg.Assert(enumerable != null, "Stack is enumerable"); + Dbg.Assert(enumerable is not null, "Stack is enumerable"); } else if (source is Queue) { ct = ContainerType.Queue; enumerable = LanguagePrimitives.GetEnumerable(source); - Dbg.Assert(enumerable != null, "Queue is enumerable"); + Dbg.Assert(enumerable is not null, "Queue is enumerable"); } else if (source is IList) { ct = ContainerType.List; enumerable = LanguagePrimitives.GetEnumerable(source); - Dbg.Assert(enumerable != null, "IList is enumerable"); + Dbg.Assert(enumerable is not null, "IList is enumerable"); } else { @@ -5392,19 +5392,19 @@ internal static void GetKnownContainerTypeInfo( { ct = ContainerType.Stack; enumerable = LanguagePrimitives.GetEnumerable(source); - Dbg.Assert(enumerable != null, "Stack is enumerable"); + Dbg.Assert(enumerable is not null, "Stack is enumerable"); } else if (DerivesFromGenericType(gt, typeof(Queue<>))) { ct = ContainerType.Queue; enumerable = LanguagePrimitives.GetEnumerable(source); - Dbg.Assert(enumerable != null, "Queue is enumerable"); + Dbg.Assert(enumerable is not null, "Queue is enumerable"); } else if (DerivesFromGenericType(gt, typeof(List<>))) { ct = ContainerType.List; enumerable = LanguagePrimitives.GetEnumerable(source); - Dbg.Assert(enumerable != null, "Queue is enumerable"); + Dbg.Assert(enumerable is not null, "Queue is enumerable"); } } } @@ -5415,7 +5415,7 @@ internal static void GetKnownContainerTypeInfo( try { enumerable = LanguagePrimitives.GetEnumerable(source); - if (enumerable != null) + if (enumerable is not null) { ct = ContainerType.Enumerable; } @@ -5435,12 +5435,12 @@ internal static void GetKnownContainerTypeInfo( if (ct == ContainerType.None) { enumerable = source as IEnumerable; - if (enumerable != null) + if (enumerable is not null) { // WinBlue: 206515 - There are no elements in the source. The source is of type XmlLinkedNode (which derives from XmlNode which implements IEnumerable). // So, adding an additional check to see if this contains any elements IEnumerator enumerator = enumerable.GetEnumerator(); - if (enumerator != null && enumerator.MoveNext()) + if (enumerator is not null && enumerator.MoveNext()) { ct = ContainerType.Enumerable; } @@ -5456,9 +5456,9 @@ internal static void GetKnownContainerTypeInfo( /// private static bool DerivesFromGenericType(Type derived, Type baseType) { - Dbg.Assert(derived != null, "caller should validate the parameter"); - Dbg.Assert(baseType != null, "caller should validate the parameter"); - while (derived != null) + Dbg.Assert(derived is not null, "caller should validate the parameter"); + Dbg.Assert(baseType is not null, "caller should validate the parameter"); + while (derived is not null) { if (derived.IsGenericType) derived = derived.GetGenericTypeDefinition(); @@ -5485,7 +5485,7 @@ private static bool DerivesFromGenericType(Type derived, Type baseType) /// internal static string GetToString(object source) { - Dbg.Assert(source != null, "caller should have validated the information"); + Dbg.Assert(source is not null, "caller should have validated the information"); // fall back value string result = null; @@ -5516,14 +5516,14 @@ internal static string GetToStringForPrimitiveObject(PSObject pso) } // preserve ToString throughout deserialization/*re*serialization - if (pso.ToStringFromDeserialization != null) + if (pso.ToStringFromDeserialization is not null) { return pso.ToStringFromDeserialization; } // preserve token text (i.e. double: 0E1517567410; see Windows 7 bug #694057 for more details) string token = pso.TokenText; - if (token != null) + if (token is not null) { string originalToString = GetToString(pso.BaseObject); if (originalToString is null || !string.Equals(token, originalToString, StringComparison.Ordinal)) @@ -5584,7 +5584,7 @@ internal static PSMemberInfoInternalCollection GetSpecificProper internal static object GetPropertyValueInThreadSafeManner(PSPropertyInfo property, bool canUseDefaultRunspaceInThreadSafeManner, out bool success) { - Dbg.Assert(property != null, "Caller should validate the parameter"); + Dbg.Assert(property is not null, "Caller should validate the parameter"); if (!property.IsGettable) { @@ -5593,14 +5593,14 @@ internal static object GetPropertyValueInThreadSafeManner(PSPropertyInfo propert } PSAliasProperty alias = property as PSAliasProperty; - if (alias != null) + if (alias is not null) { property = alias.ReferencedMember as PSPropertyInfo; } PSScriptProperty script = property as PSScriptProperty; - Dbg.Assert(script is null || script.GetterScript != null, "scriptProperty.IsGettable => (scriptProperty.GetterScript != null)"); - if ((script != null) && (!canUseDefaultRunspaceInThreadSafeManner)) + Dbg.Assert(script is null || script.GetterScript is not null, "scriptProperty.IsGettable => (scriptProperty.GetterScript is not null)"); + if ((script is not null) && (!canUseDefaultRunspaceInThreadSafeManner)) { PSEtwLog.LogAnalyticWarning( PSEventId.Serializer_ScriptPropertyWithoutRunspace, PSOpcode.Exception, PSTask.Serialization, @@ -5703,7 +5703,7 @@ private void CleanUp() foreach (KeyValuePair weakKeyValuePair in _dictionary) { object key = weakKeyValuePair.Key.Target; - if (key != null) + if (key is not null) { alive.Add(weakKeyValuePair.Key, weakKeyValuePair.Value); } @@ -5735,7 +5735,7 @@ public ICollection Keys foreach (WeakReference weakKey in _dictionary.Keys) { object key = weakKey.Target; - if (key != null) + if (key is not null) { keys.Add(key); } @@ -5852,7 +5852,7 @@ public IEnumerator> GetEnumerator() foreach (KeyValuePair weakKeyValuePair in this.WeakCollection) { object key = weakKeyValuePair.Key.Target; - if (key != null) + if (key is not null) { yield return new KeyValuePair(key, weakKeyValuePair.Value); } @@ -5913,7 +5913,7 @@ public PSPrimitiveDictionary(Hashtable other) foreach (DictionaryEntry entry in other) { Hashtable valueAsHashtable = PSObject.Base(entry.Value) as Hashtable; - if (valueAsHashtable != null) + if (valueAsHashtable is not null) { this.Add(entry.Key, new PSPrimitiveDictionary(valueAsHashtable)); } @@ -6505,14 +6505,14 @@ public void Add(string key, PSPrimitiveDictionary[] value) /// internal static PSPrimitiveDictionary CloneAndAddPSVersionTable(PSPrimitiveDictionary originalHash) { - if ((originalHash != null) && + if ((originalHash is not null) && (originalHash.ContainsKey(PSVersionInfo.PSVersionTableName))) { return (PSPrimitiveDictionary)originalHash.Clone(); } PSPrimitiveDictionary result = originalHash; - if (originalHash != null) + if (originalHash is not null) { result = (PSPrimitiveDictionary)originalHash.Clone(); } @@ -6542,9 +6542,9 @@ internal static PSPrimitiveDictionary CloneAndAddPSVersionTable(PSPrimitiveDicti /// true if the value was found and was of the correct type; false otherwise. internal static bool TryPathGet(IDictionary data, out T result, params string[] keys) { - Dbg.Assert(keys != null, "Caller should verify that keys != null"); + Dbg.Assert(keys is not null, "Caller should verify that keys is not null"); Dbg.Assert(keys.Length >= 1, "Caller should verify that keys.Length >= 1"); - Dbg.Assert(keys[0] != null, "Caller should verify that keys[i] != null"); + Dbg.Assert(keys[0] is not null, "Caller should verify that keys[i] is not null"); if (data is null || !data.Contains(keys[0])) { @@ -6560,7 +6560,7 @@ internal static bool TryPathGet(IDictionary data, out T result, params string { IDictionary subData; if (LanguagePrimitives.TryConvertTo(data[keys[0]], out subData) - && subData != null) + && subData is not null) { string[] subKeys = new string[keys.Length - 1]; Array.Copy(keys, 1, subKeys, 0, subKeys.Length); @@ -6853,8 +6853,8 @@ private static T GetPropertyValue(PSObject pso, string propertyName) /// internal static T GetPropertyValue(PSObject pso, string propertyName, RehydrationFlags flags) { - Dbg.Assert(pso != null, "Caller should verify pso != null"); - Dbg.Assert(!string.IsNullOrEmpty(propertyName), "Caller should verify propertyName != null"); + Dbg.Assert(pso is not null, "Caller should verify pso is not null"); + Dbg.Assert(!string.IsNullOrEmpty(propertyName), "Caller should verify propertyName is not null"); PSPropertyInfo property = pso.Properties[propertyName]; if ((property is null) && (RehydrationFlags.MissingPropertyOk == (flags & RehydrationFlags.MissingPropertyOk))) @@ -6930,19 +6930,19 @@ private static PSListModifier RehydratePSListModifier(PSObject pso) Hashtable h = new Hashtable(); PSPropertyInfo addProperty = pso.Properties[PSListModifier.AddKey]; - if ((addProperty != null) && (addProperty.Value != null)) + if ((addProperty is not null) && (addProperty.Value is not null)) { h.Add(PSListModifier.AddKey, addProperty.Value); } PSPropertyInfo removeProperty = pso.Properties[PSListModifier.RemoveKey]; - if ((removeProperty != null) && (removeProperty.Value != null)) + if ((removeProperty is not null) && (removeProperty.Value is not null)) { h.Add(PSListModifier.RemoveKey, removeProperty.Value); } PSPropertyInfo replaceProperty = pso.Properties[PSListModifier.ReplaceKey]; - if ((replaceProperty != null) && (replaceProperty.Value != null)) + if ((replaceProperty is not null) && (replaceProperty.Value is not null)) { h.Add(PSListModifier.ReplaceKey, replaceProperty.Value); } @@ -6996,12 +6996,12 @@ private static JobStateInfo RehydrateJobStateInfo(PSObject pso) PSPropertyInfo property = pso.Properties["Reason"]; string message = string.Empty; - if (property != null) + if (property is not null) { propertyValue = property.Value; } - if (propertyValue != null) + if (propertyValue is not null) { if (Deserializer.IsDeserializedInstanceOfType(propertyValue, typeof(Exception))) { @@ -7042,7 +7042,7 @@ internal static JobStateEventArgs RehydrateJobStateEventArgs(PSObject pso) JobStateInfo previousJobStateInfo = null; var previousJobStateInfoProperty = pso.Properties["PreviousJobStateInfo"]; - if (previousJobStateInfoProperty != null && previousJobStateInfoProperty.Value != null) + if (previousJobStateInfoProperty is not null && previousJobStateInfoProperty.Value is not null) { previousJobStateInfo = RehydrateJobStateInfo(PSObject.AsPSObject(previousJobStateInfoProperty.Value)); } @@ -7156,13 +7156,13 @@ internal static DebuggerCommandResults RehydrateDebuggerCommandResults(PSObject internal static DebuggerStopEventArgs RehydrateDebuggerStopEventArgs(PSObject pso) { PSObject psoInvocationInfo = GetPropertyValue(pso, "SerializedInvocationInfo", RehydrationFlags.NullValueOk | RehydrationFlags.MissingPropertyOk); - InvocationInfo invocationInfo = (psoInvocationInfo != null) ? new InvocationInfo(psoInvocationInfo) : null; + InvocationInfo invocationInfo = (psoInvocationInfo is not null) ? new InvocationInfo(psoInvocationInfo) : null; DebuggerResumeAction resumeAction = GetPropertyValue(pso, "ResumeAction"); Collection breakpoints = new Collection(); foreach (var item in GetPropertyValue(pso, "Breakpoints")) { Breakpoint bp = item as Breakpoint; - if (bp != null) + if (bp is not null) { breakpoints.Add(bp); } @@ -7600,7 +7600,7 @@ private static ExtendedTypeDefinition RehydrateExtendedTypeDefinition(PSObject d RehydrationFlags.NullValueBad); var result = new ExtendedTypeDefinition(typeName, viewDefinitions); - if (typeNames != null && typeNames.Count > 1) + if (typeNames is not null && typeNames.Count > 1) { for (var i = 1; i < typeNames.Count; i++) { diff --git a/src/System.Management.Automation/help/AliasHelpProvider.cs b/src/System.Management.Automation/help/AliasHelpProvider.cs index 28cd655e6eb..4a8e8fa1a7b 100644 --- a/src/System.Management.Automation/help/AliasHelpProvider.cs +++ b/src/System.Management.Automation/help/AliasHelpProvider.cs @@ -106,12 +106,12 @@ internal override IEnumerable ExactMatchHelp(HelpRequest helpRequest) // commandlet. Just ignore this exception and bail out. } - if ((commandInfo != null) && (commandInfo.CommandType == CommandTypes.Alias)) + if ((commandInfo is not null) && (commandInfo.CommandType == CommandTypes.Alias)) { AliasInfo aliasInfo = (AliasInfo)commandInfo; HelpInfo helpInfo = AliasHelpInfo.GetHelpInfo(aliasInfo); - if (helpInfo != null) + if (helpInfo is not null) { yield return helpInfo; } @@ -198,7 +198,7 @@ internal override IEnumerable SearchHelp(HelpRequest helpRequest, bool AliasInfo alias = current as AliasInfo; - if (alias != null) + if (alias is not null) { string name = alias.Name; HelpRequest exactMatchHelpRequest = helpRequest.Clone(); @@ -237,7 +237,7 @@ internal override IEnumerable SearchHelp(HelpRequest helpRequest, bool AliasInfo alias = current as AliasInfo; - if (alias != null) + if (alias is not null) { string name = alias.Name; diff --git a/src/System.Management.Automation/help/BaseCommandHelpInfo.cs b/src/System.Management.Automation/help/BaseCommandHelpInfo.cs index 12554ee2f14..fb523396029 100644 --- a/src/System.Management.Automation/help/BaseCommandHelpInfo.cs +++ b/src/System.Management.Automation/help/BaseCommandHelpInfo.cs @@ -143,7 +143,7 @@ internal override Uri GetUriForOnlineHelp() try { result = GetUriFromCommandPSObject(this.FullHelp); - if (result != null) + if (result is not null) { return result; } @@ -154,11 +154,11 @@ internal override Uri GetUriForOnlineHelp() } // else get uri from CommandInfo HelpUri attribute result = this.LookupUriFromCommandInfo(); - if (result != null) + if (result is not null) { return result; } - else if (uriFormatException != null) + else if (uriFormatException is not null) { throw uriFormatException; } @@ -201,10 +201,10 @@ internal Uri LookupUriFromCommandInfo() string commandName = this.Name; string moduleName = string.Empty; - if (this.FullHelp.Properties["ModuleName"] != null) + if (this.FullHelp.Properties["ModuleName"] is not null) { PSNoteProperty moduleNameNP = this.FullHelp.Properties["ModuleName"] as PSNoteProperty; - if (moduleNameNP != null) + if (moduleNameNP is not null) { LanguagePrimitives.TryConvertTo(moduleNameNP.Value, CultureInfo.InvariantCulture, out moduleName); @@ -306,7 +306,7 @@ internal static Uri GetUriFromCommandPSObject(PSObject commandFullHelp) PSObject navigationLink = PSObject.AsPSObject(navigationLinkAsObject); PSNoteProperty uriNP = navigationLink.Properties["uri"] as PSNoteProperty; - if (uriNP != null) + if (uriNP is not null) { string uriString = string.Empty; LanguagePrimitives.TryConvertTo(uriNP.Value, CultureInfo.InvariantCulture, out uriString); @@ -351,7 +351,7 @@ internal static Uri GetUriFromCommandPSObject(PSObject commandFullHelp) /// internal override bool MatchPatternInContent(WildcardPattern pattern) { - Dbg.Assert(pattern != null, "pattern cannot be null"); + Dbg.Assert(pattern is not null, "pattern cannot be null"); string synopsis = Synopsis; string detailedDescription = DetailedDescription; @@ -405,7 +405,7 @@ internal override PSObject[] GetParameter(string pattern) } PSObject[] prmtArray = (PSObject[])LanguagePrimitives.ConvertTo( - paramAsPSObjArray[0] != null ? paramAsPSObjArray : param, + paramAsPSObjArray[0] is not null ? paramAsPSObjArray : param, typeof(PSObject[]), CultureInfo.InvariantCulture); diff --git a/src/System.Management.Automation/help/CabinetAPI.cs b/src/System.Management.Automation/help/CabinetAPI.cs index eb407f2ec62..ea7a8e2e339 100644 --- a/src/System.Management.Automation/help/CabinetAPI.cs +++ b/src/System.Management.Automation/help/CabinetAPI.cs @@ -98,7 +98,7 @@ static CabinetExtractorFactory() /// Tracer instance. internal static ICabinetExtractor GetCabinetExtractor() { - if (s_cabinetLoader != null) + if (s_cabinetLoader is not null) { return s_cabinetLoader.GetCabinetExtractor(); } diff --git a/src/System.Management.Automation/help/CabinetNativeApi.cs b/src/System.Management.Automation/help/CabinetNativeApi.cs index 7c2333fc380..120253f5128 100644 --- a/src/System.Management.Automation/help/CabinetNativeApi.cs +++ b/src/System.Management.Automation/help/CabinetNativeApi.cs @@ -70,7 +70,7 @@ protected override void Dispose(bool disposing) } // Free managed objects within 'if (disposing)' if needed - if (fdiContext != null) + if (fdiContext is not null) { fdiContext.Dispose(); } @@ -152,7 +152,7 @@ private void populateDelegates() private void CleanUpDelegates() { // Free GCHandles so that the memory they point to may be unpinned (garbage collected) - if (_fdiAllocHandle != null) + if (_fdiAllocHandle is not null) { _fdiAllocHandle.Free(); _fdiFreeHandle.Free(); diff --git a/src/System.Management.Automation/help/CommandHelpProvider.cs b/src/System.Management.Automation/help/CommandHelpProvider.cs index b97d36ac793..04cdeb272cf 100644 --- a/src/System.Management.Automation/help/CommandHelpProvider.cs +++ b/src/System.Management.Automation/help/CommandHelpProvider.cs @@ -86,7 +86,7 @@ internal override HelpCategory HelpCategory private void GetModulePaths(CommandInfo commandInfo, out string moduleName, out string moduleDir, out string nestedModulePath) { - Dbg.Assert(commandInfo != null, "Caller should verify that commandInfo != null"); + Dbg.Assert(commandInfo is not null, "Caller should verify that commandInfo is not null"); CmdletInfo cmdletInfo = commandInfo as CmdletInfo; IScriptCommandInfo scriptCommandInfo = commandInfo as IScriptCommandInfo; @@ -98,7 +98,7 @@ private void GetModulePaths(CommandInfo commandInfo, out string moduleName, out moduleDir = null; nestedModulePath = null; - if (commandInfo.Module != null) + if (commandInfo.Module is not null) { moduleName = commandInfo.Module.Name; moduleDir = commandInfo.Module.ModuleBase; @@ -109,18 +109,18 @@ private void GetModulePaths(CommandInfo commandInfo, out string moduleName, out cmdNameWithoutPrefix = Microsoft.PowerShell.Commands.ModuleCmdletBase.RemovePrefixFromCommandName(commandInfo.Name, commandInfo.Prefix); } - if (commandInfo.Module.NestedModules != null) + if (commandInfo.Module.NestedModules is not null) { foreach (PSModuleInfo nestedModule in commandInfo.Module.NestedModules) { - if (cmdletInfo != null && + if (cmdletInfo is not null && (nestedModule.ExportedCmdlets.ContainsKey(commandInfo.Name) || (testWithoutPrefix && nestedModule.ExportedCmdlets.ContainsKey(cmdNameWithoutPrefix)))) { nestedModulePath = nestedModule.Path; break; } - else if (scriptCommandInfo != null && + else if (scriptCommandInfo is not null && (nestedModule.ExportedFunctions.ContainsKey(commandInfo.Name) || (testWithoutPrefix && nestedModule.ExportedFunctions.ContainsKey(cmdNameWithoutPrefix)))) { @@ -134,11 +134,11 @@ private void GetModulePaths(CommandInfo commandInfo, out string moduleName, out private string GetHelpName(CommandInfo commandInfo) { - Dbg.Assert(commandInfo != null, "Caller should verify that commandInfo != null"); + Dbg.Assert(commandInfo is not null, "Caller should verify that commandInfo is not null"); CmdletInfo cmdletInfo = commandInfo as CmdletInfo; - if (cmdletInfo != null) + if (cmdletInfo is not null) { return cmdletInfo.FullName; } @@ -148,8 +148,8 @@ private string GetHelpName(CommandInfo commandInfo) private HelpInfo GetHelpInfoFromHelpFile(CommandInfo commandInfo, string helpFileToFind, Collection searchPaths, bool reportErrors, out string helpFile) { - Dbg.Assert(commandInfo != null, "Caller should verify that commandInfo != null"); - Dbg.Assert(helpFileToFind != null, "Caller should verify that helpFileToFind != null"); + Dbg.Assert(commandInfo is not null, "Caller should verify that commandInfo is not null"); + Dbg.Assert(helpFileToFind is not null, "Caller should verify that helpFileToFind is not null"); CmdletInfo cmdletInfo = commandInfo as CmdletInfo; IScriptCommandInfo scriptCommandInfo = commandInfo as IScriptCommandInfo; @@ -162,21 +162,21 @@ private HelpInfo GetHelpInfoFromHelpFile(CommandInfo commandInfo, string helpFil { if (!_helpFiles.Contains(helpFile)) { - if (cmdletInfo != null) + if (cmdletInfo is not null) { LoadHelpFile(helpFile, cmdletInfo.ModuleName, cmdletInfo.Name, reportErrors); } - else if (scriptCommandInfo != null) + else if (scriptCommandInfo is not null) { LoadHelpFile(helpFile, helpFile, commandInfo.Name, reportErrors); } } - if (cmdletInfo != null) + if (cmdletInfo is not null) { result = GetFromCommandCacheOrCmdletInfo(cmdletInfo); } - else if (scriptCommandInfo != null) + else if (scriptCommandInfo is not null) { result = GetFromCommandCache(helpFile, commandInfo); } @@ -188,7 +188,7 @@ private HelpInfo GetHelpInfoFromHelpFile(CommandInfo commandInfo, string helpFil [SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", Justification = "TestUri is created only to check for source helpUriFromDotLink errors.")] private HelpInfo GetHelpInfo(CommandInfo commandInfo, bool reportErrors, bool searchOnlyContent) { - Dbg.Assert(commandInfo != null, "Caller should verify that commandInfo != null"); + Dbg.Assert(commandInfo is not null, "Caller should verify that commandInfo is not null"); HelpInfo result = null; // The help result string helpFile = null; // The file that contains the help info @@ -198,9 +198,9 @@ private HelpInfo GetHelpInfo(CommandInfo commandInfo, bool reportErrors, bool se CmdletInfo cmdletInfo = commandInfo as CmdletInfo; IScriptCommandInfo scriptCommandInfo = commandInfo as IScriptCommandInfo; FunctionInfo functionInfo = commandInfo as FunctionInfo; - bool isCmdlet = cmdletInfo != null; - bool isScriptCommand = scriptCommandInfo != null; - bool isFunction = functionInfo != null; + bool isCmdlet = cmdletInfo is not null; + bool isScriptCommand = scriptCommandInfo is not null; + bool isFunction = functionInfo is not null; string moduleName = null; string moduleDir = null; @@ -262,7 +262,7 @@ private HelpInfo GetHelpInfo(CommandInfo commandInfo, bool reportErrors, bool se return null; } - if (sb != null) + if (sb is not null) { helpFile = null; // searchOnlyContent == true means get-help is looking into the content, in this case we dont @@ -285,11 +285,11 @@ private HelpInfo GetHelpInfo(CommandInfo commandInfo, bool reportErrors, bool se } } - if (result != null) + if (result is not null) { Uri uri = result.GetUriForOnlineHelp(); - if (uri != null) + if (uri is not null) { helpUri = uri.ToString(); } @@ -348,7 +348,7 @@ private HelpInfo GetHelpInfo(CommandInfo commandInfo, bool reportErrors, bool se } // Set the HelpFile property to the file that contains the help content - if (result != null && !string.IsNullOrEmpty(helpFile)) + if (result is not null && !string.IsNullOrEmpty(helpFile)) { if (isCmdlet) { @@ -381,7 +381,7 @@ private HelpInfo GetHelpInfo(CommandInfo commandInfo, bool reportErrors, bool se } } - if (result != null) + if (result is not null) { if (isScriptCommand && result.GetUriForOnlineHelp() is null) { @@ -445,7 +445,7 @@ internal override IEnumerable ExactMatchHelp(HelpRequest helpRequest) HelpInfo helpInfo = GetHelpInfo(current, true, false); string helpName = GetHelpName(current); - if (helpInfo != null && !string.IsNullOrEmpty(helpName)) + if (helpInfo is not null && !string.IsNullOrEmpty(helpName)) { if (helpInfo.ForwardHelpCategory == helpRequest.HelpCategory && helpInfo.ForwardTarget.Equals(helpRequest.Target, StringComparison.OrdinalIgnoreCase)) @@ -509,7 +509,7 @@ private string GetHelpFile(string helpFile, CmdletInfo cmdletInfo) { helpFileToLoad = Path.GetFileName(helpFileToLoad); - if (mshSnapInInfo != null) + if (mshSnapInInfo is not null) { Diagnostics.Assert(!string.IsNullOrEmpty(mshSnapInInfo.ApplicationBase), "Application Base is null or empty."); @@ -521,7 +521,7 @@ private string GetHelpFile(string helpFile, CmdletInfo cmdletInfo) searchPaths.Add(HelpUtils.GetUserHomeHelpSearchPath()); searchPaths.Add(mshSnapInInfo.ApplicationBase); } - else if (cmdletInfo.Module != null && !string.IsNullOrEmpty(cmdletInfo.Module.Path) && !string.IsNullOrEmpty(cmdletInfo.Module.ModuleBase)) + else if (cmdletInfo.Module is not null && !string.IsNullOrEmpty(cmdletInfo.Module.Path) && !string.IsNullOrEmpty(cmdletInfo.Module.ModuleBase)) { searchPaths.Add(HelpUtils.GetModuleBaseForUserHelp(cmdletInfo.Module.ModuleBase, cmdletInfo.Module.Name)); searchPaths.Add(cmdletInfo.Module.ModuleBase); @@ -574,7 +574,7 @@ private string FindHelpFile(CmdletInfo cmdletInfo) if (string.IsNullOrEmpty(helpFile)) { - if (cmdletInfo.Module != null) + if (cmdletInfo.Module is not null) { if (InitialSessionState.IsEngineModule(cmdletInfo.Module.Name)) { @@ -663,7 +663,7 @@ private void LoadHelpFile(string helpFile, string helpFileIdentifier, string com e = invalidOperationException; } - if (reportErrors && (e != null)) + if (reportErrors && (e is not null)) { ReportHelpFileError(e, commandName, helpFile); } @@ -728,7 +728,7 @@ private void LoadHelpFile(string helpFile, string helpFileIdentifier) helpInfo = MamlCommandHelpInfo.Load(node, HelpCategory.Cmdlet); } - if (helpInfo != null) + if (helpInfo is not null) { this.HelpSystem.TraceErrors(helpInfo.Errors); AddToCommandCache(helpFileIdentifier, helpInfo.Name, helpInfo); @@ -795,7 +795,7 @@ private HelpInfo GetFromCommandCache(string helpFileIdentifier, string commandNa HelpInfo result = GetCache(key); // Win8: Win8:477680: When Function/Workflow Use External Help, Category Property is "Cmdlet" - if ((result != null) && (result.HelpCategory != helpCategory)) + if ((result is not null) && (result.HelpCategory != helpCategory)) { MamlCommandHelpInfo original = (MamlCommandHelpInfo)result; result = original.Copy(helpCategory); @@ -812,15 +812,15 @@ private HelpInfo GetFromCommandCache(string helpFileIdentifier, string commandNa /// HelpInfo object. private HelpInfo GetFromCommandCache(string helpFileIdentifier, CommandInfo commandInfo) { - Debug.Assert(commandInfo != null, "commandInfo cannot be null"); + Debug.Assert(commandInfo is not null, "commandInfo cannot be null"); HelpInfo result = GetFromCommandCache(helpFileIdentifier, commandInfo.Name, commandInfo.HelpCategory); if (result is null) { // check if the command is prefixed and try retrieving help by removing the prefix - if ((commandInfo.Module != null) && (!string.IsNullOrEmpty(commandInfo.Prefix))) + if ((commandInfo.Module is not null) && (!string.IsNullOrEmpty(commandInfo.Prefix))) { MamlCommandHelpInfo newMamlHelpInfo = GetFromCommandCacheByRemovingPrefix(helpFileIdentifier, commandInfo); - if (newMamlHelpInfo != null) + if (newMamlHelpInfo is not null) { // caching the changed help content under the prefixed name for faster // retrieval later. @@ -842,24 +842,24 @@ private HelpInfo GetFromCommandCache(string helpFileIdentifier, CommandInfo comm /// private HelpInfo GetFromCommandCacheOrCmdletInfo(CmdletInfo cmdletInfo) { - Debug.Assert(cmdletInfo != null, "cmdletInfo cannot be null"); + Debug.Assert(cmdletInfo is not null, "cmdletInfo cannot be null"); HelpInfo result = GetFromCommandCache(cmdletInfo.ModuleName, cmdletInfo.Name, cmdletInfo.HelpCategory); if (result is null) { // check if the command is prefixed and try retrieving help by removing the prefix - if ((cmdletInfo.Module != null) && (!string.IsNullOrEmpty(cmdletInfo.Prefix))) + if ((cmdletInfo.Module is not null) && (!string.IsNullOrEmpty(cmdletInfo.Prefix))) { MamlCommandHelpInfo newMamlHelpInfo = GetFromCommandCacheByRemovingPrefix(cmdletInfo.ModuleName, cmdletInfo); - if (newMamlHelpInfo != null) + if (newMamlHelpInfo is not null) { // Noun exists only for cmdlets...since prefix will change the Noun, updating // the help content accordingly - if (newMamlHelpInfo.FullHelp.Properties["Details"] != null && - newMamlHelpInfo.FullHelp.Properties["Details"].Value != null) + if (newMamlHelpInfo.FullHelp.Properties["Details"] is not null && + newMamlHelpInfo.FullHelp.Properties["Details"].Value is not null) { PSObject commandDetails = PSObject.AsPSObject(newMamlHelpInfo.FullHelp.Properties["Details"].Value); - if (commandDetails.Properties["Noun"] != null) + if (commandDetails.Properties["Noun"] is not null) { commandDetails.Properties.Remove("Noun"); } @@ -894,35 +894,35 @@ private HelpInfo GetFromCommandCacheOrCmdletInfo(CmdletInfo cmdletInfo) /// private MamlCommandHelpInfo GetFromCommandCacheByRemovingPrefix(string helpIdentifier, CommandInfo cmdInfo) { - Dbg.Assert(cmdInfo != null, "cmdInfo cannot be null"); + Dbg.Assert(cmdInfo is not null, "cmdInfo cannot be null"); MamlCommandHelpInfo result = null; MamlCommandHelpInfo originalHelpInfo = GetFromCommandCache(helpIdentifier, Microsoft.PowerShell.Commands.ModuleCmdletBase.RemovePrefixFromCommandName(cmdInfo.Name, cmdInfo.Prefix), cmdInfo.HelpCategory) as MamlCommandHelpInfo; - if (originalHelpInfo != null) + if (originalHelpInfo is not null) { result = originalHelpInfo.Copy(); // command's name can be changed using -Prefix while importing module.To give better user experience for // get-help (on par with get-command), it was decided to use the prefixed command name // for the help content. - if (result.FullHelp.Properties["Name"] != null) + if (result.FullHelp.Properties["Name"] is not null) { result.FullHelp.Properties.Remove("Name"); } result.FullHelp.Properties.Add(new PSNoteProperty("Name", cmdInfo.Name)); - if (result.FullHelp.Properties["Details"] != null && - result.FullHelp.Properties["Details"].Value != null) + if (result.FullHelp.Properties["Details"] is not null && + result.FullHelp.Properties["Details"].Value is not null) { // Note we are making a copy of the original instance and updating // it..This is to protect the help content of the original object. PSObject commandDetails = PSObject.AsPSObject( result.FullHelp.Properties["Details"].Value).Copy(); - if (commandDetails.Properties["Name"] != null) + if (commandDetails.Properties["Name"] is not null) { commandDetails.Properties.Remove("Name"); } @@ -1071,7 +1071,7 @@ internal override IEnumerable SearchHelp(HelpRequest helpRequest, bool HelpInfo helpInfo = GetHelpInfo(current, !decoratedSearch, searchOnlyContent); string helpName = GetHelpName(current); - if (helpInfo != null && !string.IsNullOrEmpty(helpName)) + if (helpInfo is not null && !string.IsNullOrEmpty(helpName)) { if (!SessionState.IsVisible(helpRequest.CommandOrigin, current)) { @@ -1128,7 +1128,7 @@ internal override IEnumerable SearchHelp(HelpRequest helpRequest, bool HelpInfo helpInfo = GetHelpInfo(current, !decoratedSearch, searchOnlyContent); string helpName = GetHelpName(current); - if (helpInfo != null && !string.IsNullOrEmpty(helpName)) + if (helpInfo is not null && !string.IsNullOrEmpty(helpName)) { if (set.Contains(helpName)) continue; diff --git a/src/System.Management.Automation/help/DefaultCommandHelpObjectBuilder.cs b/src/System.Management.Automation/help/DefaultCommandHelpObjectBuilder.cs index cde4b093d1c..389605ee34b 100644 --- a/src/System.Management.Automation/help/DefaultCommandHelpObjectBuilder.cs +++ b/src/System.Management.Automation/help/DefaultCommandHelpObjectBuilder.cs @@ -28,7 +28,7 @@ public int Compare(object x, object y) CommandParameterInfo a = x as CommandParameterInfo; CommandParameterInfo b = y as CommandParameterInfo; - Debug.Assert(a != null && b != null); + Debug.Assert(a is not null && b is not null); return (a.Position - b.Position); } @@ -66,7 +66,7 @@ internal static PSObject GetPSObjectFromCmdletInfo(CommandInfo input) if (commandInfo is CmdletInfo cmdletInfo) { bool common = false; - if (cmdletInfo.Parameters != null) + if (cmdletInfo.Parameters is not null) { common = HasCommonParameters(cmdletInfo.Parameters); } @@ -287,14 +287,14 @@ private static void AddSyntaxParametersProperties(PSObject obj, IEnumerable parameter in parameters) { @@ -464,7 +464,7 @@ private static void AddParameterProperties(PSObject obj, string name, Collection obj.Properties.Add(new PSNoteProperty("parameterSetName", sb.ToString())); } - if (paramAttribute.HelpMessage != null) + if (paramAttribute.HelpMessage is not null) { StringBuilder sb = new StringBuilder(); @@ -546,7 +546,7 @@ private static void AddParameterValueProperties(PSObject obj, Type parameterType { PSObject mshObject; - if (parameterType != null) + if (parameterType is not null) { Type type = Nullable.GetUnderlyingType(parameterType) ?? parameterType; var parameterTypeString = CommandParameterSetInfo.GetParameterTypeString(parameterType, attributes); @@ -574,7 +574,7 @@ internal static void AddInputTypesProperties(PSObject obj, Dictionary inputs = new Collection(); - if (parameters != null) + if (parameters is not null) { foreach (KeyValuePair parameter in parameters) { @@ -683,7 +683,7 @@ private static void AddAliasesProperties(PSObject obj, string name, ExecutionCon bool found = false; - if (context != null) + if (context is not null) { foreach (string alias in context.SessionState.Internal.GetAliasesByCommandName(name)) { @@ -738,21 +738,21 @@ internal static void AddRelatedLinksProperties(PSObject obj, string relatedLink) // check if obj already has relatedLinks property PSNoteProperty relatedLinksPO = obj.Properties["relatedLinks"] as PSNoteProperty; - if ((relatedLinksPO != null) && (relatedLinksPO.Value != null)) + if ((relatedLinksPO is not null) && (relatedLinksPO.Value is not null)) { PSObject relatedLinksValue = PSObject.AsPSObject(relatedLinksPO.Value); PSNoteProperty navigationLinkPO = relatedLinksValue.Properties["navigationLink"] as PSNoteProperty; - if ((navigationLinkPO != null) && (navigationLinkPO.Value != null)) + if ((navigationLinkPO is not null) && (navigationLinkPO.Value is not null)) { PSObject navigationLinkValue = navigationLinkPO.Value as PSObject; - if (navigationLinkValue != null) + if (navigationLinkValue is not null) { navigationLinkValues.Add(navigationLinkValue); } else { PSObject[] navigationLinkValueArray = navigationLinkPO.Value as PSObject[]; - if (navigationLinkValueArray != null) + if (navigationLinkValueArray is not null) { foreach (var psObject in navigationLinkValueArray) { @@ -786,7 +786,7 @@ private static Collection GetParameterAttribute(Collection GetValidateSetAttribute(Collecti { ValidateSetAttribute validateSetAttribute = (object)attribute as ValidateSetAttribute; - if (validateSetAttribute != null) + if (validateSetAttribute is not null) { validateSetAttributes.Add(validateSetAttribute); } @@ -824,7 +824,7 @@ private static Collection GetValidateSetAttribute(Collecti /// Pipeline input type. private static string GetPipelineInputString(ParameterAttribute paramAttrib) { - Debug.Assert(paramAttrib != null); + Debug.Assert(paramAttrib is not null); ArrayList values = new ArrayList(); diff --git a/src/System.Management.Automation/help/DscResourceHelpProvider.cs b/src/System.Management.Automation/help/DscResourceHelpProvider.cs index c2fd800b1e7..4bf56c8ed0e 100644 --- a/src/System.Management.Automation/help/DscResourceHelpProvider.cs +++ b/src/System.Management.Automation/help/DscResourceHelpProvider.cs @@ -66,7 +66,7 @@ internal override HelpCategory HelpCategory /// internal override IEnumerable SearchHelp(HelpRequest helpRequest, bool searchOnlyContent) { - Debug.Assert(helpRequest != null, "helpRequest cannot be null."); + Debug.Assert(helpRequest is not null, "helpRequest cannot be null."); string target = helpRequest.Target; Collection patternList = new Collection(); @@ -86,7 +86,7 @@ internal override IEnumerable SearchHelp(HelpRequest helpRequest, bool foreach (var helpInfo in GetHelpInfo(searcher)) { - if (helpInfo != null) + if (helpInfo is not null) yield return helpInfo; } } @@ -99,7 +99,7 @@ internal override IEnumerable SearchHelp(HelpRequest helpRequest, bool /// Enumerable of HelpInfo objects. internal override IEnumerable ExactMatchHelp(HelpRequest helpRequest) { - Debug.Assert(helpRequest != null, "helpRequest cannot be null."); + Debug.Assert(helpRequest is not null, "helpRequest cannot be null."); if ((helpRequest.HelpCategory & Automation.HelpCategory.DscResource) == 0) { @@ -112,7 +112,7 @@ internal override IEnumerable ExactMatchHelp(HelpRequest helpRequest) foreach (var helpInfo in GetHelpInfo(searcher)) { - if (helpInfo != null) + if (helpInfo is not null) { yield return helpInfo; } @@ -135,7 +135,7 @@ private IEnumerable GetHelpInfo(DscResourceSearcher searcher) // for binary modules, current.Module is empty. // in such cases use the leaf folder of ParentPath as filename. - if (current.Module != null) + if (current.Module is not null) { moduleName = current.Module.Name; } @@ -156,7 +156,7 @@ private IEnumerable GetHelpInfo(DscResourceSearcher searcher) HelpInfo helpInfo = GetHelpInfoFromHelpFile(current, helpFileToFind, searchPaths, true, out helpFileName); - if (helpInfo != null) + if (helpInfo is not null) { yield return helpInfo; } @@ -203,8 +203,8 @@ internal static bool IsMamlHelp(string helpFile, XmlNode helpItemsNode) private HelpInfo GetHelpInfoFromHelpFile(DscResourceInfo resourceInfo, string helpFileToFind, Collection searchPaths, bool reportErrors, out string helpFile) { - Dbg.Assert(resourceInfo != null, "Caller should verify that resourceInfo != null"); - Dbg.Assert(helpFileToFind != null, "Caller should verify that helpFileToFind != null"); + Dbg.Assert(resourceInfo is not null, "Caller should verify that resourceInfo is not null"); + Dbg.Assert(helpFileToFind is not null, "Caller should verify that helpFileToFind is not null"); helpFile = MUIFileSearcher.LocateFile(helpFileToFind, searchPaths); @@ -237,7 +237,7 @@ private HelpInfo GetFromResourceHelpCache(string helpFileIdentifier, HelpCategor HelpInfo result = GetCache(helpFileIdentifier); - if (result != null) + if (result is not null) { MamlCommandHelpInfo original = (MamlCommandHelpInfo)result; result = original.Copy(helpCategory); @@ -278,10 +278,10 @@ private void LoadHelpFile(string helpFile, string helpFileIdentifier, string com e = invalidOperationException; } - if (e != null) + if (e is not null) s_tracer.WriteLine("Error occured in DscResourceHelpProvider {0}", e.Message); - if (reportErrors && (e != null)) + if (reportErrors && (e is not null)) { ReportHelpFileError(e, commandName, helpFile); } @@ -355,7 +355,7 @@ private void LoadHelpFile(string helpFile, string helpFileIdentifier) helpInfo = MamlCommandHelpInfo.Load(node, HelpCategory.DscResource); } - if (helpInfo != null) + if (helpInfo is not null) { this.HelpSystem.TraceErrors(helpInfo.Errors); AddCache(helpFileIdentifier, helpInfo); diff --git a/src/System.Management.Automation/help/HelpCategoryInvalidException.cs b/src/System.Management.Automation/help/HelpCategoryInvalidException.cs index 51df200583d..87e1616cb9f 100644 --- a/src/System.Management.Automation/help/HelpCategoryInvalidException.cs +++ b/src/System.Management.Automation/help/HelpCategoryInvalidException.cs @@ -43,7 +43,7 @@ public HelpCategoryInvalidException() : base() /// The name of help category that is invalid. /// The inner exception of this exception. public HelpCategoryInvalidException(string helpCategory, Exception innerException) : - base((innerException != null) ? innerException.Message : string.Empty, innerException) + base((innerException is not null) ? innerException.Message : string.Empty, innerException) { _helpCategory = helpCategory; CreateErrorRecord(); @@ -94,7 +94,7 @@ public override string Message { get { - if (_errorRecord != null) + if (_errorRecord is not null) { return _errorRecord.ToString(); } diff --git a/src/System.Management.Automation/help/HelpCommands.cs b/src/System.Management.Automation/help/HelpCommands.cs index 746f2afc163..65a422b694b 100644 --- a/src/System.Management.Automation/help/HelpCommands.cs +++ b/src/System.Management.Automation/help/HelpCommands.cs @@ -309,7 +309,7 @@ protected override void ProcessRecord() else { // write first help object only once. - if (firstHelpInfoObject != null) + if (firstHelpInfoObject is not null) { WriteObjectsOrShowOnlineHelp(firstHelpInfoObject, false); firstHelpInfoObject = null; @@ -404,7 +404,7 @@ private HelpCategory ToHelpCategory(string[] category, ref bool failed) /// If Detailed and Full are not specified, nothing is changed. private PSObject TransformView(PSObject originalHelpObject) { - Diagnostics.Assert(originalHelpObject != null, + Diagnostics.Assert(originalHelpObject is not null, "HelpObject should not be null"); if (_viewTokenToAdd == HelpView.Default) @@ -522,25 +522,25 @@ private void ValidateAndThrowIfError(HelpCategory cat) if ((cat & supportedCategories) == 0) { - if (Parameter != null) + if (Parameter is not null) { throw PSTraceSource.NewArgumentException("Parameter", HelpErrors.ParamNotSupported, "-Parameter"); } - if (Component != null) + if (Component is not null) { throw PSTraceSource.NewArgumentException("Component", HelpErrors.ParamNotSupported, "-Component"); } - if (Role != null) + if (Role is not null) { throw PSTraceSource.NewArgumentException("Role", HelpErrors.ParamNotSupported, "-Role"); } - if (Functionality != null) + if (Functionality is not null) { throw PSTraceSource.NewArgumentException("Functionality", HelpErrors.ParamNotSupported, "-Functionality"); @@ -555,7 +555,7 @@ private void ValidateAndThrowIfError(HelpCategory cat) /// private void WriteObjectsOrShowOnlineHelp(HelpInfo helpInfo, bool showFullHelp) { - if (helpInfo != null) + if (helpInfo is not null) { // online help can be showed only if showFullHelp is true.. // showFullHelp will be false when the help tries to display multiple help topics.. @@ -566,7 +566,7 @@ private void WriteObjectsOrShowOnlineHelp(HelpInfo helpInfo, bool showFullHelp) // show online help s_tracer.WriteLine("Preparing to show help online."); Uri onlineUri = helpInfo.GetUriForOnlineHelp(); - if (onlineUri != null) + if (onlineUri is not null) { onlineUriFound = true; LaunchOnlineHelp(onlineUri); @@ -589,7 +589,7 @@ private void WriteObjectsOrShowOnlineHelp(HelpInfo helpInfo, bool showFullHelp) // show inline help if (showFullHelp) { - if (Parameter != null) + if (Parameter is not null) { GetAndWriteParameterInfo(helpInfo); } @@ -602,7 +602,7 @@ private void WriteObjectsOrShowOnlineHelp(HelpInfo helpInfo, bool showFullHelp) } else { - if (Parameter != null) + if (Parameter is not null) { PSObject[] pInfos = GetParameterInfo(helpInfo); @@ -625,7 +625,7 @@ private void WriteObjectsOrShowOnlineHelp(HelpInfo helpInfo, bool showFullHelp) /// private void LaunchOnlineHelp(Uri uriToLaunch) { - Diagnostics.Assert(uriToLaunch != null, "uriToLaunch should not be null"); + Diagnostics.Assert(uriToLaunch is not null, "uriToLaunch should not be null"); if (!uriToLaunch.Scheme.Equals("http", StringComparison.OrdinalIgnoreCase) && !uriToLaunch.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase)) @@ -672,7 +672,7 @@ private void LaunchOnlineHelp(Uri uriToLaunch) exception = we; } - if (exception != null) + if (exception is not null) { if (wrapCaughtException) throw PSTraceSource.NewInvalidOperationException(exception, HelpErrors.CannotLaunchURI, uriToLaunch.OriginalString); @@ -741,7 +741,7 @@ private static bool DoesCurrentRunspaceIncludeCoreHelpCmdlet() { InitialSessionState iss = System.Management.Automation.Runspaces.Runspace.DefaultRunspace.InitialSessionState; - if (iss != null) + if (iss is not null) { IEnumerable publicGetHelpEntries = iss .Commands["Get-Help"] @@ -754,7 +754,7 @@ private static bool DoesCurrentRunspaceIncludeCoreHelpCmdlet() foreach (SessionStateCommandEntry getHelpEntry in publicGetHelpEntries) { SessionStateCmdletEntry getHelpCmdlet = getHelpEntry as SessionStateCmdletEntry; - if ((getHelpCmdlet != null) && (getHelpCmdlet.ImplementingType.Equals(typeof(GetHelpCommand)))) + if ((getHelpCmdlet is not null) && (getHelpCmdlet.ImplementingType.Equals(typeof(GetHelpCommand)))) { return true; } @@ -804,8 +804,8 @@ public static string GetHelpUri(PSObject commandInfoPSObject) } AliasInfo aliasInfo = cmdInfo as AliasInfo; - if ((aliasInfo != null) && - (aliasInfo.ExternalCommandMetadata != null) && + if ((aliasInfo is not null) && + (aliasInfo.ExternalCommandMetadata is not null) && (!string.IsNullOrEmpty(aliasInfo.ExternalCommandMetadata.HelpUri))) { return aliasInfo.ExternalCommandMetadata.HelpUri; @@ -824,7 +824,7 @@ public static string GetHelpUri(PSObject commandInfoPSObject) // Win8: 651300 if core get-help is present in the runspace (and it is the only get-help command), use // help system directly and avoid perf penalty. var currentContext = System.Management.Automation.Runspaces.LocalPipeline.GetExecutionContextFromTLS(); - if ((currentContext != null) && (currentContext.HelpSystem != null)) + if ((currentContext is not null) && (currentContext.HelpSystem is not null)) { HelpRequest helpRequest = new HelpRequest(cmdName, cmdInfo.HelpCategory); helpRequest.ProviderContext = new ProviderContext( @@ -835,7 +835,7 @@ public static string GetHelpUri(PSObject commandInfoPSObject) foreach ( Uri result in currentContext.HelpSystem.ExactMatchHelp(helpRequest).Select( - helpInfo => helpInfo.GetUriForOnlineHelp()).Where(result => result != null)) + helpInfo => helpInfo.GetUriForOnlineHelp()).Where(result => result is not null)) { return result.OriginalString; } @@ -857,7 +857,7 @@ Uri result in { Collection helpInfos = getHelpPS.Invoke(); - if (helpInfos != null) + if (helpInfos is not null) { for (int index = 0; index < helpInfos.Count; index++) { @@ -865,7 +865,7 @@ Uri result in if (LanguagePrimitives.TryConvertTo(helpInfos[index], out helpInfo)) { Uri result = helpInfo.GetUriForOnlineHelp(); - if (result != null) + if (result is not null) { return result.OriginalString; } @@ -873,7 +873,7 @@ Uri result in else { Uri result = BaseCommandHelpInfo.GetUriFromCommandPSObject(helpInfos[index]); - return (result != null) ? result.OriginalString : string.Empty; + return (result is not null) ? result.OriginalString : string.Empty; } } } diff --git a/src/System.Management.Automation/help/HelpCommentsParser.cs b/src/System.Management.Automation/help/HelpCommentsParser.cs index 0f43aedc44b..1eb53309cc2 100644 --- a/src/System.Management.Automation/help/HelpCommentsParser.cs +++ b/src/System.Management.Automation/help/HelpCommentsParser.cs @@ -34,7 +34,7 @@ private HelpCommentsParser(List parameterDescriptions) private HelpCommentsParser(CommandInfo commandInfo, List parameterDescriptions) { FunctionInfo fi = commandInfo as FunctionInfo; - if (fi != null) + if (fi is not null) { _scriptBlock = fi.ScriptBlock; _commandName = fi.Name; @@ -42,7 +42,7 @@ private HelpCommentsParser(CommandInfo commandInfo, List parameterDescri else { ExternalScriptInfo si = commandInfo as ExternalScriptInfo; - if (si != null) + if (si is not null) { _scriptBlock = si.ScriptBlock; _commandName = si.Path; @@ -279,7 +279,7 @@ internal XmlDocument BuildXmlFromComments() parameterSetData = parameter.GetParameterSetData(1u << i++); } - if (parameterSetData != null) + if (parameterSetData is not null) { isMandatory = parameterSetData.IsMandatory; valueFromPipeline = parameterSetData.ValueFromPipeline; @@ -293,7 +293,7 @@ internal XmlDocument BuildXmlFromComments() string defaultValueStr = string.Empty; object defaultValue = null; var defaultValueAttribute = compiledAttributes.OfType().FirstOrDefault(); - if (defaultValueAttribute != null) + if (defaultValueAttribute is not null) { defaultValueStr = defaultValueAttribute.Help; if (string.IsNullOrEmpty(defaultValueStr)) @@ -314,11 +314,11 @@ internal XmlDocument BuildXmlFromComments() } var wrapper = defaultValue as Compiler.DefaultValueExpressionWrapper; - if (wrapper != null) + if (wrapper is not null) { defaultValueStr = wrapper.Expression.Extent.Text; } - else if (defaultValue != null) + else if (defaultValue is not null) { defaultValueStr = PSObject.ToStringParser(null, defaultValue); } @@ -426,7 +426,7 @@ internal XmlDocument BuildXmlFromComments() outputs = _scriptBlock.OutputType; } - if (outputs != null) + if (outputs is not null) { XmlElement returnValues = _doc.CreateElement("command:returnValues", commandURI); foreach (object output in outputs) @@ -649,7 +649,7 @@ internal string GetHelpFile(CommandInfo commandInfo) { helpFileToLoad = Path.Combine(Path.GetDirectoryName(scriptFile), _sections.MamlHelpFile); } - else if (commandInfo.Module != null) + else if (commandInfo.Module is not null) { helpFileToLoad = Path.Combine(Path.GetDirectoryName(commandInfo.Module.Path), _sections.MamlHelpFile); } @@ -839,7 +839,7 @@ internal static HelpInfo CreateFromComments(ExecutionContext context, HelpCommentsParser helpCommentsParser = new HelpCommentsParser(commandInfo, parameterDescriptions); helpCommentsParser.AnalyzeCommentBlock(comments); - if (helpCommentsParser._sections.Links != null && helpCommentsParser._sections.Links.Count != 0) + if (helpCommentsParser._sections.Links is not null && helpCommentsParser._sections.Links.Count != 0) { helpUriFromDotLink = helpCommentsParser._sections.Links[0]; } @@ -866,7 +866,7 @@ internal static HelpInfo CreateFromComments(ExecutionContext context, CommandInf if (!dontSearchOnRemoteComputer) { RemoteHelpInfo remoteHelpInfo = helpCommentsParser.GetRemoteHelpInfo(context, commandInfo); - if (remoteHelpInfo != null) + if (remoteHelpInfo is not null) { // Add HelpUri if necessary if (remoteHelpInfo.GetUriForOnlineHelp() is null) @@ -882,7 +882,7 @@ internal static HelpInfo CreateFromComments(ExecutionContext context, CommandInf XmlDocument doc = helpCommentsParser.BuildXmlFromComments(); HelpCategory helpCategory = commandInfo.HelpCategory; MamlCommandHelpInfo localHelpInfo = MamlCommandHelpInfo.Load(doc.DocumentElement, helpCategory); - if (localHelpInfo != null) + if (localHelpInfo is not null) { helpCommentsParser.SetAdditionalData(localHelpInfo); @@ -1056,7 +1056,7 @@ private static List GetParameterComments(Language.Token[] tokens, IParam var firstToken = FirstTokenInExtent(tokens, parameter.Extent, startIndex); var comments = GetPrecedingCommentBlock(tokens, firstToken, CommentBlockProximity); - if (comments != null) + if (comments is not null) { foreach (var comment in comments) { @@ -1075,7 +1075,7 @@ private static List GetParameterComments(Language.Token[] tokens, IParam lastToken += 1; comments = GetCommentBlock(tokens, ref lastToken); - if (comments != null) + if (comments is not null) { foreach (var comment in comments) { @@ -1093,12 +1093,12 @@ private static List GetParameterComments(Language.Token[] tokens, IParam internal static Tuple, List> GetHelpCommentTokens(IParameterMetadataProvider ipmp, Dictionary scriptBlockTokenCache) { - Diagnostics.Assert(scriptBlockTokenCache != null, "scriptBlockTokenCache cannot be null"); + Diagnostics.Assert(scriptBlockTokenCache is not null, "scriptBlockTokenCache cannot be null"); var ast = (Ast)ipmp; var rootAst = ast; Ast configAst = null; - while (rootAst.Parent != null) + while (rootAst.Parent is not null) { rootAst = rootAst.Parent; if (rootAst is ConfigurationDefinitionAst) @@ -1125,7 +1125,7 @@ private static List GetParameterComments(Language.Token[] tokens, IParam var funcDefnAst = ast as FunctionDefinitionAst; List commentBlock; - if (funcDefnAst != null || configAst != null) + if (funcDefnAst is not null || configAst is not null) { // The first comment block preceding the function or configuration keyword is a candidate help comment block. var funcOrConfigTokenIndex = @@ -1140,7 +1140,7 @@ private static List GetParameterComments(Language.Token[] tokens, IParam // comment block is behind function definition // we don't support it for configuration declaration as this style is rarely used - if (funcDefnAst != null) + if (funcDefnAst is not null) { startTokenIndex = FirstTokenInExtent(tokens, funcDefnAst.Body.Extent) + 1; diff --git a/src/System.Management.Automation/help/HelpFileHelpInfo.cs b/src/System.Management.Automation/help/HelpFileHelpInfo.cs index 09a65b0890a..d3c11ccc346 100644 --- a/src/System.Management.Automation/help/HelpFileHelpInfo.cs +++ b/src/System.Management.Automation/help/HelpFileHelpInfo.cs @@ -31,7 +31,7 @@ private HelpFileHelpInfo(string name, string text, string filename) // Take the 5th line as synopsis. This may not be true if // format of help file is changed later on. _synopsis = GetLine(text, 5); - if (_synopsis != null) + if (_synopsis is not null) { _synopsis = _synopsis.Trim(); } @@ -129,7 +129,7 @@ private static string GetLine(string text, int line) internal override bool MatchPatternInContent(WildcardPattern pattern) { - Diagnostics.Assert(pattern != null, "pattern cannot be null."); + Diagnostics.Assert(pattern is not null, "pattern cannot be null."); string helpContent = string.Empty; LanguagePrimitives.TryConvertTo(FullHelp, out helpContent); diff --git a/src/System.Management.Automation/help/HelpFileHelpProvider.cs b/src/System.Management.Automation/help/HelpFileHelpProvider.cs index 142664e002c..0991eeb6d8c 100644 --- a/src/System.Management.Automation/help/HelpFileHelpProvider.cs +++ b/src/System.Management.Automation/help/HelpFileHelpProvider.cs @@ -63,7 +63,7 @@ internal override IEnumerable ExactMatchHelp(HelpRequest helpRequest) string helpFileName = helpRequest.Target + ".help.txt"; Collection filesMatched = MUIFileSearcher.SearchFiles(helpFileName, GetExtendedSearchPaths()); - Diagnostics.Assert(filesMatched != null, "Files collection should not be null."); + Diagnostics.Assert(filesMatched is not null, "Files collection should not be null."); var matchedFilesToRemove = FilterToLatestModuleVersion(filesMatched); foreach (string file in filesMatched) @@ -90,7 +90,7 @@ internal override IEnumerable ExactMatchHelp(HelpRequest helpRequest) HelpInfo helpInfo = GetCache(file); - if (helpInfo != null) + if (helpInfo is not null) { countHelpInfosFound++; yield return helpInfo; @@ -126,7 +126,7 @@ private Collection FilterToLatestModuleVersion(Collection filesM GetModuleNameAndVersion(psModulePath, fileFullName, out moduleName, out moduleVersionFromPath); // Skip modules whose root we cannot determine or which do not have versions. - if (moduleVersionFromPath != null && moduleName != null) + if (moduleVersionFromPath is not null && moduleName is not null) { Tuple moduleVersion = null; Tuple key = new Tuple(moduleName, fileName); @@ -249,7 +249,7 @@ internal override IEnumerable SearchHelp(HelpRequest helpRequest, bool HelpFileHelpInfo helpInfo = GetCache(file) as HelpFileHelpInfo; - if (helpInfo != null) + if (helpInfo is not null) { if (searchOnlyContent) { @@ -314,7 +314,7 @@ private HelpInfo LoadHelpFile(string path) HelpInfo helpInfo = GetCache(path); - if (helpInfo != null) + if (helpInfo is not null) return helpInfo; string helpText = null; diff --git a/src/System.Management.Automation/help/HelpNotFoundException.cs b/src/System.Management.Automation/help/HelpNotFoundException.cs index f9ba44c386d..1a2580f8af5 100644 --- a/src/System.Management.Automation/help/HelpNotFoundException.cs +++ b/src/System.Management.Automation/help/HelpNotFoundException.cs @@ -43,7 +43,7 @@ public HelpNotFoundException() : base() /// The help topic for which help is not found. /// The inner exception. public HelpNotFoundException(string helpTopic, Exception innerException) : - base((innerException != null) ? innerException.Message : string.Empty, innerException) + base((innerException is not null) ? innerException.Message : string.Empty, innerException) { _helpTopic = helpTopic; CreateErrorRecord(); @@ -99,7 +99,7 @@ public override string Message { get { - if (_errorRecord != null) + if (_errorRecord is not null) { return _errorRecord.ToString(); } diff --git a/src/System.Management.Automation/help/HelpProvider.cs b/src/System.Management.Automation/help/HelpProvider.cs index 76ce3168432..7f3a3598d9e 100644 --- a/src/System.Management.Automation/help/HelpProvider.cs +++ b/src/System.Management.Automation/help/HelpProvider.cs @@ -239,7 +239,7 @@ internal Collection GetSearchPaths() { Collection searchPaths = this.HelpSystem.GetSearchPaths(); - Diagnostics.Assert(searchPaths != null, + Diagnostics.Assert(searchPaths is not null, "HelpSystem returned an null search path"); string defaultShellSearchPath = GetDefaultShellSearchPath(); diff --git a/src/System.Management.Automation/help/HelpProviderWithCache.cs b/src/System.Management.Automation/help/HelpProviderWithCache.cs index 99dc3fa7a19..82a85cd7b66 100644 --- a/src/System.Management.Automation/help/HelpProviderWithCache.cs +++ b/src/System.Management.Automation/help/HelpProviderWithCache.cs @@ -121,7 +121,7 @@ internal override IEnumerable SearchHelp(HelpRequest helpRequest, bool if (!this.CacheFullyLoaded) { IEnumerable result = DoSearchHelp(searchHelpRequest); - if (result != null) + if (result is not null) { foreach (HelpInfo helpInfoToReturn in result) { diff --git a/src/System.Management.Automation/help/HelpSystem.cs b/src/System.Management.Automation/help/HelpSystem.cs index c7dc9eb68f4..e8a8ed53ec8 100644 --- a/src/System.Management.Automation/help/HelpSystem.cs +++ b/src/System.Management.Automation/help/HelpSystem.cs @@ -247,7 +247,7 @@ internal bool VerboseHelpErrors internal Collection GetSearchPaths() { // return the cache if already present. - if (_searchPaths != null) + if (_searchPaths is not null) { return _searchPaths; } @@ -255,7 +255,7 @@ internal Collection GetSearchPaths() _searchPaths = new Collection(); // add loaded modules paths to the search path - if (ExecutionContext.Modules != null) + if (ExecutionContext.Modules is not null) { foreach (PSModuleInfo loadedModule in ExecutionContext.Modules.ModuleTable.Values) { @@ -294,7 +294,7 @@ private IEnumerable DoGetHelp(HelpRequest helpRequest) { HelpInfo helpInfo = GetDefaultHelp(); - if (helpInfo != null) + if (helpInfo is not null) { yield return helpInfo; } @@ -617,7 +617,7 @@ private void InitializeHelpProviders() { HelpProvider helpProvider = GetHelpProvider(_providerInfos[i]); - if (helpProvider != null) + if (helpProvider is not null) { helpProvider.Initialize(this._executionContext); _helpProviders.Add(helpProvider); @@ -640,7 +640,7 @@ private HelpProvider GetHelpProvider(HelpProviderInfo providerInfo) try { - if (providerAssembly != null) + if (providerAssembly is not null) { HelpProvider helpProvider = (HelpProvider)providerAssembly.CreateInstance(providerInfo.ClassName, @@ -658,7 +658,7 @@ private HelpProvider GetHelpProvider(HelpProviderInfo providerInfo) catch (TargetInvocationException e) { System.Console.WriteLine(e.Message); - if (e.InnerException != null) + if (e.InnerException is not null) { System.Console.WriteLine(e.InnerException.Message); System.Console.WriteLine(e.InnerException.StackTrace); diff --git a/src/System.Management.Automation/help/MUIFileSearcher.cs b/src/System.Management.Automation/help/MUIFileSearcher.cs index 3a867e20c5d..3330809a254 100644 --- a/src/System.Management.Automation/help/MUIFileSearcher.cs +++ b/src/System.Management.Automation/help/MUIFileSearcher.cs @@ -133,7 +133,7 @@ private string[] GetFiles(string path, string pattern) break; } - if (wildcardPattern != null) + if (wildcardPattern is not null) { string fileName = Path.GetFileName(filePath); if (wildcardPattern.IsMatch(fileName)) @@ -208,7 +208,7 @@ private void SearchForFiles(string pattern, string directory) List cultureNameList = new List(); CultureInfo culture = CultureInfo.CurrentUICulture; - while (culture != null && !string.IsNullOrEmpty(culture.Name)) + while (culture is not null && !string.IsNullOrEmpty(culture.Name)) { cultureNameList.Add(culture.Name); culture = culture.Parent; @@ -275,7 +275,7 @@ private static Collection NormalizeSearchPaths(string target, Collection } // step 2: add directories specified in to search path. - if (searchPaths != null) + if (searchPaths is not null) { foreach (string directory in searchPaths) { @@ -288,7 +288,7 @@ private static Collection NormalizeSearchPaths(string target, Collection // step 3: locate the file in the default PowerShell installation directory. string defaultPSPath = Utils.GetApplicationBase(Utils.DefaultPowerShellShellID); - if (defaultPSPath != null && + if (defaultPSPath is not null && !result.Contains(defaultPSPath) && Directory.Exists(defaultPSPath)) { diff --git a/src/System.Management.Automation/help/MamlClassHelpInfo.cs b/src/System.Management.Automation/help/MamlClassHelpInfo.cs index 002eecb3bfe..2793ced3f67 100644 --- a/src/System.Management.Automation/help/MamlClassHelpInfo.cs +++ b/src/System.Management.Automation/help/MamlClassHelpInfo.cs @@ -97,7 +97,7 @@ internal override string Name string tempName = string.Empty; var title = _fullHelpObject.Properties["title"]; - if (title != null && title.Value != null) + if (title is not null && title.Value is not null) { tempName = title.Value.ToString(); } @@ -113,7 +113,7 @@ internal override string Synopsis string tempSynopsis = string.Empty; var intro = _fullHelpObject.Properties["introduction"]; - if (intro != null && intro.Value != null) + if (intro is not null && intro.Value is not null) { tempSynopsis = intro.Value.ToString(); } diff --git a/src/System.Management.Automation/help/MamlCommandHelpInfo.cs b/src/System.Management.Automation/help/MamlCommandHelpInfo.cs index 12e1469e7c9..c378a843a91 100644 --- a/src/System.Management.Automation/help/MamlCommandHelpInfo.cs +++ b/src/System.Management.Automation/help/MamlCommandHelpInfo.cs @@ -30,17 +30,17 @@ internal MamlCommandHelpInfo(PSObject helpObject, HelpCategory helpCategory) this.AddCommonHelpProperties(); // set user defined data - if (helpObject.Properties["Component"] != null) + if (helpObject.Properties["Component"] is not null) { _component = helpObject.Properties["Component"].Value as string; } - if (helpObject.Properties["Role"] != null) + if (helpObject.Properties["Role"] is not null) { _role = helpObject.Properties["Role"].Value as string; } - if (helpObject.Properties["Functionality"] != null) + if (helpObject.Properties["Functionality"] is not null) { _functionality = helpObject.Properties["Functionality"].Value as string; } @@ -293,10 +293,10 @@ internal MamlCommandHelpInfo MergeProviderSpecificHelp(PSObject cmdletHelp, PSOb // to avoid _fullHelpObject being get terminated. result._fullHelpObject = this._fullHelpObject.Copy(); - if (cmdletHelp != null) + if (cmdletHelp is not null) result._fullHelpObject.Properties.Add(new PSNoteProperty("PS_Cmdlet", cmdletHelp)); - if (dynamicParameterHelp != null) + if (dynamicParameterHelp is not null) result._fullHelpObject.Properties.Add(new PSNoteProperty("PS_DynamicParameters", dynamicParameterHelp)); return result; @@ -397,7 +397,7 @@ private string ExtractText(PSObject psObject) /// internal override bool MatchPatternInContent(WildcardPattern pattern) { - System.Management.Automation.Diagnostics.Assert(pattern != null, "pattern cannot be null"); + System.Management.Automation.Diagnostics.Assert(pattern is not null, "pattern cannot be null"); string synopsis = Synopsis; if ((!string.IsNullOrEmpty(synopsis)) && (pattern.IsMatch(synopsis))) diff --git a/src/System.Management.Automation/help/MamlNode.cs b/src/System.Management.Automation/help/MamlNode.cs index 872543d2e4c..8449b3699f9 100644 --- a/src/System.Management.Automation/help/MamlNode.cs +++ b/src/System.Management.Automation/help/MamlNode.cs @@ -212,7 +212,7 @@ private PSObject GetPSObject(XmlNode xmlNode) // the ouput is readable. This is done only for complex nodes. mshObject.TypeNames.Clear(); - if (xmlNode.Attributes["type"] != null) + if (xmlNode.Attributes["type"] is not null) { if (string.Equals(xmlNode.Attributes["type"].Value, "field", StringComparison.OrdinalIgnoreCase)) mshObject.TypeNames.Add("MamlPSClassHelpInfo#field"); @@ -223,7 +223,7 @@ private PSObject GetPSObject(XmlNode xmlNode) mshObject.TypeNames.Add("MamlCommandHelpInfo#" + xmlNode.LocalName); } - if (xmlNode.Attributes != null) + if (xmlNode.Attributes is not null) { foreach (XmlNode attribute in xmlNode.Attributes) { @@ -303,7 +303,7 @@ private Hashtable GetInsideProperties(XmlNode xmlNode) if (xmlNode is null) return properties; - if (xmlNode.ChildNodes != null) + if (xmlNode.ChildNodes is not null) { foreach (XmlNode childNode in xmlNode.ChildNodes) { @@ -327,7 +327,7 @@ private void RemoveUnsupportedNodes(XmlNode xmlNode) // We want to modify only children.. // The current node is taken care by the callee.. XmlNode childNode = xmlNode.FirstChild; - while (childNode != null) + while (childNode is not null) { // We dont want Comments..so remove.. if (childNode.NodeType == XmlNodeType.Comment) @@ -605,7 +605,7 @@ private PSObject[] GetMamlFormattingPSObjects(XmlNode xmlNode) { ++count; PSObject paraPSObject = GetParaPSObject(childNode, count != paraNodes, trim: trim); - if (paraPSObject != null) + if (paraPSObject is not null) mshObjects.Add(paraPSObject); continue; } @@ -828,7 +828,7 @@ private ArrayList GetListPSObjects(XmlNode xmlNode) { PSObject listItemPSObject = GetListItemPSObject(childNode, ordered, ref index); - if (listItemPSObject != null) + if (listItemPSObject is not null) mshObjects.Add(listItemPSObject); continue; @@ -956,7 +956,7 @@ private ArrayList GetDefinitionListPSObjects(XmlNode xmlNode) { PSObject definitionListItemPSObject = GetDefinitionListItemPSObject(childNode); - if (definitionListItemPSObject != null) + if (definitionListItemPSObject is not null) mshObjects.Add(definitionListItemPSObject); continue; diff --git a/src/System.Management.Automation/help/MamlUtil.cs b/src/System.Management.Automation/help/MamlUtil.cs index 36c8199bcab..177c76992c0 100644 --- a/src/System.Management.Automation/help/MamlUtil.cs +++ b/src/System.Management.Automation/help/MamlUtil.cs @@ -56,7 +56,7 @@ internal static void AddCommonProperties(PSObject maml1, PSObject maml2) if (maml1.Properties["PSSnapIn"] is null) { PSPropertyInfo snapInProperty = maml2.Properties["PSSnapIn"]; - if (snapInProperty != null) + if (snapInProperty is not null) { maml1.Properties.Add(new PSNoteProperty("PSSnapIn", snapInProperty.Value)); } @@ -65,7 +65,7 @@ internal static void AddCommonProperties(PSObject maml1, PSObject maml2) if (maml1.Properties["ModuleName"] is null) { PSPropertyInfo moduleNameProperty = maml2.Properties["ModuleName"]; - if (moduleNameProperty != null) + if (moduleNameProperty is not null) { maml1.Properties.Add(new PSNoteProperty("ModuleName", moduleNameProperty.Value)); } @@ -103,7 +103,7 @@ internal static void OverrideParameters(PSObject maml1, PSObject maml2) // For maml2: Add as collection or single item. No-op if PSPropertyInfo propertyInfo2 = GetPropertyInfo(maml2, parametersPath); var array = propertyInfo2.Value as Array; - if (array != null) + if (array is not null) { maml2items.AddRange(array as IEnumerable); } @@ -118,7 +118,7 @@ internal static void OverrideParameters(PSObject maml1, PSObject maml2) PSPropertyInfo propertyInfo1 = GetPropertyInfo(maml1, parametersPath); List maml1items = new List(); array = propertyInfo1.Value as Array; - if (array != null) + if (array is not null) { maml1items.AddRange(array as IEnumerable); } @@ -134,7 +134,7 @@ internal static void OverrideParameters(PSObject maml1, PSObject maml2) string param2Name = string.Empty; PSPropertyInfo m2propertyInfo = m2paramObj.Properties["Name"]; - if (m2propertyInfo != null) + if (m2propertyInfo is not null) { if (!LanguagePrimitives.TryConvertTo(m2propertyInfo.Value, out param2Name)) { @@ -148,7 +148,7 @@ internal static void OverrideParameters(PSObject maml1, PSObject maml2) string param1Name = string.Empty; PSPropertyInfo m1PropertyInfo = m1ParamObj.Properties["Name"]; - if (m1PropertyInfo != null) + if (m1PropertyInfo is not null) { if (!LanguagePrimitives.TryConvertTo(m1PropertyInfo.Value, out param1Name)) { @@ -240,10 +240,10 @@ internal static void PrependPropertyValue(PSObject maml1, PSObject maml2, string // For maml2: Add as collection or single item. No-op if PSPropertyInfo propertyInfo2 = GetPropertyInfo(maml2, path); - if (propertyInfo2 != null) + if (propertyInfo2 is not null) { var array = propertyInfo2.Value as Array; - if (array != null) + if (array is not null) { items.AddRange(propertyInfo2.Value as IEnumerable); } @@ -258,12 +258,12 @@ internal static void PrependPropertyValue(PSObject maml1, PSObject maml2, string // For maml1: Add as collection or single item. Do nothing if null or some other type. PSPropertyInfo propertyInfo1 = GetPropertyInfo(maml1, path); - if (propertyInfo1 != null) + if (propertyInfo1 is not null) { if (!shouldOverride) { var array = propertyInfo1.Value as Array; - if (array != null) + if (array is not null) { items.AddRange(propertyInfo1.Value as IEnumerable); } diff --git a/src/System.Management.Automation/help/PSClassHelpProvider.cs b/src/System.Management.Automation/help/PSClassHelpProvider.cs index 1863644e21e..1f78752bb6c 100644 --- a/src/System.Management.Automation/help/PSClassHelpProvider.cs +++ b/src/System.Management.Automation/help/PSClassHelpProvider.cs @@ -66,7 +66,7 @@ internal override HelpCategory HelpCategory /// internal override IEnumerable SearchHelp(HelpRequest helpRequest, bool searchOnlyContent) { - Debug.Assert(helpRequest != null, "helpRequest cannot be null."); + Debug.Assert(helpRequest is not null, "helpRequest cannot be null."); string target = helpRequest.Target; Collection patternList = new Collection(); @@ -88,7 +88,7 @@ internal override IEnumerable SearchHelp(HelpRequest helpRequest, bool foreach (var helpInfo in GetHelpInfo(searcher)) { - if (helpInfo != null) + if (helpInfo is not null) yield return helpInfo; } } @@ -101,7 +101,7 @@ internal override IEnumerable SearchHelp(HelpRequest helpRequest, bool /// Enumerable of HelpInfo objects. internal override IEnumerable ExactMatchHelp(HelpRequest helpRequest) { - Debug.Assert(helpRequest != null, "helpRequest cannot be null."); + Debug.Assert(helpRequest is not null, "helpRequest cannot be null."); if ((helpRequest.HelpCategory & Automation.HelpCategory.Class) == 0) { @@ -115,7 +115,7 @@ internal override IEnumerable ExactMatchHelp(HelpRequest helpRequest) foreach (var helpInfo in GetHelpInfo(searcher)) { - if (helpInfo != null) + if (helpInfo is not null) { yield return helpInfo; } @@ -161,7 +161,7 @@ private IEnumerable GetHelpInfo(PSClassSearcher searcher) HelpInfo helpInfo = GetHelpInfoFromHelpFile(current, helpFileToFind, searchPaths, true, out helpFileName); - if (helpInfo != null) + if (helpInfo is not null) { yield return helpInfo; } @@ -208,8 +208,8 @@ internal static bool IsMamlHelp(string helpFile, XmlNode helpItemsNode) private HelpInfo GetHelpInfoFromHelpFile(PSClassInfo classInfo, string helpFileToFind, Collection searchPaths, bool reportErrors, out string helpFile) { - Dbg.Assert(classInfo != null, "Caller should verify that classInfo != null"); - Dbg.Assert(helpFileToFind != null, "Caller should verify that helpFileToFind != null"); + Dbg.Assert(classInfo is not null, "Caller should verify that classInfo is not null"); + Dbg.Assert(helpFileToFind is not null, "Caller should verify that helpFileToFind is not null"); helpFile = MUIFileSearcher.LocateFile(helpFileToFind, searchPaths); @@ -242,7 +242,7 @@ private HelpInfo GetFromPSClassHelpCache(string helpFileIdentifier, HelpCategory HelpInfo result = GetCache(helpFileIdentifier); - if (result != null) + if (result is not null) { MamlClassHelpInfo original = (MamlClassHelpInfo)result; result = original.Copy(helpCategory); @@ -283,10 +283,10 @@ private void LoadHelpFile(string helpFile, string helpFileIdentifier, string com e = invalidOperationException; } - if (e != null) + if (e is not null) s_tracer.WriteLine("Error occured in PSClassHelpProvider {0}", e.Message); - if (reportErrors && (e != null)) + if (reportErrors && (e is not null)) { ReportHelpFileError(e, commandName, helpFile); } @@ -360,7 +360,7 @@ private void LoadHelpFile(string helpFile, string helpFileIdentifier) helpInfo = MamlClassHelpInfo.Load(node, HelpCategory.Class); } - if (helpInfo != null) + if (helpInfo is not null) { this.HelpSystem.TraceErrors(helpInfo.Errors); AddCache(helpFileIdentifier, helpInfo); diff --git a/src/System.Management.Automation/help/ProviderCommandHelpInfo.cs b/src/System.Management.Automation/help/ProviderCommandHelpInfo.cs index b95ade5141c..226748e3369 100644 --- a/src/System.Management.Automation/help/ProviderCommandHelpInfo.cs +++ b/src/System.Management.Automation/help/ProviderCommandHelpInfo.cs @@ -20,8 +20,8 @@ internal class ProviderCommandHelpInfo : HelpInfo /// internal ProviderCommandHelpInfo(HelpInfo genericHelpInfo, ProviderContext providerContext) { - Dbg.Assert(genericHelpInfo != null, "Expected genericHelpInfo != null"); - Dbg.Assert(providerContext != null, "Expected providerContext != null"); + Dbg.Assert(genericHelpInfo is not null, "Expected genericHelpInfo is not null"); + Dbg.Assert(providerContext is not null, "Expected providerContext is not null"); // This should be set to None to prevent infinite forwarding. this.ForwardHelpCategory = HelpCategory.None; diff --git a/src/System.Management.Automation/help/ProviderContext.cs b/src/System.Management.Automation/help/ProviderContext.cs index 86fc8a6c895..925d5122f06 100644 --- a/src/System.Management.Automation/help/ProviderContext.cs +++ b/src/System.Management.Automation/help/ProviderContext.cs @@ -40,7 +40,7 @@ internal ProviderContext( ExecutionContext executionContext, PathIntrinsics pathIntrinsics) { - Dbg.Assert(executionContext != null, "ExecutionContext cannot be null."); + Dbg.Assert(executionContext is not null, "ExecutionContext cannot be null."); _requestedPath = requestedPath; _executionContext = executionContext; _pathIntrinsics = pathIntrinsics; @@ -117,7 +117,7 @@ internal MamlCommandHelpInfo GetProviderSpecificHelpInfo(string helpItemName) } bool isJEASession = false; - if (this._executionContext.InitialSessionState != null && this._executionContext.InitialSessionState.Providers != null && providerInfo != null) + if (this._executionContext.InitialSessionState is not null && this._executionContext.InitialSessionState.Providers is not null && providerInfo is not null) { foreach ( Runspaces.SessionStateProviderEntry sessionStateProvider in diff --git a/src/System.Management.Automation/help/ProviderHelpInfo.cs b/src/System.Management.Automation/help/ProviderHelpInfo.cs index 48d05a35ea3..0ed80339d22 100644 --- a/src/System.Management.Automation/help/ProviderHelpInfo.cs +++ b/src/System.Management.Automation/help/ProviderHelpInfo.cs @@ -162,7 +162,7 @@ internal override PSObject FullHelp /// internal override bool MatchPatternInContent(WildcardPattern pattern) { - Diagnostics.Assert(pattern != null, "pattern cannot be null"); + Diagnostics.Assert(pattern is not null, "pattern cannot be null"); string synopsis = Synopsis; string detailedDescription = DetailedDescription; @@ -211,7 +211,7 @@ internal PSObject GetCmdletHelp(string cmdletName) /// private void LoadCmdletHelps() { - if (_cmdletHelps != null) + if (_cmdletHelps is not null) return; if (_fullHelpObject is null) @@ -279,7 +279,7 @@ internal PSObject[] GetDynamicParameterHelp(string[] parameters) { PSObject entry = (PSObject)_dynamicParameterHelps[parameters[i].ToLower()]; - if (entry != null) + if (entry is not null) result.Add(entry); } @@ -292,7 +292,7 @@ internal PSObject[] GetDynamicParameterHelp(string[] parameters) /// private void LoadDynamicParameterHelps() { - if (_dynamicParameterHelps != null) + if (_dynamicParameterHelps is not null) return; if (_fullHelpObject is null) diff --git a/src/System.Management.Automation/help/ProviderHelpProvider.cs b/src/System.Management.Automation/help/ProviderHelpProvider.cs index 1e7037cb540..ebc5c4b0349 100644 --- a/src/System.Management.Automation/help/ProviderHelpProvider.cs +++ b/src/System.Management.Automation/help/ProviderHelpProvider.cs @@ -87,7 +87,7 @@ internal override IEnumerable ExactMatchHelp(HelpRequest helpRequest) } } - if (matchingProviders != null) + if (matchingProviders is not null) { foreach (ProviderInfo providerInfo in matchingProviders) { @@ -110,7 +110,7 @@ internal override IEnumerable ExactMatchHelp(HelpRequest helpRequest) HelpInfo helpInfo = GetCache(providerInfo.PSSnapInName + "\\" + providerInfo.Name); - if (helpInfo != null) + if (helpInfo is not null) { yield return helpInfo; } @@ -170,7 +170,7 @@ private void LoadHelpFile(ProviderInfo providerInfo) // Otherwise, // Look in the default search path and cmdlet assembly path Collection searchPaths = new Collection(); - if (mshSnapInInfo != null) + if (mshSnapInInfo is not null) { Diagnostics.Assert(!string.IsNullOrEmpty(mshSnapInInfo.ApplicationBase), "Application Base is null or empty."); @@ -180,7 +180,7 @@ private void LoadHelpFile(ProviderInfo providerInfo) // will look only in that path. helpFileToLoad = Path.Combine(mshSnapInInfo.ApplicationBase, helpFile); } - else if ((providerInfo.Module != null) && (!string.IsNullOrEmpty(providerInfo.Module.Path))) + else if ((providerInfo.Module is not null) && (!string.IsNullOrEmpty(providerInfo.Module.Path))) { helpFileToLoad = Path.Combine(providerInfo.Module.ModuleBase, helpFile); } @@ -231,7 +231,7 @@ private void LoadHelpFile(ProviderInfo providerInfo) { HelpInfo helpInfo = ProviderHelpInfo.Load(node); - if (helpInfo != null) + if (helpInfo is not null) { this.HelpSystem.TraceErrors(helpInfo.Errors); // Add snapin qualified type name for this command.. @@ -335,7 +335,7 @@ internal override IEnumerable SearchHelp(HelpRequest helpRequest, bool HelpInfo helpInfo = GetCache(providerInfo.PSSnapInName + "\\" + providerInfo.Name); - if (helpInfo != null) + if (helpInfo is not null) { if (searchOnlyContent) { diff --git a/src/System.Management.Automation/help/RemoteHelpInfo.cs b/src/System.Management.Automation/help/RemoteHelpInfo.cs index e0823880a55..1388ad66e5a 100644 --- a/src/System.Management.Automation/help/RemoteHelpInfo.cs +++ b/src/System.Management.Automation/help/RemoteHelpInfo.cs @@ -23,7 +23,7 @@ internal RemoteHelpInfo( string remoteHelpCategory, HelpCategory localHelpCategory) : base(localHelpCategory) { - Dbg.Assert(remoteRunspace != null, "Caller should verify arguments"); + Dbg.Assert(remoteRunspace is not null, "Caller should verify arguments"); using (PowerShell powerShell = PowerShell.Create()) { @@ -55,16 +55,16 @@ internal RemoteHelpInfo( // get-help (on par with get-command), it was decided to use the local command name // for the help content. PSPropertyInfo nameInfo = _deserializedRemoteHelp.Properties["Name"]; - if (nameInfo != null) + if (nameInfo is not null) { nameInfo.Value = localCommandName; } PSObject commandDetails = this.Details; - if (commandDetails != null) + if (commandDetails is not null) { nameInfo = commandDetails.Properties["Name"]; - if (nameInfo != null) + if (nameInfo is not null) { nameInfo.Value = localCommandName; } diff --git a/src/System.Management.Automation/help/SaveHelpCommand.cs b/src/System.Management.Automation/help/SaveHelpCommand.cs index 26de687778b..7bea383fc31 100644 --- a/src/System.Management.Automation/help/SaveHelpCommand.cs +++ b/src/System.Management.Automation/help/SaveHelpCommand.cs @@ -113,7 +113,7 @@ protected override void ProcessRecord() { // Module and FullyQualifiedModule should not be specified at the same time. // Throw out terminating error if this is the case. - if (Module != null && FullyQualifiedModule != null) + if (Module is not null && FullyQualifiedModule is not null) { string errMsg = StringUtil.Format(SessionStateStrings.GetContent_TailAndHeadCannotCoexist, "Module", "FullyQualifiedModule"); ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "ModuleAndFullyQualifiedModuleCannotBeSpecifiedTogether", ErrorCategory.InvalidOperation, null); @@ -123,7 +123,7 @@ protected override void ProcessRecord() List moduleNames = null; List moduleInfos = null; - if (Module != null) + if (Module is not null) { moduleNames = new List(); moduleInfos = new List(); @@ -186,7 +186,7 @@ internal override bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, string destPath = path; - if (_credential != null) + if (_credential is not null) { if (path.Contains("*")) { @@ -260,7 +260,7 @@ internal override bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, } finally { - if (helpInfoDrive != null) + if (helpInfoDrive is not null) { helpInfoDrive.Dispose(); } @@ -288,7 +288,7 @@ internal override bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, SessionState.Path.Combine(path, module.GetHelpInfoName()), _credential); - if (xml != null) + if (xml is not null) { // constructing the helpinfo object from previous update help log xml.. // no need to resolve the uri's in this case. @@ -331,7 +331,7 @@ internal override bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, } else { - Debug.Assert(helpInfoUri != null, "If we are here, helpInfoUri must not be null"); + Debug.Assert(helpInfoUri is not null, "If we are here, helpInfoUri must not be null"); string helpContentUri = contentUri.ResolvedUri; string helpContentName = module.GetHelpContentName(contentUri.Culture); @@ -349,7 +349,7 @@ internal override bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, { // Remote - if (_credential != null) + if (_credential is not null) { try { @@ -381,7 +381,7 @@ internal override bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, } } - if (_credential != null) + if (_credential is not null) { _helpSystem.GenerateHelpInfo(module.ModuleName, module.ModuleGuid, newHelpInfo.UnresolvedUri, contentUri.Culture.Name, newHelpInfo.GetCultureVersion(contentUri.Culture), tempPath, module.GetHelpInfoName(), _force); @@ -407,7 +407,7 @@ internal override bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, } finally { - if (helpContentDrive != null) + if (helpContentDrive is not null) { helpContentDrive.Dispose(); } @@ -432,14 +432,14 @@ public override object Transform(EngineIntrinsics engineIntrinsics, object input // deal with scalar string argument var strArg = argument as string; - if (strArg != null) + if (strArg is not null) { return new PSModuleInfo(name: strArg, path: null, context: null, sessionState: null); } // deal with IList argument IList iListArg = ParameterBinderBase.GetIList(argument); - if (iListArg != null && iListArg.Count > 0) + if (iListArg is not null && iListArg.Count > 0) { int elementCount = iListArg.Count; int targetIndex = 0; diff --git a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs index ff688dbf56f..cc5ac607cbb 100644 --- a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs +++ b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs @@ -46,7 +46,7 @@ public CultureInfo[] UICulture get { CultureInfo[] result = null; - if (_language != null) + if (_language is not null) { result = new CultureInfo[_language.Length]; for (int index = 0; index < _language.Length; index++) @@ -279,19 +279,19 @@ private Dictionary, UpdatableHelpModuleInfo> GetModuleInf List modules = null; string moduleNamePattern = null; - if (pattern != null) + if (pattern is not null) { moduleNamePattern = pattern; modules = Utils.GetModules(pattern, context); } - else if (fullyQualifiedName != null) + else if (fullyQualifiedName is not null) { moduleNamePattern = fullyQualifiedName.Name; modules = Utils.GetModules(fullyQualifiedName, context); } var helpModules = new Dictionary, UpdatableHelpModuleInfo>(); - if (modules != null) + if (modules is not null) { foreach (PSModuleInfo module in modules) { @@ -314,7 +314,7 @@ private Dictionary, UpdatableHelpModuleInfo> GetModuleInf if (!helpModules.ContainsKey(keyTuple)) { List availableModules = Utils.GetModules(name.Key, context); - if (availableModules != null) + if (availableModules is not null) { foreach (PSModuleInfo module in availableModules) { @@ -366,8 +366,8 @@ protected override void EndProcessing() UpdatableHelpExceptionContext e = exception; if ((exception.Exception.FullyQualifiedErrorId == "HelpCultureNotSupported") && - ((exception.Cultures != null && exception.Cultures.Count > 1) || - (exception.Modules != null && exception.Modules.Count > 1))) + ((exception.Cultures is not null && exception.Cultures.Count > 1) || + (exception.Modules is not null && exception.Modules.Count > 1))) { // Win8: 744749 Rewriting the error message only in the case where either // multiple cultures or multiple modules are involved. @@ -399,7 +399,7 @@ internal void Process(IEnumerable moduleNames, IEnumerable moduleNames, IEnumerable, UpdatableHelpModuleInfo> GetModuleIn if (modules.Count == 0 && _exceptions.Count == 0 && !noErrors) { - var errorMessage = fullyQualifiedName != null ? StringUtil.Format(HelpDisplayStrings.ModuleNotFoundWithFullyQualifiedName, fullyQualifiedName) + var errorMessage = fullyQualifiedName is not null ? StringUtil.Format(HelpDisplayStrings.ModuleNotFoundWithFullyQualifiedName, fullyQualifiedName) : StringUtil.Format(HelpDisplayStrings.CannotMatchModulePattern, pattern); ErrorRecord errorRecord = new ErrorRecord(new Exception(errorMessage), @@ -642,7 +642,7 @@ internal Dictionary, UpdatableHelpModuleInfo> GetModuleIn internal bool IsUpdateNecessary(UpdatableHelpModuleInfo module, UpdatableHelpInfo currentHelpInfo, UpdatableHelpInfo newHelpInfo, CultureInfo culture, bool force) { - Debug.Assert(module != null); + Debug.Assert(module is not null); if (newHelpInfo is null) { @@ -660,7 +660,7 @@ internal bool IsUpdateNecessary(UpdatableHelpModuleInfo module, UpdatableHelpInf } // Version check - if (!force && currentHelpInfo != null && !currentHelpInfo.IsNewerVersion(newHelpInfo, culture)) + if (!force && currentHelpInfo is not null && !currentHelpInfo.IsNewerVersion(newHelpInfo, culture)) { return false; } @@ -870,7 +870,7 @@ internal void ProcessException(string moduleName, string culture, Exception e) _exceptions[except.FullyQualifiedErrorId].Modules.Add(moduleName); - if (culture != null) + if (culture is not null) { _exceptions[except.FullyQualifiedErrorId].Cultures.Add(culture); } diff --git a/src/System.Management.Automation/help/UpdatableHelpInfo.cs b/src/System.Management.Automation/help/UpdatableHelpInfo.cs index df59e49e45f..f87ea98f5e6 100644 --- a/src/System.Management.Automation/help/UpdatableHelpInfo.cs +++ b/src/System.Management.Automation/help/UpdatableHelpInfo.cs @@ -21,8 +21,8 @@ internal class CultureSpecificUpdatableHelp /// Version info. internal CultureSpecificUpdatableHelp(CultureInfo culture, Version version) { - Debug.Assert(version != null); - Debug.Assert(culture != null); + Debug.Assert(version is not null); + Debug.Assert(culture is not null); Culture = culture; Version = version; @@ -51,7 +51,7 @@ internal class UpdatableHelpInfo /// Supported UI cultures. internal UpdatableHelpInfo(string unresolvedUri, CultureSpecificUpdatableHelp[] cultures) { - Debug.Assert(cultures != null); + Debug.Assert(cultures is not null); UnresolvedUri = unresolvedUri; HelpContentUriCollection = new Collection(); @@ -81,12 +81,12 @@ internal UpdatableHelpInfo(string unresolvedUri, CultureSpecificUpdatableHelp[] /// True if the other HelpInfo is newer, false if not. internal bool IsNewerVersion(UpdatableHelpInfo helpInfo, CultureInfo culture) { - Debug.Assert(helpInfo != null); + Debug.Assert(helpInfo is not null); Version v1 = helpInfo.GetCultureVersion(culture); Version v2 = GetCultureVersion(culture); - Debug.Assert(v1 != null); + Debug.Assert(v1 is not null); if (v2 is null) { @@ -103,7 +103,7 @@ internal bool IsNewerVersion(UpdatableHelpInfo helpInfo, CultureInfo culture) /// True if supported, false if not. internal bool IsCultureSupported(CultureInfo culture) { - Debug.Assert(culture != null); + Debug.Assert(culture is not null); foreach (CultureSpecificUpdatableHelp updatableHelpItem in UpdatableHelpItems) { diff --git a/src/System.Management.Automation/help/UpdatableHelpModuleInfo.cs b/src/System.Management.Automation/help/UpdatableHelpModuleInfo.cs index 9f0c32d679a..34d1263c0a2 100644 --- a/src/System.Management.Automation/help/UpdatableHelpModuleInfo.cs +++ b/src/System.Management.Automation/help/UpdatableHelpModuleInfo.cs @@ -28,7 +28,7 @@ internal class UpdatableHelpModuleInfo internal UpdatableHelpModuleInfo(string name, Guid guid, string path, string uri) { Debug.Assert(!string.IsNullOrEmpty(name)); - Debug.Assert(guid != null); + Debug.Assert(guid is not null); Debug.Assert(!string.IsNullOrEmpty(path)); Debug.Assert(!string.IsNullOrEmpty(uri)); @@ -73,7 +73,7 @@ internal Guid ModuleGuid /// HelpContent name. internal string GetHelpContentName(CultureInfo culture) { - Debug.Assert(culture != null); + Debug.Assert(culture is not null); return ModuleName + "_" + _moduleGuid.ToString() + "_" + culture.Name + "_" + HelpContentZipName; } diff --git a/src/System.Management.Automation/help/UpdatableHelpSystem.cs b/src/System.Management.Automation/help/UpdatableHelpSystem.cs index e28b96a26a3..6508c2d66d3 100644 --- a/src/System.Management.Automation/help/UpdatableHelpSystem.cs +++ b/src/System.Management.Automation/help/UpdatableHelpSystem.cs @@ -292,7 +292,7 @@ internal IEnumerable GetCurrentUICulture() { CultureInfo culture = CultureInfo.CurrentUICulture; - while (culture != null) + while (culture is not null) { if (string.IsNullOrEmpty(culture.Name)) { @@ -345,7 +345,7 @@ internal UpdatableHelpInfo GetHelpInfo(UpdatableHelpCommandType commandType, str client.Timeout = _defaultTimeout; Task responseBody = client.GetStringAsync(uri); xml = responseBody.Result; - if (responseBody.Exception != null) + if (responseBody.Exception is not null) { return null; } @@ -797,7 +797,7 @@ private bool DownloadHelpContentHttpClient(string uri, string fileName, Updatabl if (!responseMsg.IsCanceled) { - if (responseMsg.Exception != null) + if (responseMsg.Exception is not null) { Errors.Add(new UpdatableHelpSystemException("HelpContentNotFound", StringUtil.Format(HelpDisplayStrings.HelpContentNotFound), @@ -845,7 +845,7 @@ private void WriteResponseToFile(HttpResponseMessage response, string fileName) { Task copyStreamOp = response.Content.CopyToAsync(downloadedFileStream); copyStreamOp.Wait(); - if (copyStreamOp.Exception != null) + if (copyStreamOp.Exception is not null) { Errors.Add(copyStreamOp.Exception); } @@ -901,7 +901,7 @@ internal void GenerateHelpInfo(string moduleName, Guid moduleGuid, string conten UpdatableHelpInfo oldHelpInfo = null; string xml = UpdatableHelpSystem.LoadStringFromPath(_cmdlet, destHelpInfo, null); - if (xml != null) + if (xml is not null) { // constructing the helpinfo object from previous update help log xml.. // no need to resolve the uri's in this case. @@ -927,7 +927,7 @@ internal void GenerateHelpInfo(string moduleName, Guid moduleGuid, string conten bool found = false; - if (oldHelpInfo != null) + if (oldHelpInfo is not null) { foreach (CultureSpecificUpdatableHelp oldInfo in oldHelpInfo.UpdatableHelpItems) { @@ -1268,7 +1268,7 @@ private void ValidateAndCopyHelpContent(string sourcePath, Collection de XmlNode helpItemsNode = null; - if (contentDocument.DocumentElement != null && + if (contentDocument.DocumentElement is not null && contentDocument.DocumentElement.LocalName.Equals("providerHelp", StringComparison.OrdinalIgnoreCase)) { helpItemsNode = contentDocument; @@ -1303,7 +1303,7 @@ private void ValidateAndCopyHelpContent(string sourcePath, Collection de } } - Debug.Assert(helpItemsNode != null, "helpItemsNode must not be null"); + Debug.Assert(helpItemsNode is not null, "helpItemsNode must not be null"); string targetNamespace = "http://schemas.microsoft.com/maml/2004/10"; @@ -1416,9 +1416,9 @@ private void ValidateAndCopyHelpContent(string sourcePath, Collection de /// String loaded. internal static string LoadStringFromPath(PSCmdlet cmdlet, string path, PSCredential credential) { - Debug.Assert(path != null); + Debug.Assert(path is not null); - if (credential != null) + if (credential is not null) { // New PSDrive @@ -1523,7 +1523,7 @@ private void HandleDownloadFileCompleted(object sender, AsyncCompletedEventArgs if (!e.Cancelled) { - if (e.Error != null) + if (e.Error is not null) { if (e.Error is WebException) { @@ -1613,7 +1613,7 @@ internal UpdatableHelpSystemDrive(PSCmdlet cmdlet, string path, PSCredential cre PSDriveInfo mappedDrive = cmdlet.SessionState.Drive.GetAtScope(_driveName, "local"); - if (mappedDrive != null) + if (mappedDrive is not null) { if (mappedDrive.Root.Equals(path)) { @@ -1645,7 +1645,7 @@ public void Dispose() { PSDriveInfo mappedDrive = _cmdlet.SessionState.Drive.GetAtScope(_driveName, "local"); - if (mappedDrive != null) + if (mappedDrive is not null) { _cmdlet.SessionState.Drive.Remove(_driveName, true, "local"); } diff --git a/src/System.Management.Automation/help/UpdatableHelpUri.cs b/src/System.Management.Automation/help/UpdatableHelpUri.cs index 28683a3e2a8..781780c843b 100644 --- a/src/System.Management.Automation/help/UpdatableHelpUri.cs +++ b/src/System.Management.Automation/help/UpdatableHelpUri.cs @@ -21,7 +21,7 @@ internal class UpdatableHelpUri internal UpdatableHelpUri(string moduleName, Guid moduleGuid, CultureInfo culture, string resolvedUri) { Debug.Assert(!string.IsNullOrEmpty(moduleName)); - Debug.Assert(moduleGuid != null); + Debug.Assert(moduleGuid is not null); Debug.Assert(!string.IsNullOrEmpty(resolvedUri)); ModuleName = moduleName; diff --git a/src/System.Management.Automation/help/UpdateHelpCommand.cs b/src/System.Management.Automation/help/UpdateHelpCommand.cs index 5936e6d91c3..b16a4fcefb5 100644 --- a/src/System.Management.Automation/help/UpdateHelpCommand.cs +++ b/src/System.Management.Automation/help/UpdateHelpCommand.cs @@ -148,7 +148,7 @@ protected override void BeginProcessing() // Pull default source path from GP string defaultSourcePath = _helpSystem.GetDefaultSourcePath(); - if (defaultSourcePath != null) + if (defaultSourcePath is not null) { _path = new string[1] { defaultSourcePath }; } @@ -164,7 +164,7 @@ protected override void ProcessRecord() { // Module and FullyQualifiedModule should not be specified at the same time. // Throw out terminating error if this is the case. - if (Module != null && FullyQualifiedModule != null) + if (Module is not null && FullyQualifiedModule is not null) { string errMsg = StringUtil.Format(SessionStateStrings.GetContent_TailAndHeadCannotCoexist, "Module", "FullyQualifiedModule"); ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "ModuleAndFullyQualifiedModuleCannotBeSpecifiedTogether", ErrorCategory.InvalidOperation, null); @@ -231,7 +231,7 @@ internal override bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, SessionState.Path.Combine(moduleBase, module.GetHelpInfoName()), null); - if (xml != null) + if (xml is not null) { // constructing the helpinfo object from previous update help log xml.. // no need to resolve the uri's in this case. @@ -250,7 +250,7 @@ internal override bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, _alreadyCheckedOncePerDayPerModule = true; - if (_path != null) + if (_path is not null) { UpdatableHelpSystemDrive helpInfoDrive = null; try @@ -271,7 +271,7 @@ internal override bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, { string sourcePath = path; - if (_credential != null) + if (_credential is not null) { UpdatableHelpSystemDrive drive = new UpdatableHelpSystemDrive(this, path, _credential); sourcePath = drive.DriveName; @@ -305,7 +305,7 @@ internal override bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, xml = UpdatableHelpSystem.LoadStringFromPath(this, literalPath, _credential); - if (xml != null) + if (xml is not null) { newHelpInfo = _helpSystem.CreateHelpInfo(xml, module.ModuleName, module.ModuleGuid, culture, resolvedPath, verbose: false, shouldResolveUri: true, ignoreValidationException: false); @@ -322,7 +322,7 @@ internal override bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, } finally { - if (helpInfoDrive != null) + if (helpInfoDrive is not null) { helpInfoDrive.Dispose(); } @@ -348,11 +348,11 @@ internal override bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, foreach (UpdatableHelpUri contentUri in newHelpInfo.HelpContentUriCollection) { - Version currentHelpVersion = (currentHelpInfo != null) ? currentHelpInfo.GetCultureVersion(contentUri.Culture) : null; + Version currentHelpVersion = (currentHelpInfo is not null) ? currentHelpInfo.GetCultureVersion(contentUri.Culture) : null; string updateHelpShouldProcessAction = string.Format(CultureInfo.InvariantCulture, HelpDisplayStrings.UpdateHelpShouldProcessActionMessage, module.ModuleName, - (currentHelpVersion != null) ? currentHelpVersion.ToString() : "0.0.0.0", + (currentHelpVersion is not null) ? currentHelpVersion.ToString() : "0.0.0.0", newHelpInfo.GetCultureVersion(contentUri.Culture), contentUri.Culture); if (!this.ShouldProcess(updateHelpShouldProcessAction, "Update-Help")) @@ -380,7 +380,7 @@ internal override bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, { try { - Debug.Assert(helpInfoUri != null, "If we are here, helpInfoUri must not be null"); + Debug.Assert(helpInfoUri is not null, "If we are here, helpInfoUri must not be null"); string helpContentUri = contentUri.ResolvedUri; string xsdPath = SessionState.Path.Combine(Utils.GetApplicationBase(Context.ShellID), "Schemas\\PSMaml\\maml.xsd"); // TODO: Edit the maml XSDs and change this @@ -408,7 +408,7 @@ internal override bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, if (Directory.Exists(helpContentUri)) { - if (_credential != null) + if (_credential is not null) { string helpContentName = module.GetHelpContentName(contentUri.Culture); string tempContentPath = Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetRandomFileName())); diff --git a/src/System.Management.Automation/logging/LogProvider.cs b/src/System.Management.Automation/logging/LogProvider.cs index c27c246e91e..da8943db67d 100644 --- a/src/System.Management.Automation/logging/LogProvider.cs +++ b/src/System.Management.Automation/logging/LogProvider.cs @@ -171,17 +171,17 @@ protected static void AppendException(StringBuilder sb, Exception except) IContainsErrorRecord ier = except as IContainsErrorRecord; - if (ier != null) + if (ier is not null) { ErrorRecord er = ier.ErrorRecord; - if (er != null) + if (er is not null) { sb.AppendLine(StringUtil.Format(EtwLoggingStrings.ErrorRecordId, er.FullyQualifiedErrorId)); ErrorDetails details = er.ErrorDetails; - if (details != null) + if (details is not null) { sb.AppendLine(StringUtil.Format(EtwLoggingStrings.ErrorRecordRecommendedAction, details.RecommendedAction)); } @@ -196,7 +196,7 @@ protected static void AppendException(StringBuilder sb, Exception except) /// Additional information. protected static void AppendAdditionalInfo(StringBuilder sb, Dictionary additionalInfo) { - if (additionalInfo != null) + if (additionalInfo is not null) { foreach (KeyValuePair value in additionalInfo) { diff --git a/src/System.Management.Automation/logging/MshLog.cs b/src/System.Management.Automation/logging/MshLog.cs index a1f73699056..0effcbb0663 100644 --- a/src/System.Management.Automation/logging/MshLog.cs +++ b/src/System.Management.Automation/logging/MshLog.cs @@ -116,7 +116,7 @@ private static IEnumerable GetLogProvider(ExecutionContext executio /// private static IEnumerable GetLogProvider(LogContext logContext) { - System.Diagnostics.Debug.Assert(logContext != null); + System.Diagnostics.Debug.Assert(logContext is not null); System.Diagnostics.Debug.Assert(!string.IsNullOrEmpty(logContext.ShellId)); return GetLogProvider(logContext.ShellId); @@ -217,7 +217,7 @@ internal static void LogEngineHealthEvent(ExecutionContext executionContext, InvocationInfo invocationInfo = null; IContainsErrorRecord icer = exception as IContainsErrorRecord; - if (icer != null && icer.ErrorRecord != null) + if (icer is not null && icer.ErrorRecord is not null) invocationInfo = icer.ErrorRecord.InvocationInfo; foreach (LogProvider provider in GetLogProvider(executionContext)) { @@ -419,7 +419,7 @@ Severity severity InvocationInfo invocationInfo = null; IContainsErrorRecord icer = exception as IContainsErrorRecord; - if (icer != null && icer.ErrorRecord != null) + if (icer is not null && icer.ErrorRecord is not null) invocationInfo = icer.ErrorRecord.InvocationInfo; foreach (LogProvider provider in GetLogProvider(executionContext)) { @@ -610,7 +610,7 @@ Severity severity InvocationInfo invocationInfo = null; IContainsErrorRecord icer = exception as IContainsErrorRecord; - if (icer != null && icer.ErrorRecord != null) + if (icer is not null && icer.ErrorRecord is not null) invocationInfo = icer.ErrorRecord.InvocationInfo; foreach (LogProvider provider in GetLogProvider(executionContext)) { @@ -768,7 +768,7 @@ private static LogContext GetLogContext(ExecutionContext executionContext, Invoc logContext.ShellId = shellId; logContext.Severity = severity.ToString(); - if (executionContext.EngineHostInterface != null) + if (executionContext.EngineHostInterface is not null) { logContext.HostName = executionContext.EngineHostInterface.Name; logContext.HostVersion = executionContext.EngineHostInterface.Version.ToString(); @@ -777,13 +777,13 @@ private static LogContext GetLogContext(ExecutionContext executionContext, Invoc logContext.HostApplication = string.Join(" ", Environment.GetCommandLineArgs()); - if (executionContext.CurrentRunspace != null) + if (executionContext.CurrentRunspace is not null) { logContext.EngineVersion = executionContext.CurrentRunspace.Version.ToString(); logContext.RunspaceId = executionContext.CurrentRunspace.InstanceId.ToString(); Pipeline currentPipeline = ((RunspaceBase)executionContext.CurrentRunspace).GetCurrentlyRunningPipeline(); - if (currentPipeline != null) + if (currentPipeline is not null) { logContext.PipelineId = currentPipeline.InstanceId.ToString(CultureInfo.CurrentCulture); } @@ -810,7 +810,7 @@ private static LogContext GetLogContext(ExecutionContext executionContext, Invoc System.Management.Automation.Remoting.PSSenderInfo psSenderInfo = executionContext.SessionState.PSVariable.GetValue("PSSenderInfo") as System.Management.Automation.Remoting.PSSenderInfo; - if (psSenderInfo != null) + if (psSenderInfo is not null) { logContext.ConnectedUser = psSenderInfo.UserInfo.Identity.Name; } @@ -823,7 +823,7 @@ private static LogContext GetLogContext(ExecutionContext executionContext, Invoc logContext.ScriptName = invocationInfo.ScriptName; logContext.CommandLine = invocationInfo.Line; - if (invocationInfo.MyCommand != null) + if (invocationInfo.MyCommand is not null) { logContext.CommandName = invocationInfo.MyCommand.Name; logContext.CommandType = invocationInfo.MyCommand.CommandType.ToString(); diff --git a/src/System.Management.Automation/logging/eventlog/EventLogLogProvider.cs b/src/System.Management.Automation/logging/eventlog/EventLogLogProvider.cs index e6f301a04ac..f355a372976 100644 --- a/src/System.Management.Automation/logging/eventlog/EventLogLogProvider.cs +++ b/src/System.Management.Automation/logging/eventlog/EventLogLogProvider.cs @@ -99,13 +99,13 @@ internal override void LogEngineHealthEvent(LogContext logContext, int eventId, Hashtable mapArgs = new Hashtable(); IContainsErrorRecord icer = exception as IContainsErrorRecord; - if (icer != null && icer.ErrorRecord != null) + if (icer is not null && icer.ErrorRecord is not null) { mapArgs["ExceptionClass"] = exception.GetType().Name; mapArgs["ErrorCategory"] = icer.ErrorRecord.CategoryInfo.Category; mapArgs["ErrorId"] = icer.ErrorRecord.FullyQualifiedErrorId; - if (icer.ErrorRecord.ErrorDetails != null) + if (icer.ErrorRecord.ErrorDetails is not null) { mapArgs["ErrorMessage"] = icer.ErrorRecord.ErrorDetails.Message; } @@ -219,13 +219,13 @@ internal override void LogCommandHealthEvent(LogContext logContext, Exception ex Hashtable mapArgs = new Hashtable(); IContainsErrorRecord icer = exception as IContainsErrorRecord; - if (icer != null && icer.ErrorRecord != null) + if (icer is not null && icer.ErrorRecord is not null) { mapArgs["ExceptionClass"] = exception.GetType().Name; mapArgs["ErrorCategory"] = icer.ErrorRecord.CategoryInfo.Category; mapArgs["ErrorId"] = icer.ErrorRecord.FullyQualifiedErrorId; - if (icer.ErrorRecord.ErrorDetails != null) + if (icer.ErrorRecord.ErrorDetails is not null) { mapArgs["ErrorMessage"] = icer.ErrorRecord.ErrorDetails.Message; } @@ -396,13 +396,13 @@ internal override void LogProviderHealthEvent(LogContext logContext, string prov mapArgs["ProviderName"] = providerName; IContainsErrorRecord icer = exception as IContainsErrorRecord; - if (icer != null && icer.ErrorRecord != null) + if (icer is not null && icer.ErrorRecord is not null) { mapArgs["ExceptionClass"] = exception.GetType().Name; mapArgs["ErrorCategory"] = icer.ErrorRecord.CategoryInfo.Category; mapArgs["ErrorId"] = icer.ErrorRecord.FullyQualifiedErrorId; - if (icer.ErrorRecord.ErrorDetails != null + if (icer.ErrorRecord.ErrorDetails is not null && !string.IsNullOrEmpty(icer.ErrorRecord.ErrorDetails.Message)) { mapArgs["ErrorMessage"] = icer.ErrorRecord.ErrorDetails.Message; diff --git a/src/System.Management.Automation/namespaces/AliasProvider.cs b/src/System.Management.Automation/namespaces/AliasProvider.cs index 0d7749516a5..7acc7145e62 100644 --- a/src/System.Management.Automation/namespaces/AliasProvider.cs +++ b/src/System.Management.Automation/namespaces/AliasProvider.cs @@ -150,13 +150,13 @@ internal override object GetSessionStateItem(string name) internal override object GetValueOfItem(object item) { Dbg.Diagnostics.Assert( - item != null, + item is not null, "Caller should verify the item parameter"); object value = item; AliasInfo aliasInfo = item as AliasInfo; - if (aliasInfo != null) + if (aliasInfo is not null) { value = aliasInfo.Definition; } @@ -188,7 +188,7 @@ internal override void SetSessionStateItem(string name, object value, bool write AliasInfo item = null; - bool dynamicParametersSpecified = dynamicParameters != null && dynamicParameters.OptionsSet; + bool dynamicParametersSpecified = dynamicParameters is not null && dynamicParameters.OptionsSet; if (value is null) { @@ -196,7 +196,7 @@ internal override void SetSessionStateItem(string name, object value, bool write { item = (AliasInfo)GetSessionStateItem(name); - if (item != null) + if (item is not null) { item.SetOptions(dynamicParameters.Options, Force); } @@ -211,7 +211,7 @@ internal override void SetSessionStateItem(string name, object value, bool write do // false loop { string stringValue = value as string; - if (stringValue != null) + if (stringValue is not null) { if (dynamicParametersSpecified) { @@ -226,7 +226,7 @@ internal override void SetSessionStateItem(string name, object value, bool write } AliasInfo alias = value as AliasInfo; - if (alias != null) + if (alias is not null) { AliasInfo newAliasInfo = new AliasInfo( @@ -248,7 +248,7 @@ internal override void SetSessionStateItem(string name, object value, bool write } while (false); } - if (writeItem && item != null) + if (writeItem && item is not null) { WriteItemObject(item, item.Name, false); } @@ -297,7 +297,7 @@ internal override bool CanRenameItem(object item) bool result = false; AliasInfo aliasInfo = item as AliasInfo; - if (aliasInfo != null) + if (aliasInfo is not null) { if ((aliasInfo.Options & ScopedItemOptions.Constant) != 0 || ((aliasInfo.Options & ScopedItemOptions.ReadOnly) != 0 && !Force)) diff --git a/src/System.Management.Automation/namespaces/CoreCommandContext.cs b/src/System.Management.Automation/namespaces/CoreCommandContext.cs index 5b31fa558d1..0ca9a097da0 100644 --- a/src/System.Management.Automation/namespaces/CoreCommandContext.cs +++ b/src/System.Management.Automation/namespaces/CoreCommandContext.cs @@ -60,7 +60,7 @@ internal CmdletProviderContext(ExecutionContext executionContext) ExecutionContext = executionContext; Origin = CommandOrigin.Internal; Drive = executionContext.EngineSessionState.CurrentDrive; - if ((executionContext.CurrentCommandProcessor != null) && + if ((executionContext.CurrentCommandProcessor is not null) && (executionContext.CurrentCommandProcessor.Command is Cmdlet)) { _command = (Cmdlet)executionContext.CurrentCommandProcessor.Command; @@ -124,7 +124,7 @@ internal CmdletProviderContext( _command = command; Origin = command.CommandOrigin; - if (credentials != null) + if (credentials is not null) { _credentials = credentials; } @@ -178,7 +178,7 @@ internal CmdletProviderContext( _command = command; Origin = command.CommandOrigin; - if (credentials != null) + if (credentials is not null) { _credentials = credentials; } @@ -263,7 +263,7 @@ internal CmdletProviderContext( _command = contextToCopyFrom._command; - if (contextToCopyFrom.Credential != null) + if (contextToCopyFrom.Credential is not null) { _credentials = contextToCopyFrom.Credential; } @@ -383,7 +383,7 @@ internal System.Management.Automation.Provider.CmdletProvider ProviderInstance private void CopyFilters(CmdletProviderContext context) { Dbg.Diagnostics.Assert( - context != null, + context is not null, "The caller should have verified the context"); Include = context.Include; @@ -393,7 +393,7 @@ private void CopyFilters(CmdletProviderContext context) internal void RemoveStopReferral() { - if (_copiedContext != null) + if (_copiedContext is not null) { _copiedContext.StopReferrals.Remove(this); } @@ -414,7 +414,7 @@ internal InvocationInfo MyInvocation { get { - if (_command != null) + if (_command is not null) { return _command.MyInvocation; } @@ -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 is null && Drive is not null) { result = Drive.Credential; } @@ -468,11 +468,11 @@ internal bool UseTransaction { get { - if ((_command != null) && (_command.CommandRuntime != null)) + if ((_command is not null) && (_command.CommandRuntime is not null)) { MshCommandRuntime mshRuntime = _command.CommandRuntime as MshCommandRuntime; - if (mshRuntime != null) + if (mshRuntime is not null) { return mshRuntime.UseTransaction; } @@ -487,7 +487,7 @@ internal bool UseTransaction /// public bool TransactionAvailable() { - if (_command != null) + if (_command is not null) { return _command.TransactionAvailable(); } @@ -503,7 +503,7 @@ public PSTransactionContext CurrentPSTransaction { get { - if (_command != null) + if (_command is not null) { return _command.CurrentPSTransaction; } @@ -568,7 +568,7 @@ internal bool ShouldProcess( string target) { bool result = true; - if (_command != null) + if (_command is not null) { result = _command.ShouldProcess(target); } @@ -595,7 +595,7 @@ internal bool ShouldProcess( string action) { bool result = true; - if (_command != null) + if (_command is not null) { result = _command.ShouldProcess(target, action); } @@ -635,7 +635,7 @@ internal bool ShouldProcess( string caption) { bool result = true; - if (_command != null) + if (_command is not null) { result = _command.ShouldProcess( verboseDescription, @@ -685,7 +685,7 @@ internal bool ShouldProcess( out ShouldProcessReason shouldProcessReason) { bool result = true; - if (_command != null) + if (_command is not null) { result = _command.ShouldProcess( verboseDescription, @@ -720,7 +720,7 @@ internal bool ShouldContinue( string caption) { bool result = true; - if (_command != null) + if (_command is not null) { result = _command.ShouldContinue(query, caption); } @@ -755,7 +755,7 @@ internal bool ShouldContinue( ref bool noToAll) { bool result = true; - if (_command != null) + if (_command is not null) { result = _command.ShouldContinue( query, caption, ref yesToAll, ref noToAll); @@ -777,7 +777,7 @@ internal bool ShouldContinue( /// internal void WriteVerbose(string text) { - if (_command != null) + if (_command is not null) { _command.WriteVerbose(text); } @@ -791,7 +791,7 @@ internal void WriteVerbose(string text) /// internal void WriteWarning(string text) { - if (_command != null) + if (_command is not null) { _command.WriteWarning(text); } @@ -799,7 +799,7 @@ internal void WriteWarning(string text) internal void WriteProgress(ProgressRecord record) { - if (_command != null) + if (_command is not null) { _command.WriteProgress(record); } @@ -813,7 +813,7 @@ internal void WriteProgress(ProgressRecord record) /// internal void WriteDebug(string text) { - if (_command != null) + if (_command is not null) { _command.WriteDebug(text); } @@ -821,7 +821,7 @@ internal void WriteDebug(string text) internal void WriteInformation(InformationRecord record) { - if (_command != null) + if (_command is not null) { _command.WriteInformation(record); } @@ -829,7 +829,7 @@ internal void WriteInformation(InformationRecord record) internal void WriteInformation(object messageData, string[] tags) { - if (_command != null) + if (_command is not null) { _command.WriteInformation(messageData, tags); } @@ -937,14 +937,14 @@ internal void ThrowFirstErrorOrDoNothing(bool wrapExceptionInProviderException) { Collection errors = GetAccumulatedErrorObjects(); - if (errors != null && errors.Count > 0) + if (errors is not null && errors.Count > 0) { // Throw the first exception if (wrapExceptionInProviderException) { ProviderInfo providerInfo = null; - if (this.ProviderInstance != null) + if (this.ProviderInstance is not null) { providerInfo = this.ProviderInstance.ProviderInfo; } @@ -958,7 +958,7 @@ internal void ThrowFirstErrorOrDoNothing(bool wrapExceptionInProviderException) MshLog.LogProviderHealthEvent( this.ExecutionContext, - providerInfo != null ? providerInfo.Name : "unknown provider", + providerInfo is not null ? providerInfo.Name : "unknown provider", e, Severity.Warning); @@ -1035,7 +1035,7 @@ internal void WriteObject(object obj) if (PassThru) { - if (_command != null) + if (_command is not null) { s_tracer.WriteLine("Writing to command pipeline"); @@ -1101,7 +1101,7 @@ internal void WriteError(ErrorRecord errorRecord) if (_streamErrors) { - if (_command != null) + if (_command is not null) { s_tracer.WriteLine("Writing error package to command error pipe"); @@ -1120,8 +1120,8 @@ internal void WriteError(ErrorRecord errorRecord) // Since we are not streaming, just add the object to the accumulatedErrorObjects _accumulatedErrorObjects.Add(errorRecord); - if (errorRecord.ErrorDetails != null - && errorRecord.ErrorDetails.TextLookupError != null) + if (errorRecord.ErrorDetails is not null + && errorRecord.ErrorDetails.TextLookupError is not null) { Exception textLookupError = errorRecord.ErrorDetails.TextLookupError; errorRecord.ErrorDetails.TextLookupError = null; @@ -1143,7 +1143,7 @@ internal void WriteError(ErrorRecord errorRecord) /// internal bool HasErrors() { - return _accumulatedErrorObjects != null && _accumulatedErrorObjects.Count > 0; + return _accumulatedErrorObjects is not null && _accumulatedErrorObjects.Count > 0; } /// @@ -1155,7 +1155,7 @@ internal void StopProcessing() { Stopping = true; - if (_providerInstance != null) + if (_providerInstance is not null) { // We don't need to catch any of the exceptions here because // we are terminating the pipeline and any exception will @@ -1184,8 +1184,8 @@ internal bool HasIncludeOrExclude { get { - return ((Include != null && Include.Count > 0) || - (Exclude != null && Exclude.Count > 0)); + return ((Include is not null && Include.Count > 0) || + (Exclude is not null && Exclude.Count > 0)); } } diff --git a/src/System.Management.Automation/namespaces/DriveProviderBase.cs b/src/System.Management.Automation/namespaces/DriveProviderBase.cs index d69f17e94ee..6430ef75f8e 100644 --- a/src/System.Management.Automation/namespaces/DriveProviderBase.cs +++ b/src/System.Management.Automation/namespaces/DriveProviderBase.cs @@ -46,7 +46,7 @@ internal PSDriveInfo NewDrive(PSDriveInfo drive, CmdletProviderContext context) // Make sure the provider supports credentials if they were passed // in the drive. - if (drive.Credential != null && + if (drive.Credential is not null && drive.Credential != PSCredential.Empty && !CmdletProviderManagementIntrinsics.CheckProviderCapabilities(ProviderCapabilities.Credentials, ProviderInfo)) { diff --git a/src/System.Management.Automation/namespaces/EnvironmentProvider.cs b/src/System.Management.Automation/namespaces/EnvironmentProvider.cs index b22a3ecde9c..767de1ef4db 100644 --- a/src/System.Management.Automation/namespaces/EnvironmentProvider.cs +++ b/src/System.Management.Automation/namespaces/EnvironmentProvider.cs @@ -85,7 +85,7 @@ internal override object GetSessionStateItem(string name) string value = Environment.GetEnvironmentVariable(name); - if (value != null) + if (value is not null) { result = new DictionaryEntry(name, value); } @@ -229,7 +229,7 @@ internal override IDictionary GetSessionStateTable() internal override object GetValueOfItem(object item) { Dbg.Diagnostics.Assert( - item != null, + item is not null, "Caller should verify the item parameter"); object value = item; diff --git a/src/System.Management.Automation/namespaces/FileSystemContentStream.cs b/src/System.Management.Automation/namespaces/FileSystemContentStream.cs index 63770c59239..9fd3fc39c60 100644 --- a/src/System.Management.Automation/namespaces/FileSystemContentStream.cs +++ b/src/System.Management.Automation/namespaces/FileSystemContentStream.cs @@ -448,7 +448,7 @@ internal void SeekItemsBackward(int backCount) s_tracer.WriteLine("blocks seek backwards = {0}", backCount); var blocks = new List(); - if (_reader != null) + if (_reader is not null) { // Make the reader automatically detect the encoding Seek(0, SeekOrigin.Begin); @@ -530,7 +530,7 @@ internal void SeekItemsBackward(int backCount) { if (currentBlock == backCount) { - Dbg.Diagnostics.Assert(lastDelimiterMatch != null, "lastDelimiterMatch should not be null when currentBlock == backCount"); + Dbg.Diagnostics.Assert(lastDelimiterMatch is not null, "lastDelimiterMatch should not be null when currentBlock == backCount"); if (lastDelimiterMatch.EndsWith(actualDelimiter, StringComparison.Ordinal)) { curStreamPosition += _backReader.GetByteCount(_delimiter); @@ -578,7 +578,7 @@ private bool ReadByLine(bool waitChanges, List blocks, bool readBackward } } - if (line != null) + if (line is not null) { blocks.Add(line); } @@ -864,7 +864,7 @@ private void CreateStreams(string filePath, string streamName, FileMode fileMode if ((fileAccess & (FileAccess.Write)) != 0) { // Ensure we are using the proper encoding - if ((_reader != null) && + if ((_reader is not null) && ((fileAccess & (FileAccess.Read)) != 0)) { _reader.Peek(); @@ -889,7 +889,7 @@ private void CreateStreams(string filePath, string streamName, FileMode fileMode private void WaitForChanges(string filePath, FileMode fileMode, FileAccess fileAccess, FileShare fileShare, Encoding fileEncoding) { // Close the old stream, and store our current position. - if (_stream != null) + if (_stream is not null) { _fileOffset = _stream.Position; _stream.Dispose(); @@ -926,7 +926,7 @@ private void WaitForChanges(string filePath, FileMode fileMode, FileAccess fileA { bool isTaskCompleted = tcs.Task.Wait(500); - if (errorEventArgs != null) + if (errorEventArgs is not null) { throw errorEventArgs.GetException(); } @@ -971,9 +971,9 @@ private void WaitForChanges(string filePath, FileMode fileMode, FileAccess fileA // Seek to the place we last left off. _stream.Seek(_fileOffset, SeekOrigin.Begin); - if (_reader != null) { _reader.DiscardBufferedData(); } + if (_reader is not null) { _reader.DiscardBufferedData(); } - if (_backReader != null) { _backReader.DiscardBufferedData(); } + if (_backReader is not null) { _backReader.DiscardBufferedData(); } } /// @@ -987,15 +987,15 @@ private void WaitForChanges(string filePath, FileMode fileMode, FileAccess fileA /// public void Seek(long offset, SeekOrigin origin) { - if (_writer != null) { _writer.Flush(); } + if (_writer is not null) { _writer.Flush(); } _stream.Seek(offset, origin); - if (_writer != null) { _writer.Flush(); } + if (_writer is not null) { _writer.Flush(); } - if (_reader != null) { _reader.DiscardBufferedData(); } + if (_reader is not null) { _reader.DiscardBufferedData(); } - if (_backReader != null) { _backReader.DiscardBufferedData(); } + if (_backReader is not null) { _backReader.DiscardBufferedData(); } } /// @@ -1005,7 +1005,7 @@ public void Close() { bool streamClosed = false; - if (_writer != null) + if (_writer is not null) { try { @@ -1018,13 +1018,13 @@ public void Close() } } - if (_reader != null) + if (_reader is not null) { _reader.Dispose(); streamClosed = true; } - if (_backReader != null) + if (_backReader is not null) { _backReader.Dispose(); streamClosed = true; @@ -1057,7 +1057,7 @@ public IList Write(IList content) foreach (object line in content) { object[] contentArray = line as object[]; - if (contentArray != null) + if (contentArray is not null) { foreach (object obj in contentArray) { @@ -1119,13 +1119,13 @@ internal void Dispose(bool isDisposing) { if (isDisposing) { - if (_stream != null) + if (_stream is not null) _stream.Dispose(); - if (_reader != null) + if (_reader is not null) _reader.Dispose(); - if (_backReader != null) + if (_backReader is not null) _backReader.Dispose(); - if (_writer != null) + if (_writer is not null) _writer.Dispose(); } } @@ -1176,7 +1176,7 @@ internal FileStreamBackReader(FileStream fileStream, Encoding encoding) /// private bool IsSingleByteCharacterSet() { - if (_singleByteCharSet != null) + if (_singleByteCharSet is not null) return (bool)_singleByteCharSet; // Porting note: only UTF-8 is supported on Linux, which is not an SBCS diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 3c82e1a4e11..c2bedaac3df 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -253,10 +253,10 @@ internal override bool IsFilterSet() { bool attributeFilterSet = false; GetChildDynamicParameters fspDynamicParam = DynamicParameters as GetChildDynamicParameters; - if (fspDynamicParam != null) + if (fspDynamicParam is not null) { attributeFilterSet = ( - (fspDynamicParam.Attributes != null) + (fspDynamicParam.Attributes is not null) || (fspDynamicParam.Directory) || (fspDynamicParam.File) || (fspDynamicParam.Hidden) @@ -389,7 +389,7 @@ public string GetHelpMaml(string helpItemName, string path) // Execute the XPath query and return its MAML snippet XmlNode result = document.SelectSingleNode(xpathQuery, nsMgr); - if (result != null) + if (result is not null) { return result.OuterXml; } @@ -424,7 +424,7 @@ public string GetHelpMaml(string helpItemName, string path) } finally { - if (reader != null) + if (reader is not null) { ((IDisposable)reader).Dispose(); } @@ -451,7 +451,7 @@ public string GetHelpMaml(string helpItemName, string path) protected override ProviderInfo Start(ProviderInfo providerInfo) { // Set the home folder for the user - if (providerInfo != null && string.IsNullOrEmpty(providerInfo.Home)) + if (providerInfo is not null && string.IsNullOrEmpty(providerInfo.Home)) { // %USERPROFILE% - indicate where a user's home directory is located in the file system. string homeDirectory = Environment.GetEnvironmentVariable(Platform.CommonEnvVariableNames.Home); @@ -609,7 +609,7 @@ private void MapNetworkDrive(PSDriveInfo drive) private void WinMapNetworkDrive(PSDriveInfo drive) { - if (drive != null && !string.IsNullOrEmpty(drive.Root)) + if (drive is not null && !string.IsNullOrEmpty(drive.Root)) { const int CONNECT_UPDATE_PROFILE = 0x00000001; const int CONNECT_NOPERSIST = 0x00000000; @@ -643,7 +643,7 @@ private void WinMapNetworkDrive(PSDriveInfo drive) } // If alternate credentials is supplied then use them to get connected to network share. - if (drive.Credential != null && !drive.Credential.Equals(PSCredential.Empty)) + if (drive.Credential is not null && !drive.Credential.Equals(PSCredential.Empty)) { userName = drive.Credential.UserName; @@ -695,7 +695,7 @@ private void WinMapNetworkDrive(PSDriveInfo drive) finally { // Clear the password in the memory. - if (passwd != null) + if (passwd is not null) { Array.Clear(passwd, 0, passwd.Length - 1); } @@ -711,8 +711,8 @@ private void WinMapNetworkDrive(PSDriveInfo drive) /// private bool IsNetworkMappedDrive(PSDriveInfo drive) { - bool shouldMapNetworkDrive = (drive != null && !string.IsNullOrEmpty(drive.Root) && PathIsNetworkPath(drive.Root)) && - (drive.Persist || (drive.Credential != null && !drive.Credential.Equals(PSCredential.Empty))); + bool shouldMapNetworkDrive = (drive is not null && !string.IsNullOrEmpty(drive.Root) && PathIsNetworkPath(drive.Root)) && + (drive.Persist || (drive.Credential is not null && !drive.Credential.Equals(PSCredential.Empty))); return shouldMapNetworkDrive; } @@ -792,7 +792,7 @@ private PSDriveInfo WinRemoveDrive(PSDriveInfo drive) private bool IsSupportedDriveForPersistence(PSDriveInfo drive) { bool isSupportedDriveForPersistence = false; - if (drive != null && !string.IsNullOrEmpty(drive.Name) && drive.Name.Length == 1) + if (drive is not null && !string.IsNullOrEmpty(drive.Name) && drive.Name.Length == 1) { char driveChar = Convert.ToChar(drive.Name, CultureInfo.InvariantCulture); @@ -1012,7 +1012,7 @@ protected override Collection InitializeDefaultDrives() Collection results = new Collection(); DriveInfo[] logicalDrives = DriveInfo.GetDrives(); - if (logicalDrives != null) + if (logicalDrives is not null) { foreach (DriveInfo newDrive in logicalDrives) { @@ -1276,12 +1276,12 @@ protected override void GetItem(string path) bool retrieveStreams = false; FileSystemProviderGetItemDynamicParameters dynamicParameters = null; - if (DynamicParameters != null) + if (DynamicParameters is not null) { dynamicParameters = DynamicParameters as FileSystemProviderGetItemDynamicParameters; - if (dynamicParameters != null) + if (dynamicParameters is not null) { - if ((dynamicParameters.Stream != null) && (dynamicParameters.Stream.Length > 0)) + if ((dynamicParameters.Stream is not null) && (dynamicParameters.Stream.Length > 0)) { retrieveStreams = true; } @@ -1305,7 +1305,7 @@ protected override void GetItem(string path) #endif FileSystemInfo result = GetFileSystemItem(path, ref isContainer, false); - if (result != null) + if (result is not null) { #if !UNIX // If we want to retrieve the file streams, retrieve them. @@ -1388,7 +1388,7 @@ private FileSystemInfo GetFileSystemItem(string path, ref bool isContainer, bool FlagsExpression evaluator = null; FlagsExpression switchEvaluator = null; GetChildDynamicParameters fspDynamicParam = DynamicParameters as GetChildDynamicParameters; - if (fspDynamicParam != null) + if (fspDynamicParam is not null) { evaluator = fspDynamicParam.Attributes; switchEvaluator = FormatAttributeSwitchParameters(); @@ -1397,12 +1397,12 @@ private FileSystemInfo GetFileSystemItem(string path, ref bool isContainer, bool bool filterHidden = false; // "Hidden" is specified somewhere in the expression bool switchFilterHidden = false; // "Hidden" is specified somewhere in the parameters - if (evaluator != null) + if (evaluator is not null) { filterHidden = evaluator.ExistsInExpression(FileAttributes.Hidden); } - if (switchEvaluator != null) + if (switchEvaluator is not null) { switchFilterHidden = switchEvaluator.ExistsInExpression(FileAttributes.Hidden); } @@ -1642,7 +1642,7 @@ private void GetPathItems( var fsinfo = GetFileSystemInfo(path, out bool isDirectory); - if (fsinfo != null) + if (fsinfo is not null) { if (isDirectory) { @@ -1651,7 +1651,7 @@ private void GetPathItems( if (recurse) { GetChildDynamicParameters fspDynamicParam = DynamicParameters as GetChildDynamicParameters; - if (fspDynamicParam != null && fspDynamicParam.FollowSymlink) + if (fspDynamicParam is not null && fspDynamicParam.FollowSymlink) { tracker = new InodeTracker(fsinfo.FullName); } @@ -1665,7 +1665,7 @@ private void GetPathItems( FlagsExpression evaluator = null; FlagsExpression switchEvaluator = null; GetChildDynamicParameters fspDynamicParam = DynamicParameters as GetChildDynamicParameters; - if (fspDynamicParam != null) + if (fspDynamicParam is not null) { evaluator = fspDynamicParam.Attributes; switchEvaluator = FormatAttributeSwitchParameters(); @@ -1676,13 +1676,13 @@ private void GetPathItems( bool filterHidden = false; // "Hidden" is specified somewhere in the expression bool switchFilterHidden = false; // "Hidden" is specified somewhere in the parameters - if (evaluator != null) + if (evaluator is not null) { attributeFilter = evaluator.Evaluate(fsinfo.Attributes); // expressions filterHidden = evaluator.ExistsInExpression(FileAttributes.Hidden); } - if (switchEvaluator != null) + if (switchEvaluator is not null) { switchAttributeFilter = switchEvaluator.Evaluate(fsinfo.Attributes); // switch parameters switchFilterHidden = switchEvaluator.ExistsInExpression(FileAttributes.Hidden); @@ -1734,7 +1734,7 @@ private void Dir( try { - if (Filter != null && + if (Filter is not null && Filter.Length > 0) { if (returnContainers == ReturnContainers.ReturnAllContainers) @@ -1776,7 +1776,7 @@ private void Dir( FlagsExpression switchEvaluator = null; GetChildDynamicParameters fspDynamicParam = DynamicParameters as GetChildDynamicParameters; - if (fspDynamicParam != null) + if (fspDynamicParam is not null) { evaluator = fspDynamicParam.Attributes; switchEvaluator = FormatAttributeSwitchParameters(); @@ -1805,13 +1805,13 @@ private void Dir( // 'Hidden' is specified somewhere in the parameters bool switchFilterHidden = false; - if (evaluator != null) + if (evaluator is not null) { attributeFilter = evaluator.Evaluate(filesystemInfo.Attributes); filterHidden = evaluator.ExistsInExpression(FileAttributes.Hidden); } - if (switchEvaluator != null) + if (switchEvaluator is not null) { switchAttributeFilter = switchEvaluator.Evaluate(filesystemInfo.Attributes); switchFilterHidden = switchEvaluator.ExistsInExpression(FileAttributes.Hidden); @@ -1868,12 +1868,12 @@ private void Dir( bool isFilterHiddenSpecified = false; // "Hidden" is specified somewhere in the expression bool isSwitchFilterHiddenSpecified = false; // "Hidden" is specified somewhere in the parameters - if (evaluator != null) + if (evaluator is not null) { isFilterHiddenSpecified = evaluator.ExistsInExpression(FileAttributes.Hidden); } - if (switchEvaluator != null) + if (switchEvaluator is not null) { isSwitchFilterHiddenSpecified = switchEvaluator.ExistsInExpression(FileAttributes.Hidden); } @@ -2314,7 +2314,7 @@ protected override void NewItem( FileAccess.Write, FileShare.None)) { - if (value != null) + if (value is not null) { StreamWriter streamWriter = new StreamWriter(newFile); streamWriter.Write(value.ToString()); @@ -2385,7 +2385,7 @@ protected override void NewItem( } else { - exists = GetFileSystemInfo(strTargetPath, out isDirectory) != null; + exists = GetFileSystemInfo(strTargetPath, out isDirectory) is not null; } } catch (Exception e) @@ -2417,7 +2417,7 @@ protected override void NewItem( try { - symLinkExists = GetFileSystemInfo(path, out isSymLinkDirectory) != null; + symLinkExists = GetFileSystemInfo(path, out isSymLinkDirectory) is not null; } catch (Exception e) { @@ -2552,7 +2552,7 @@ protected override void NewItem( try { - exists = GetFileSystemInfo(strTargetPath, out isDirectory) != null; + exists = GetFileSystemInfo(strTargetPath, out isDirectory) is not null; } catch (Exception e) { @@ -2588,7 +2588,7 @@ protected override void NewItem( return; } - bool pathExists = pathDirInfo != null; + bool pathExists = pathDirInfo is not null; if (pathExists) { @@ -2793,7 +2793,7 @@ private void CreateDirectory(string path, bool streamOutput) return; } - if (error != null) + if (error is not null) { WriteError(error); return; @@ -2856,7 +2856,7 @@ private bool CreateIntermediateDirectories(string path) { string root = string.Empty; - if (PSDriveInfo != null) + if (PSDriveInfo is not null) { root = PSDriveInfo.Root; } @@ -2942,12 +2942,12 @@ protected override void RemoveItem(string path, bool recurse) bool removeStreams = false; FileSystemProviderRemoveItemDynamicParameters dynamicParameters = null; - if (DynamicParameters != null) + if (DynamicParameters is not null) { dynamicParameters = DynamicParameters as FileSystemProviderRemoveItemDynamicParameters; - if (dynamicParameters != null) + if (dynamicParameters is not null) { - if ((dynamicParameters.Stream != null) && (dynamicParameters.Stream.Length > 0)) + if ((dynamicParameters.Stream is not null) && (dynamicParameters.Stream.Length > 0)) { removeStreams = true; } @@ -3090,7 +3090,7 @@ protected override object RemoveItemDynamicParameters(string path, bool recurse) /// private void RemoveDirectoryInfoItem(DirectoryInfo directory, bool recurse, bool force, bool rootOfRemoval) { - Dbg.Diagnostics.Assert(directory != null, "Caller should always check directory"); + Dbg.Diagnostics.Assert(directory is not null, "Caller should always check directory"); bool continueRemoval = true; @@ -3136,7 +3136,7 @@ private void RemoveDirectoryInfoItem(DirectoryInfo directory, bool recurse, bool return; } - if (childDir != null) + if (childDir is not null) { RemoveDirectoryInfoItem(childDir, recurse, force, false); } @@ -3162,7 +3162,7 @@ private void RemoveDirectoryInfoItem(DirectoryInfo directory, bool recurse, bool return; } - if (file != null) + if (file is not null) { if (recurse) { @@ -3209,7 +3209,7 @@ private void RemoveDirectoryInfoItem(DirectoryInfo directory, bool recurse, bool private void RemoveFileInfoItem(FileInfo file, bool force) { Dbg.Diagnostics.Assert( - file != null, + file is not null, "Caller should always check file"); string action = FileSystemProviderStrings.RemoveItemActionFile; @@ -3234,7 +3234,7 @@ private void RemoveFileInfoItem(FileInfo file, bool force) private void RemoveFileSystemItem(FileSystemInfo fileSystemInfo, bool force) { Dbg.Diagnostics.Assert( - fileSystemInfo != null, + fileSystemInfo is not null, "Caller should always check fileSystemInfo"); // First check if we can delete this file when force is not specified. @@ -3373,7 +3373,7 @@ protected override bool ItemExists(string path) ErrorRecord error = null; bool result = ItemExists(path, out error); - if (error != null) + if (error is not null) { WriteError(error); } @@ -3414,13 +3414,13 @@ private bool ItemExists(string path, out ErrorRecord error) try { var fsinfo = GetFileSystemInfo(path, out bool _); - result = fsinfo != null; + result = fsinfo is not null; FileSystemItemProviderDynamicParameters itemExistsDynamicParameters = DynamicParameters as FileSystemItemProviderDynamicParameters; // If the items see if we need to check the age of the file... - if (result && itemExistsDynamicParameters != null) + if (result && itemExistsDynamicParameters is not null) { DateTime lastWriteTime = fsinfo.LastWriteTime; @@ -3562,7 +3562,7 @@ protected override bool HasChildItems(string path) private static bool DirectoryInfoHasChildItems(DirectoryInfo directory) { Dbg.Diagnostics.Assert( - directory != null, + directory is not null, "The caller should verify directory."); bool result = false; @@ -3623,9 +3623,9 @@ protected override void CopyItem( CopyItemDynamicParameters copyDynamicParameter = DynamicParameters as CopyItemDynamicParameters; - if (copyDynamicParameter != null) + if (copyDynamicParameter is not null) { - if (copyDynamicParameter.FromSession != null) + if (copyDynamicParameter.FromSession is not null) { fromSession = copyDynamicParameter.FromSession; } @@ -3647,14 +3647,14 @@ protected override void CopyItem( return; } // Copy-Item from session - if (fromSession != null) + if (fromSession is not null) { CopyItemFromRemoteSession(path, destinationPath, recurse, Force, fromSession); } else { // Copy-Item to session - if (toSession != null) + if (toSession is not null) { using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create()) { @@ -3700,7 +3700,7 @@ private void CopyItemFromRemoteSession(string path, string destinationPath, bool throw PSTraceSource.NewArgumentNullException(SessionStateStrings.PathNotFound, path); } - if (op["Items"] != null) + if (op["Items"] is not null) { PSObject obj = (PSObject)op["Items"]; ArrayList itemsList = (ArrayList)obj.BaseObject; @@ -3789,7 +3789,7 @@ private void CopyDirectoryInfoItem( System.Management.Automation.PowerShell ps) { Dbg.Diagnostics.Assert( - directory != null, + directory is not null, "The caller should verify directory."); // Generate the path based on whether the destination path exists and @@ -3870,7 +3870,7 @@ private void CopyDirectoryInfoItem( return; } - if (file != null) + if (file is not null) { try { @@ -3902,7 +3902,7 @@ private void CopyDirectoryInfoItem( return; } - if (childDir != null) + if (childDir is not null) { try { @@ -3930,7 +3930,7 @@ private void CopyDirectoryInfoItem( private void CopyFileInfoItem(FileInfo file, string destinationPath, bool force, System.Management.Automation.PowerShell ps) { Dbg.Diagnostics.Assert( - file != null, + file is not null, "The caller should verify file."); // If the destination is a container, add the file name @@ -4050,7 +4050,7 @@ private void CopyDirectoryFromRemoteSession( bool recurse, System.Management.Automation.PowerShell ps) { - Dbg.Diagnostics.Assert((sourceDirectoryName != null && sourceDirectoryFullName != null), "The caller should verify directory."); + Dbg.Diagnostics.Assert((sourceDirectoryName is not null && sourceDirectoryFullName is not null), "The caller should verify directory."); if (IsItemContainer(destination)) { @@ -4092,7 +4092,7 @@ private void CopyDirectoryFromRemoteSession( return; } - if (op["Files"] != null) + if (op["Files"] is not null) { PSObject obj = (PSObject)op["Files"]; ArrayList filesList = (ArrayList)obj.BaseObject; @@ -4125,7 +4125,7 @@ private void CopyDirectoryFromRemoteSession( } } - if (op["Directories"] != null) + if (op["Directories"] is not null) { PSObject obj = (PSObject)op["Directories"]; ArrayList directories = (ArrayList)obj.BaseObject; @@ -4164,7 +4164,7 @@ private ArrayList GetRemoteSourceAlternateStreams(System.Management.Automation.P ps.AddParameter("supportAltStreamPath", path); Hashtable op = SafeInvokeCommand.Invoke(ps, this, null); - if (op != null && op["SourceSupportsAlternateStreams"] != null) + if (op is not null && op["SourceSupportsAlternateStreams"] is not null) { supportsAlternateStreams = (bool)op["SourceSupportsAlternateStreams"]; } @@ -4235,21 +4235,21 @@ private void SetFileMetadata(string sourceFileFullName, FileInfo destinationFile { Hashtable metadata = GetRemoteFileMetadata(sourceFileFullName, ps); - if (metadata != null) + if (metadata is not null) { // LastWriteTime - if (metadata["LastWriteTimeUtc"] != null) + if (metadata["LastWriteTimeUtc"] is not null) { destinationFile.LastWriteTimeUtc = (DateTime)metadata["LastWriteTimeUtc"]; } - if (metadata["LastWriteTime"] != null) + if (metadata["LastWriteTime"] is not null) { destinationFile.LastWriteTime = (DateTime)metadata["LastWriteTime"]; } // Attributes - if (metadata["Attributes"] != null) + if (metadata["Attributes"] is not null) { PSObject obj = (PSObject)metadata["Attributes"]; foreach (string value in (ArrayList)obj.BaseObject) @@ -4283,7 +4283,7 @@ private void CopyFileFromRemoteSession( System.Management.Automation.PowerShell ps, long fileSize = 0) { - Dbg.Diagnostics.Assert(sourceFileFullName != null, "The caller should verify file."); + Dbg.Diagnostics.Assert(sourceFileFullName is not null, "The caller should verify file."); // If the destination is a container, add the file name // to the destination path. @@ -4312,7 +4312,7 @@ private void CopyFileFromRemoteSession( { // Check if the remote source file has any alternate data streams ArrayList remoteFileStreams = GetRemoteSourceAlternateStreams(ps, sourceFileFullName); - if ((remoteFileStreams != null) && (remoteFileStreams.Count > 0)) + if ((remoteFileStreams is not null) && (remoteFileStreams.Count > 0)) { foreach (string streamName in remoteFileStreams) { @@ -4410,7 +4410,7 @@ private bool PerformCopyFileFromRemoteSession(string sourceFileFullName, FileInf break; } - if (op["ExceptionThrown"] != null) + if (op["ExceptionThrown"] is not null) { bool failedToReadFile = (bool)(op["ExceptionThrown"]); if (failedToReadFile) @@ -4423,7 +4423,7 @@ private bool PerformCopyFileFromRemoteSession(string sourceFileFullName, FileInf // To accomodate empty files string content = string.Empty; - if (op["b64Fragment"] != null) + if (op["b64Fragment"] is not null) { content = (string)op["b64Fragment"]; } @@ -4475,7 +4475,7 @@ private bool PerformCopyFileFromRemoteSession(string sourceFileFullName, FileInf } finally { - if (wStream != null) + if (wStream is not null) { wStream.Dispose(); } @@ -4526,7 +4526,7 @@ private bool RemoteTargetSupportsAlternateStreams(System.Management.Automation.P ps.AddParameter("supportAltStreamPath", path); Hashtable op = SafeInvokeCommand.Invoke(ps, this, null); - if (op != null && op["TargetSupportsAlternateStreams"] != null) + if (op is not null && op["TargetSupportsAlternateStreams"] is not null) { supportsAlternateStreams = (bool)op["TargetSupportsAlternateStreams"]; } @@ -4550,19 +4550,19 @@ private string MakeRemotePath(System.Management.Automation.PowerShell ps, string ps.AddParameter(nameof(remotePath), remotePath); Hashtable op = SafeInvokeCommand.Invoke(ps, this, null); - if (op != null) + if (op is not null) { - if (op["IsDirectoryInfo"] != null) + if (op["IsDirectoryInfo"] is not null) { isDirectoryInfo = (bool)op["IsDirectoryInfo"]; } - if (op["IsFileInfo"] != null) + if (op["IsFileInfo"] is not null) { isFileInfo = (bool)op["IsFileInfo"]; } - if (op["ParentIsDirectoryInfo"] != null) + if (op["ParentIsDirectoryInfo"] is not null) { parentIsDirectoryInfo = (bool)op["ParentIsDirectoryInfo"]; } @@ -4599,9 +4599,9 @@ private bool RemoteDirectoryExist(System.Management.Automation.PowerShell ps, st ps.AddParameter("dirPathExists", path); Hashtable op = SafeInvokeCommand.Invoke(ps, this, null); - if (op != null) + if (op is not null) { - if (op["Exists"] != null) + if (op["Exists"] is not null) pathExists = (bool)op["Exists"]; } @@ -4644,7 +4644,7 @@ private bool CopyFileStreamToRemoteSession(FileInfo file, string destinationPath fStream = AlternateDataStreamUtilities.CreateFileStream(file.FullName, streamName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); } #endif - long remainingFileSize = fStream != null ? fStream.Length : 0; + long remainingFileSize = fStream is not null ? fStream.Length : 0; do { if (Stopping) @@ -4758,7 +4758,7 @@ private bool CopyFileStreamToRemoteSession(FileInfo file, string destinationPath } finally { - if (fStream != null) + if (fStream is not null) { fStream.Dispose(); } @@ -4786,7 +4786,7 @@ private Hashtable GetFileMetadata(FileInfo file) private void SetRemoteFileMetadata(FileInfo file, string remoteFilePath, System.Management.Automation.PowerShell ps) { Hashtable metadata = GetFileMetadata(file); - if (metadata != null) + if (metadata is not null) { ps.AddCommand(CopyFileRemoteUtils.PSCopyToSessionHelperName); ps.AddParameter("metaDataFilePath", remoteFilePath); @@ -4868,7 +4868,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["ExceptionThrown"] != null) + if (op["ExceptionThrown"] is not null) { // If an error is thrown on the remote session, it is written via SafeInvokeCommand.Invoke. if ((bool)op["ExceptionThrown"]) @@ -5596,7 +5596,7 @@ private Stack NormalizeThePath(string basepath, Stack tokenizedP // Clean up the child name to proper casing and short-path // expansion if required. Also verify that .NET hasn't over-normalized // the path - if (fsinfo != null) + if (fsinfo is not null) { // This might happen if you've passed a child name of two or more dots, // which the .NET APIs treat as the parent directory @@ -5828,7 +5828,7 @@ protected override void MoveItem( FileInfo file = new FileInfo(path); Dbg.Diagnostics.Assert( - file != null, + file is not null, "FileInfo should be throwing an exception but it's " + "returning null instead"); @@ -5873,7 +5873,7 @@ private void MoveFileInfoItem( bool output) { Dbg.Diagnostics.Assert( - file != null, + file is not null, "The caller should verify file."); Dbg.Diagnostics.Assert( @@ -5945,7 +5945,7 @@ private void MoveFileInfoItem( if (force && File.Exists(destination)) { FileInfo destfile = new FileInfo(destination); - if (destfile != null) + if (destfile is not null) { try { @@ -5998,7 +5998,7 @@ private void MoveDirectoryInfoItem( bool force) { Dbg.Diagnostics.Assert( - directory != null, + directory is not null, "The caller should verify directory."); Dbg.Diagnostics.Assert( @@ -6201,14 +6201,14 @@ public void GetProperty(string path, Collection providerSpecificPickList { foreach (string property in providerSpecificPickList) { - if (property != null && property.Length > 0) + if (property is not null && property.Length > 0) { try { PSObject mshObject = PSObject.AsPSObject(fileSystemObject); PSMemberInfo member = mshObject.Properties[property]; object value; - if (member != null) + if (member is not null) { value = member.Value; if (result is null) @@ -6251,7 +6251,7 @@ public void GetProperty(string path, Collection providerSpecificPickList WriteError(new ErrorRecord(accessException, "GetPropertyUnauthorizedAccessError", ErrorCategory.PermissionDenied, path)); } - if (result != null) + if (result is not null) { WritePropertyObject(result, path); } @@ -6317,7 +6317,7 @@ public void SetProperty(string path, PSObject propertyToSet) var fsinfo = GetFileSystemInfo(path, out bool isDirectory); // Create a PSObject with either a DirectoryInfo or FileInfo object at its core. - if (fsinfo != null) + if (fsinfo is not null) { PSObject fileSystemInfoShell = PSObject.AsPSObject(fsinfo); @@ -6371,7 +6371,7 @@ public void SetProperty(string path, PSObject propertyToSet) PSObject mshObject = PSObject.AsPSObject(fileSystemInfoShell); PSMemberInfo member = mshObject.Properties[property.Name]; - if (member != null) + if (member is not null) { if (string.Equals(property.Name, "attributes", StringComparison.OrdinalIgnoreCase)) { @@ -6609,12 +6609,12 @@ public IContentReader GetContentReader(string path) // Get the dynamic parameters. // They override the defaults specified above. - if (DynamicParameters != null) + if (DynamicParameters is not null) { FileSystemContentReaderDynamicParameters dynParams = DynamicParameters as FileSystemContentReaderDynamicParameters; - if (dynParams != null) + if (dynParams is not null) { // -raw is not allowed when -first,-last or -wait is specified // this call will validate that and throws. @@ -6779,12 +6779,12 @@ public IContentWriter GetContentWriter(string path) bool suppressNewline = false; // Get the dynamic parameters - if (DynamicParameters != null) + if (DynamicParameters is not null) { FileSystemContentWriterDynamicParameters dynParams = DynamicParameters as FileSystemContentWriterDynamicParameters; - if (dynParams != null) + if (dynParams is not null) { usingByteEncoding = dynParams.AsByteStream; streamTypeSpecified = dynParams.WasStreamTypeSpecified; @@ -6917,20 +6917,20 @@ public void ClearContent(string path) // We get called during: // - Clear-Content // - Set-Content, in the phase that clears the path first. - if (DynamicParameters != null) + if (DynamicParameters is not null) { dynamicParameters = DynamicParameters as FileSystemClearContentDynamicParameters; writerDynamicParameters = DynamicParameters as FileSystemContentWriterDynamicParameters; - if (dynamicParameters != null) + if (dynamicParameters is not null) { - if ((dynamicParameters.Stream != null) && (dynamicParameters.Stream.Length > 0)) + if ((dynamicParameters.Stream is not null) && (dynamicParameters.Stream.Length > 0)) clearStream = true; streamName = dynamicParameters.Stream; } - else if (writerDynamicParameters != null) + else if (writerDynamicParameters is not null) { - if ((writerDynamicParameters.Stream != null) && (writerDynamicParameters.Stream.Length > 0)) + if ((writerDynamicParameters.Stream is not null) && (writerDynamicParameters.Stream.Length > 0)) clearStream = true; streamName = writerDynamicParameters.Stream; } @@ -6969,7 +6969,7 @@ public void ClearContent(string path) { // If we've been called as part of Clear-Content, validate that the stream exists. // This is because the core API doesn't support truncate mode. - if (dynamicParameters != null) + if (dynamicParameters is not null) { fileStream = AlternateDataStreamUtilities.CreateFileStream(path, streamName, FileMode.Open, FileAccess.Write, FileShare.Write); fileStream.Dispose(); @@ -7428,7 +7428,7 @@ public static Hashtable Invoke(System.Management.Automation.PowerShell ps, FileS if (useFileSystemProviderContext) { - Dbg.Diagnostics.Assert(fileSystemContext != null, "The caller should verify FileSystemProvider context."); + Dbg.Diagnostics.Assert(fileSystemContext is not null, "The caller should verify FileSystemProvider context."); } Collection output; @@ -7474,7 +7474,7 @@ public static Hashtable Invoke(System.Management.Automation.PowerShell ps, FileS if (output.Count != 1 || output[0].GetType() != typeof(Hashtable)) { // unexpected output - Dbg.Diagnostics.Assert(output[0] != null, "Expected an output from the remote call."); + Dbg.Diagnostics.Assert(output[0] is not null, "Expected an output from the remote call."); return null; } @@ -8083,7 +8083,7 @@ public static string GetLinkType(PSObject instance) { FileSystemInfo fileSysInfo = instance.BaseObject as FileSystemInfo; - if (fileSysInfo != null) + if (fileSysInfo is not null) { return InternalGetLinkType(fileSysInfo); } @@ -8422,7 +8422,7 @@ private static string WinInternalGetTarget(SafeFileHandle handle) return null; } - if (targetDir != null && targetDir.StartsWith(NonInterpretedPathPrefix, StringComparison.OrdinalIgnoreCase)) + if (targetDir is not null && targetDir.StartsWith(NonInterpretedPathPrefix, StringComparison.OrdinalIgnoreCase)) { targetDir = targetDir.Substring(NonInterpretedPathPrefix.Length); } diff --git a/src/System.Management.Automation/namespaces/FunctionProvider.cs b/src/System.Management.Automation/namespaces/FunctionProvider.cs index f042e973f0d..7047e9bafc3 100644 --- a/src/System.Management.Automation/namespaces/FunctionProvider.cs +++ b/src/System.Management.Automation/namespaces/FunctionProvider.cs @@ -158,7 +158,7 @@ internal override void SetSessionStateItem(string name, object value, bool write CommandInfo modifiedItem = null; - bool dynamicParametersSpecified = dynamicParameters != null && dynamicParameters.OptionsSet; + bool dynamicParametersSpecified = dynamicParameters is not null && dynamicParameters.OptionsSet; if (value is null) { @@ -170,7 +170,7 @@ internal override void SetSessionStateItem(string name, object value, bool write { modifiedItem = (CommandInfo)GetSessionStateItem(name); - if (modifiedItem != null) + if (modifiedItem is not null) { SetOptions(modifiedItem, dynamicParameters.Options); } @@ -186,13 +186,13 @@ internal override void SetSessionStateItem(string name, object value, bool write { // Unwrap the PSObject before binding it as a scriptblock... PSObject pso = value as PSObject; - if (pso != null) + if (pso is not null) { value = pso.BaseObject; } ScriptBlock scriptBlockValue = value as ScriptBlock; - if (scriptBlockValue != null) + if (scriptBlockValue is not null) { if (dynamicParametersSpecified) { @@ -208,7 +208,7 @@ internal override void SetSessionStateItem(string name, object value, bool write } FunctionInfo function = value as FunctionInfo; - if (function != null) + if (function is not null) { ScopedItemOptions options = function.Options; @@ -222,7 +222,7 @@ internal override void SetSessionStateItem(string name, object value, bool write } string stringValue = value as string; - if (stringValue != null) + if (stringValue is not null) { ScriptBlock scriptBlock = ScriptBlock.Create(Context.ExecutionContext, stringValue); @@ -241,7 +241,7 @@ internal override void SetSessionStateItem(string name, object value, bool write throw PSTraceSource.NewArgumentException(nameof(value)); } while (false); - if (writeItem && modifiedItem != null) + if (writeItem && modifiedItem is not null) { WriteItemObject(modifiedItem, modifiedItem.Name, false); } @@ -286,13 +286,13 @@ internal override void RemoveSessionStateItem(string name) internal override object GetValueOfItem(object item) { Dbg.Diagnostics.Assert( - item != null, + item is not null, "Caller should verify the item parameter"); object value = item; FunctionInfo function = item as FunctionInfo; - if (function != null) + if (function is not null) { value = function.ScriptBlock; } @@ -327,7 +327,7 @@ internal override bool CanRenameItem(object item) bool result = false; FunctionInfo functionInfo = item as FunctionInfo; - if (functionInfo != null) + if (functionInfo is not null) { if ((functionInfo.Options & ScopedItemOptions.Constant) != 0 || ((functionInfo.Options & ScopedItemOptions.ReadOnly) != 0 && !Force)) diff --git a/src/System.Management.Automation/namespaces/LocationGlobber.cs b/src/System.Management.Automation/namespaces/LocationGlobber.cs index b238ed967aa..cad45e0f8b6 100644 --- a/src/System.Management.Automation/namespaces/LocationGlobber.cs +++ b/src/System.Management.Automation/namespaces/LocationGlobber.cs @@ -273,7 +273,7 @@ out CmdletProvider providerInstance // Only do the expansion if the path actually contains wildcard // characters. - if ((itemProvider != null) && + if ((itemProvider is not null) && (WildcardPattern.ContainsWildcardCharacters(providerPath))) { stringResult = new Collection(itemProvider.ExpandPath(providerPath, context)); @@ -287,7 +287,7 @@ out CmdletProvider providerInstance { s_pathResolutionTracer.WriteLine("Wildcard matching is being performed by the engine."); - if (containerCmdletProvider != null) + if (containerCmdletProvider is not null) { // Since it is really a provider-internal path, use provider-to-provider globbing // and then add back on the provider ID. @@ -310,7 +310,7 @@ out CmdletProvider providerInstance // They are suppressing wildcard expansion else { - if (itemProvider != null) + if (itemProvider is not null) { if (allowNonexistingPaths || itemProvider.ItemExists(providerPath, context)) { @@ -444,11 +444,11 @@ private Collection ResolveDriveQualifiedPath( out providerInstance); Dbg.Diagnostics.Assert( - drive != null, + drive is not null, "GetDriveRootRelativePathFromPSPath should always return a valid drive"); Dbg.Diagnostics.Assert( - relativePath != null, + relativePath is not null, "There should always be a way to generate a provider path for a " + "given path"); @@ -494,7 +494,7 @@ private Collection ResolveDriveQualifiedPath( // Only do the expansion if the path actually contains wildcard // characters. - if ((itemProvider != null) && + if ((itemProvider is not null) && (WildcardPattern.ContainsWildcardCharacters(relativePath))) { foreach (string pathResult in itemProvider.ExpandPath(itemPath, context)) @@ -525,7 +525,7 @@ private Collection ResolveDriveQualifiedPath( // They are suppressing wildcard expansion else { - if (itemProvider != null) + if (itemProvider is not null) { if (allowNonexistingPaths || itemProvider.ItemExists(itemPath, context)) { @@ -768,7 +768,7 @@ internal Collection GetGlobbedProviderPathsFromMonadPath( return new Collection(); } - if (drive != null) + if (drive is not null) { context.Drive = drive; } @@ -868,7 +868,7 @@ internal Collection GetGlobbedProviderPathsFromProviderPath( // Throw the first error ErrorRecord errorRecord = context.GetAccumulatedErrorObjects()[0]; - if (errorRecord != null) + if (errorRecord is not null) { throw errorRecord.Exception; } @@ -1072,7 +1072,7 @@ internal string GetProviderPath(string path, out ProviderInfo provider) { Collection errors = context.GetAccumulatedErrorObjects(); - if (errors != null && + if (errors is not null && errors.Count > 0) { throw errors[0].Exception; @@ -1274,11 +1274,11 @@ internal string GetProviderPath( string relativePath = GetDriveRootRelativePathFromPSPath(path, context, false, out drive, out providerInstance); Dbg.Diagnostics.Assert( - drive != null, + drive is not null, "GetDriveRootRelativePathFromPSPath should always return a valid drive"); Dbg.Diagnostics.Assert( - relativePath != null, + relativePath is not null, "There should always be a way to generate a provider path for a " + "given path"); @@ -1305,11 +1305,11 @@ internal string GetProviderPath( s_pathResolutionTracer.WriteLine("RESOLVED PATH: {0}", result); // If this is a private provider, don't allow access to it directly from the runspace. - if ((provider != null) && - (context != null) && - (context.MyInvocation != null) && - (context.ExecutionContext != null) && - (context.ExecutionContext.InitialSessionState != null)) + if ((provider is not null) && + (context is not null) && + (context.MyInvocation is not null) && + (context.ExecutionContext is not null) && + (context.ExecutionContext.InitialSessionState is not null)) { foreach (Runspaces.SessionStateProviderEntry sessionStateProvider in context.ExecutionContext.InitialSessionState.Providers[provider.Name]) { @@ -1566,7 +1566,7 @@ internal bool IsAbsolutePath(string path, out string driveName) bool result = false; - if (_sessionState.Drive.Current != null) + if (_sessionState.Drive.Current is not null) { driveName = _sessionState.Drive.Current.Name; } @@ -1632,7 +1632,7 @@ internal bool IsAbsolutePath(string path, out string driveName) if (result) { Dbg.Diagnostics.Assert( - driveName != null, + driveName is not null, "The drive name should always have a value, " + "the default is the current working drive"); @@ -1823,7 +1823,7 @@ internal string GetDriveRootRelativePathFromPSPath( workingDriveForPath = null; string driveName = null; - if (_sessionState.Drive.Current != null) + if (_sessionState.Drive.Current is not null) { driveName = _sessionState.Drive.Current.Name; } @@ -1834,7 +1834,7 @@ internal string GetDriveRootRelativePathFromPSPath( if (IsAbsolutePath(path, out driveName)) { Dbg.Diagnostics.Assert( - driveName != null, + driveName is not null, "IsAbsolutePath should be returning the drive name"); s_tracer.WriteLine( @@ -2249,7 +2249,7 @@ internal string GenerateRelativePath( } NavigationCmdletProvider navigationProvider = providerInstance as NavigationCmdletProvider; - if (navigationProvider != null) + if (navigationProvider is not null) { string rootedPath = _sessionState.Internal.MakePath(context.Drive.Root, driveRootRelativeWorkingPath, context); string normalizedRelativePath = navigationProvider.ContractRelativePath(rootedPath, context.Drive.Root, false, context); @@ -2521,7 +2521,7 @@ internal static bool ShouldPerformGlobbing(string path, CmdletProviderContext co { bool pathContainsGlobCharacters = false; - if (path != null) + if (path is not null) { pathContainsGlobCharacters = StringContainsGlobCharacters(path); } @@ -2529,12 +2529,12 @@ internal static bool ShouldPerformGlobbing(string path, CmdletProviderContext co bool contextContainsIncludeExclude = false; bool contextContainsNoGlob = false; - if (context != null) + if (context is not null) { - bool includePresent = context.Include != null && context.Include.Count > 0; + bool includePresent = context.Include is not null && context.Include.Count > 0; s_pathResolutionTracer.WriteLine("INCLUDE filter present: {0}", includePresent); - bool excludePresent = context.Exclude != null && context.Exclude.Count > 0; + bool excludePresent = context.Exclude is not null && context.Exclude.Count > 0; s_pathResolutionTracer.WriteLine("EXCLUDE filter present: {0}", excludePresent); contextContainsIncludeExclude = includePresent || excludePresent; @@ -2687,7 +2687,7 @@ private Collection ExpandMshGlobPath( string leafElement = path; - if (navigationProvider != null) + if (navigationProvider is not null) { leafElement = navigationProvider.GetChildName(path, context); } @@ -2707,7 +2707,7 @@ private Collection ExpandMshGlobPath( // Now use the parent path for the next iteration - if (navigationProvider != null) + if (navigationProvider is not null) { // Now call GetParentPath with the root @@ -2758,7 +2758,7 @@ private Collection ExpandMshGlobPath( { string leafElement = path; - if (navigationProvider != null) + if (navigationProvider is not null) { leafElement = navigationProvider.GetChildName(path, context); @@ -2799,7 +2799,7 @@ private Collection ExpandMshGlobPath( string leafElement = leafElements.Pop(); Dbg.Diagnostics.Assert( - leafElement != null, + leafElement is not null, "I am only pushing strings onto this stack so I should be able " + "to cast any Pop to a string without failure."); @@ -2835,7 +2835,7 @@ private Collection ExpandMshGlobPath( // Check to see if the matching item is a container - if (navigationProvider != null && + if (navigationProvider is not null && !_sessionState.Internal.IsItemContainer( resolvedPath, context)) @@ -2852,7 +2852,7 @@ private Collection ExpandMshGlobPath( else if (navigationProvider is null) { Dbg.Diagnostics.Assert( - navigationProvider != null, + navigationProvider is not null, "The path in the dirs should never be a container unless " + "the provider implements the NavigationCmdletProvider interface. If it " + "doesn't, there should be no more leafElements in the stack " + @@ -2872,7 +2872,7 @@ private Collection ExpandMshGlobPath( } Dbg.Diagnostics.Assert( - dirs != null, + dirs is not null, "GenerateNewPathsWithGlobLeaf() should return the base path as an element " + "even if there are no globing characters"); @@ -2949,7 +2949,7 @@ private Collection ExpandMshGlobPath( } Dbg.Diagnostics.Assert( - result != null, + result is not null, "This method should at least return the path or more if it has glob characters"); return result; @@ -2978,7 +2978,7 @@ private Collection ExpandMshGlobPath( internal static string GetMshQualifiedPath(string path, PSDriveInfo drive) { Dbg.Diagnostics.Assert( - drive != null, + drive is not null, "The caller should verify drive before calling this method"); string result = null; @@ -3018,11 +3018,11 @@ internal static string GetMshQualifiedPath(string path, PSDriveInfo drive) internal static string RemoveMshQualifier(string path, PSDriveInfo drive) { Dbg.Diagnostics.Assert( - drive != null, + drive is not null, "The caller should verify drive before calling this method"); Dbg.Diagnostics.Assert( - path != null, + path is not null, "The caller should verify path before calling this method"); string result = null; @@ -3150,7 +3150,7 @@ internal static string GetDriveQualifiedPath(string path, PSDriveInfo drive) private static string RemoveDriveQualifier(string path) { Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should verify path"); string result = path; @@ -3252,7 +3252,7 @@ internal static string GetProviderQualifiedPath(string path, ProviderInfo provid internal static string RemoveProviderQualifier(string path) { Dbg.Diagnostics.Assert( - path != null, + path is not null, "Caller should verify path"); string result = path; @@ -3437,7 +3437,7 @@ private List GenerateNewPSPathsWithGlobLeaf( { string childPath = child; - if (navigationProvider != null) + if (navigationProvider is not null) { string parentPath = RemoveMshQualifier(mshQualifiedParentPath, drive); @@ -3484,7 +3484,7 @@ private List GenerateNewPSPathsWithGlobLeaf( string childPath = backslashEscapedLeafElement; - if (navigationProvider != null) + if (navigationProvider is not null) { string parentPath = RemoveMshQualifier(resolvedPath, drive); @@ -3645,7 +3645,7 @@ internal Collection ExpandGlobPath( string leafElement = path; - if (navigationProvider != null) + if (navigationProvider is not null) { leafElement = navigationProvider.GetChildName(path, context); } @@ -3665,17 +3665,17 @@ internal Collection ExpandGlobPath( // Now use the parent path for the next iteration - if (navigationProvider != null) + if (navigationProvider is not null) { // See if we can get the root from the context string root = string.Empty; - if (context != null) + if (context is not null) { PSDriveInfo drive = context.Drive; - if (drive != null) + if (drive is not null) { root = drive.Root; } @@ -3729,7 +3729,7 @@ internal Collection ExpandGlobPath( { string leafElement = path; - if (navigationProvider != null) + if (navigationProvider is not null) { leafElement = navigationProvider.GetChildName(path, context); @@ -3768,7 +3768,7 @@ internal Collection ExpandGlobPath( string leafElement = leafElements.Pop(); Dbg.Diagnostics.Assert( - leafElement != null, + leafElement is not null, "I am only pushing strings onto this stack so I should be able " + "to cast any Pop to a string without failure."); @@ -3800,7 +3800,7 @@ internal Collection ExpandGlobPath( // Check to see if the matching item is a container - if (navigationProvider != null && + if (navigationProvider is not null && !navigationProvider.IsItemContainer( dirs[index], context)) @@ -3817,7 +3817,7 @@ internal Collection ExpandGlobPath( else if (navigationProvider is null) { Dbg.Diagnostics.Assert( - navigationProvider != null, + navigationProvider is not null, "The path in the dirs should never be a container unless " + "the provider implements the NavigationCmdletProvider interface. If it " + "doesn't, there should be no more leafElements in the stack " + @@ -3837,7 +3837,7 @@ internal Collection ExpandGlobPath( } Dbg.Diagnostics.Assert( - dirs != null, + dirs is not null, "GenerateNewPathsWithGlobLeaf() should return the base path as an element " + "even if there are no globing characters"); @@ -3878,7 +3878,7 @@ internal Collection ExpandGlobPath( } Dbg.Diagnostics.Assert( - result != null, + result is not null, "This method should at least return the path or more if it has glob characters"); if (changedPathOrFilter) @@ -4029,7 +4029,7 @@ internal List GenerateNewPathsWithGlobLeaf( { string childPath = child; - if (navigationProvider != null) + if (navigationProvider is not null) { childPath = navigationProvider.MakePath(unescapedDir, child, context); } @@ -4066,7 +4066,7 @@ internal List GenerateNewPathsWithGlobLeaf( string childPath = backslashEscapedLeafElement; - if (navigationProvider != null) + if (navigationProvider is not null) { childPath = navigationProvider. @@ -4220,7 +4220,7 @@ private Collection GetChildNamesInDir( else { Dbg.Diagnostics.Assert( - drive != null, + drive is not null, "Caller should verify that drive is not null when dirIsProviderPath is false"); // If the directory is an MSH path we must resolve it before calling GetChildNames() @@ -4278,7 +4278,7 @@ private Collection GetChildNamesInDir( { Collection errors = getChildNamesContext.GetAccumulatedErrorObjects(); - if (errors != null && + if (errors is not null && errors.Count > 0) { foreach (ErrorRecord errorRecord in errors) @@ -4613,7 +4613,7 @@ internal string GetHomeRelativePath(string path) string result = path; - if (IsHomePath(path) && _sessionState.Drive.Current != null) + if (IsHomePath(path) && _sessionState.Drive.Current is not null) { ProviderInfo provider = _sessionState.Drive.Current.Provider; @@ -4653,7 +4653,7 @@ internal string GetHomeRelativePath(string path) // Now piece together the provider's home path and the remaining // portion of the passed in path - if (provider.Home != null && + if (provider.Home is not null && provider.Home.Length > 0) { CmdletProviderContext context = @@ -4698,7 +4698,7 @@ private static void TraceFilters(CmdletProviderContext context) // Trace the filter s_pathResolutionTracer.WriteLine("Filter: {0}", context.Filter ?? string.Empty); - if (context.Include != null) + if (context.Include is not null) { // Trace the include filters StringBuilder includeString = new StringBuilder(); @@ -4710,7 +4710,7 @@ private static void TraceFilters(CmdletProviderContext context) s_pathResolutionTracer.WriteLine("Include: {0}", includeString.ToString()); } - if (context.Exclude != null) + if (context.Exclude is not null) { // Trace the exclude filters StringBuilder excludeString = new StringBuilder(); diff --git a/src/System.Management.Automation/namespaces/NavigationProviderBase.cs b/src/System.Management.Automation/namespaces/NavigationProviderBase.cs index 62ce17619e5..d642cf29e2e 100644 --- a/src/System.Management.Automation/namespaces/NavigationProviderBase.cs +++ b/src/System.Management.Automation/namespaces/NavigationProviderBase.cs @@ -412,7 +412,7 @@ protected virtual string GetParentPath(string path, string root) if (root is null) { - if (PSDriveInfo != null) + if (PSDriveInfo is not null) { root = PSDriveInfo.Root; } @@ -424,7 +424,7 @@ protected virtual string GetParentPath(string path, string root) path = path.TrimEnd(StringLiterals.DefaultPathSeparator); string rootPath = string.Empty; - if (root != null) + if (root is not null) { rootPath = NormalizePath(root); } @@ -923,7 +923,7 @@ private bool IsAbsolutePath(string path) { result = true; } - else if (this.PSDriveInfo != null && !string.IsNullOrEmpty(this.PSDriveInfo.Root) && + else if (this.PSDriveInfo is not null && !string.IsNullOrEmpty(this.PSDriveInfo.Root) && path.StartsWith(this.PSDriveInfo.Root, StringComparison.OrdinalIgnoreCase)) { result = true; diff --git a/src/System.Management.Automation/namespaces/PathInfo.cs b/src/System.Management.Automation/namespaces/PathInfo.cs index 4e8720253ed..478d9155a40 100644 --- a/src/System.Management.Automation/namespaces/PathInfo.cs +++ b/src/System.Management.Automation/namespaces/PathInfo.cs @@ -19,7 +19,7 @@ public PSDriveInfo Drive { PSDriveInfo result = null; - if (_drive != null && + if (_drive is not null && !_drive.Hidden) { result = _drive; diff --git a/src/System.Management.Automation/namespaces/ProviderBase.cs b/src/System.Management.Automation/namespaces/ProviderBase.cs index 47cf392f4f8..26b6faaaefe 100644 --- a/src/System.Management.Automation/namespaces/ProviderBase.cs +++ b/src/System.Management.Automation/namespaces/ProviderBase.cs @@ -142,7 +142,7 @@ internal CmdletProviderContext Context } // Check that the provider supports the use of credentials - if (value.Credential != null && + if (value.Credential is not null && value.Credential != PSCredential.Empty && !CmdletProviderManagementIntrinsics.CheckProviderCapabilities(ProviderCapabilities.Credentials, _providerInformation)) { @@ -151,8 +151,8 @@ internal CmdletProviderContext Context } // Supplying Credentials for the FileSystemProvider is supported only for New-PSDrive Command. - if (_providerInformation != null && !string.IsNullOrEmpty(_providerInformation.Name) && _providerInformation.Name.Equals("FileSystem") && - value.Credential != null && + if (_providerInformation is not null && !string.IsNullOrEmpty(_providerInformation.Name) && _providerInformation.Name.Equals("FileSystem") && + value.Credential is not null && value.Credential != PSCredential.Empty && !value.ExecutionContext.CurrentCommandProcessor.Command.GetType().Name.Equals("NewPSDriveCommand")) { @@ -1148,7 +1148,7 @@ public bool Stopping using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( - Context != null, + Context is not null, "The context should always be set"); return Context.Stopping; @@ -1166,7 +1166,7 @@ public SessionState SessionState using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( - Context != null, + Context is not null, "The context should always be set"); return new SessionState(Context.ExecutionContext.EngineSessionState); @@ -1184,7 +1184,7 @@ public ProviderIntrinsics InvokeProvider using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( - Context != null, + Context is not null, "The context should always be set"); return new ProviderIntrinsics(Context.ExecutionContext.EngineSessionState); @@ -1202,7 +1202,7 @@ public CommandInvocationIntrinsics InvokeCommand using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( - Context != null, + Context is not null, "The context should always be set"); return new CommandInvocationIntrinsics(Context.ExecutionContext); @@ -1220,7 +1220,7 @@ public PSCredential Credential using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( - Context != null, + Context is not null, "The context should always be set"); return Context.Credential; @@ -1257,7 +1257,7 @@ protected PSDriveInfo PSDriveInfo using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( - Context != null, + Context is not null, "The context should always be set"); return Context.Drive; @@ -1276,7 +1276,7 @@ protected object DynamicParameters using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( - Context != null, + Context is not null, "The context should always be set"); return Context.DynamicParameters; @@ -1303,7 +1303,7 @@ public SwitchParameter Force using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( - Context != null, + Context is not null, "The context should always be set"); return Context.Force; @@ -1321,7 +1321,7 @@ public string Filter using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( - Context != null, + Context is not null, "The context should always be set"); return Context.Filter; @@ -1340,7 +1340,7 @@ public Collection Include using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( - Context != null, + Context is not null, "The context should always be set"); return Context.Include; @@ -1359,7 +1359,7 @@ public Collection Exclude using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( - Context != null, + Context is not null, "The context should always be set"); return Context.Exclude; @@ -1377,7 +1377,7 @@ public PSHost Host using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( - Context != null, + Context is not null, "The context should always be set"); return Context.ExecutionContext.EngineHostInterface; @@ -1471,8 +1471,8 @@ public void ThrowTerminatingError(ErrorRecord errorRecord) throw PSTraceSource.NewArgumentNullException(nameof(errorRecord)); } - if (errorRecord.ErrorDetails != null - && errorRecord.ErrorDetails.TextLookupError != null) + if (errorRecord.ErrorDetails is not null + && errorRecord.ErrorDetails.TextLookupError is not null) { Exception textLookupError = errorRecord.ErrorDetails.TextLookupError; errorRecord.ErrorDetails.TextLookupError = null; @@ -1513,7 +1513,7 @@ public bool ShouldProcess( using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( - Context != null, + Context is not null, "The context should always be set"); return Context.ShouldProcess(target); @@ -1528,7 +1528,7 @@ public bool ShouldProcess( using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( - Context != null, + Context is not null, "The context should always be set"); return Context.ShouldProcess(target, action); @@ -1544,7 +1544,7 @@ public bool ShouldProcess( using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( - Context != null, + Context is not null, "The context should always be set"); return Context.ShouldProcess( @@ -1564,7 +1564,7 @@ public bool ShouldProcess( using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( - Context != null, + Context is not null, "The context should always be set"); return Context.ShouldProcess( @@ -1583,7 +1583,7 @@ public bool ShouldContinue( using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( - Context != null, + Context is not null, "The context should always be set"); return Context.ShouldContinue(query, caption); @@ -1600,7 +1600,7 @@ public bool ShouldContinue( using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( - Context != null, + Context is not null, "The context should always be set"); return Context.ShouldContinue( @@ -1646,7 +1646,7 @@ public void WriteVerbose(string text) using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( - Context != null, + Context is not null, "The context should always be set"); Context.WriteVerbose(text); @@ -1659,7 +1659,7 @@ public void WriteWarning(string text) using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( - Context != null, + Context is not null, "The context should always be set"); Context.WriteWarning(text); @@ -1672,7 +1672,7 @@ public void WriteProgress(ProgressRecord progressRecord) using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( - Context != null, + Context is not null, "The context should always be set"); if (progressRecord is null) @@ -1690,7 +1690,7 @@ public void WriteDebug(string text) using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( - Context != null, + Context is not null, "The context should always be set"); Context.WriteDebug(text); @@ -1703,7 +1703,7 @@ public void WriteInformation(InformationRecord record) using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( - Context != null, + Context is not null, "The context should always be set"); Context.WriteInformation(record); @@ -1716,7 +1716,7 @@ public void WriteInformation(object messageData, string[] tags) using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( - Context != null, + Context is not null, "The context should always be set"); Context.WriteInformation(messageData, tags); @@ -1749,7 +1749,7 @@ private void WriteObject( providerBaseTracer.WriteLine("Attaching {0} = {1}", "PSIsContainer", isContainer); Diagnostics.Assert( - Context != null, + Context is not null, "The context should always be set"); Context.WriteObject(result); @@ -1772,7 +1772,7 @@ private void WriteObject( PSObject result = WrapOutputInPSObject(item, path); Diagnostics.Assert( - Context != null, + Context is not null, "The context should always be set"); Context.WriteObject(result); @@ -1807,14 +1807,14 @@ private PSObject WrapOutputInPSObject( PSObject result = new PSObject(item); Diagnostics.Assert( - ProviderInfo != null, + ProviderInfo is not null, "The ProviderInfo should always be set"); // Move the TypeNames to the wrapping object if the wrapped object // was an PSObject PSObject mshObj = item as PSObject; - if (mshObj != null) + if (mshObj is not null) { result.InternalTypeNames = new ConsolidatedString(mshObj.InternalTypeNames); } @@ -1830,13 +1830,13 @@ private PSObject WrapOutputInPSObject( // Now get the parent path and child name NavigationCmdletProvider navProvider = this as NavigationCmdletProvider; - if (navProvider != null && path != null) + if (navProvider is not null && path is not null) { // Get the parent path string parentPath = null; - if (PSDriveInfo != null) + if (PSDriveInfo is not null) { parentPath = navProvider.GetParentPath(path, PSDriveInfo.Root, Context); } @@ -1887,7 +1887,7 @@ private PSObject WrapOutputInPSObject( // PSDriveInfo - if (PSDriveInfo != null) + if (PSDriveInfo is not null) { result.AddOrSetProperty(this.PSDriveInfo.GetNotePropertyForProviderCmdlets("PSDrive")); providerBaseTracer.WriteLine("Attaching {0} = {1}", "PSDrive", this.PSDriveInfo); @@ -1995,7 +1995,7 @@ public void WriteError(ErrorRecord errorRecord) using (PSTransactionManager.GetEngineProtectionScope()) { Diagnostics.Assert( - Context != null, + Context is not null, "The context should always be set"); if (errorRecord is null) @@ -2003,8 +2003,8 @@ public void WriteError(ErrorRecord errorRecord) throw PSTraceSource.NewArgumentNullException(nameof(errorRecord)); } - if (errorRecord.ErrorDetails != null - && errorRecord.ErrorDetails.TextLookupError != null) + if (errorRecord.ErrorDetails is not null + && errorRecord.ErrorDetails.TextLookupError is not null) { MshLog.LogProviderHealthEvent( this.Context.ExecutionContext, diff --git a/src/System.Management.Automation/namespaces/RegistryProvider.cs b/src/System.Management.Automation/namespaces/RegistryProvider.cs index df66402197d..ac96ec5a011 100644 --- a/src/System.Management.Automation/namespaces/RegistryProvider.cs +++ b/src/System.Management.Automation/namespaces/RegistryProvider.cs @@ -279,12 +279,12 @@ protected override void SetItem(string path, object value) // Check to see if the type was specified by the user bool valueSet = false; - if (DynamicParameters != null) + if (DynamicParameters is not null) { RegistryProviderSetItemDynamicParameter dynParams = DynamicParameters as RegistryProviderSetItemDynamicParameter; - if (dynParams != null) + if (dynParams is not null) { try { @@ -569,7 +569,7 @@ protected override void GetChildItems( string[] keyNames = key.GetSubKeyNames(); key.Close(); - if (keyNames != null) + if (keyNames is not null) { foreach (string subkeyName in keyNames) { @@ -596,7 +596,7 @@ protected override void GetChildItems( IRegistryWrapper resultKey = GetRegkeyForPath(keypath, false); - if (resultKey != null) + if (resultKey is not null) { WriteRegistryItemObject(resultKey, keypath); } @@ -781,7 +781,7 @@ private static string EscapeSpecialChars(string path) System.Globalization.StringInfo.GetTextElementEnumerator(path); Dbg.Diagnostics.Assert( - textEnumerator != null, + textEnumerator is not null, string.Format(CultureInfo.CurrentCulture, "Cannot get a text enumerator for name {0}", path)); while (textEnumerator.MoveNext()) @@ -830,7 +830,7 @@ private static string EscapeChildName(string name) System.Globalization.StringInfo.GetTextElementEnumerator(name); Dbg.Diagnostics.Assert( - textEnumerator != null, + textEnumerator is not null, string.Format(CultureInfo.CurrentCulture, "Cannot get a text enumerator for name {0}", name)); while (textEnumerator.MoveNext()) @@ -960,7 +960,7 @@ protected override void NewItem( // Check to see if the key already exists IRegistryWrapper resultKey = GetRegkeyForPath(path, false); - if (resultKey != null) + if (resultKey is not null) { if (!Force) { @@ -1014,7 +1014,7 @@ protected override void NewItem( { // Set the default key value if the value and type were specified - if (newItem != null) + if (newItem is not null) { RegistryValueKind kind; if (!ParseKind(type, out kind)) @@ -1201,7 +1201,7 @@ protected override bool ItemExists(string path) { IRegistryWrapper key = GetRegkeyForPath(path, false); - if (key != null) + if (key is not null) { result = true; key.Close(); @@ -1255,7 +1255,7 @@ protected override bool HasChildItems(string path) { IRegistryWrapper key = GetRegkeyForPath(path, false); - if (key != null) + if (key is not null) { result = key.SubKeyCount > 0; key.Close(); @@ -1367,7 +1367,7 @@ private bool CopyRegistryKey( } Dbg.Diagnostics.Assert( - key != null, + key is not null, "The key should have been validated by the caller"); Dbg.Diagnostics.Assert( @@ -1433,7 +1433,7 @@ private bool CopyRegistryKey( WriteError(new ErrorRecord(e, e.GetType().FullName, ErrorCategory.InvalidOperation, destinationName)); } - if (newKey != null) + if (newKey is not null) { // Now copy all the properties from the source to the destination @@ -1601,7 +1601,7 @@ protected override bool IsItemContainer(string path) { IRegistryWrapper key = GetRegkeyForPath(path, false); - if (key != null) + if (key is not null) { // All registry keys can be containers. Values are considered // properties @@ -1877,12 +1877,12 @@ public void SetProperty( // Get the kind of the value using the dynamic parameters - if (DynamicParameters != null) + if (DynamicParameters is not null) { RegistryProviderSetItemDynamicParameter dynParams = DynamicParameters as RegistryProviderSetItemDynamicParameter; - if (dynParams != null) + if (dynParams is not null) { kind = dynParams.Type; } @@ -3365,7 +3365,7 @@ private bool CreateIntermediateKeys(string path) // Create new subkey..and close IRegistryWrapper subKey = rootKey.CreateSubKey(remainingPath); - if (subKey != null) + if (subKey is not null) { subKey.Close(); } @@ -3704,7 +3704,7 @@ private void SetRegistryValue( bool writeResult) { Dbg.Diagnostics.Assert( - key != null, + key is not null, "Caller should have verified key"); string propertyNameToSet = GetPropertyName(propertyName); @@ -3743,7 +3743,7 @@ private void SetRegistryValue( if (kind == RegistryValueKind.Unknown) { // set the kind based on value - if (value != null) + if (value is not null) { kind = GetValueKindFromObject(value); } @@ -3808,7 +3808,7 @@ private static object ConvertValueToKind(object value, RegistryValueKind kind) switch (kind) { case RegistryValueKind.Binary: - value = (value != null) + value = (value is not null) ? (byte[])LanguagePrimitives.ConvertTo( value, typeof(byte[]), @@ -3818,7 +3818,7 @@ private static object ConvertValueToKind(object value, RegistryValueKind kind) case RegistryValueKind.DWord: { - if (value != null) + if (value is not null) { try { @@ -3836,7 +3836,7 @@ private static object ConvertValueToKind(object value, RegistryValueKind kind) } break; case RegistryValueKind.ExpandString: - value = (value != null) + value = (value is not null) ? (string)LanguagePrimitives.ConvertTo( value, typeof(string), @@ -3845,7 +3845,7 @@ private static object ConvertValueToKind(object value, RegistryValueKind kind) break; case RegistryValueKind.MultiString: - value = (value != null) + value = (value is not null) ? (string[])LanguagePrimitives.ConvertTo( value, typeof(string[]), @@ -3855,7 +3855,7 @@ private static object ConvertValueToKind(object value, RegistryValueKind kind) case RegistryValueKind.QWord: { - if (value != null) + if (value is not null) { try { @@ -3873,7 +3873,7 @@ private static object ConvertValueToKind(object value, RegistryValueKind kind) } break; case RegistryValueKind.String: - value = (value != null) + value = (value is not null) ? (string)LanguagePrimitives.ConvertTo( value, typeof(string), @@ -4007,7 +4007,7 @@ private void WriteRegistryItemObject( if (key is null) { Dbg.Diagnostics.Assert( - key != null, + key is not null, "The RegistryProvider should never attempt to write out a null value"); // Don't error, but don't write out anything either. @@ -4075,7 +4075,7 @@ private bool ParseKind(string type, out RegistryValueKind kind) innerException = argException; } - if (innerException != null) + if (innerException is not null) { success = false; diff --git a/src/System.Management.Automation/namespaces/RegistrySecurity.cs b/src/System.Management.Automation/namespaces/RegistrySecurity.cs index bf878bd595d..60a35770fc5 100644 --- a/src/System.Management.Automation/namespaces/RegistrySecurity.cs +++ b/src/System.Management.Automation/namespaces/RegistrySecurity.cs @@ -60,7 +60,7 @@ public void GetSecurityDescriptor(string path, key = GetRegkeyForPathWriteIfError(path, false); - if (key != null) + if (key is not null) { try { @@ -125,7 +125,7 @@ public void SetSecurityDescriptor( key = GetRegkeyForPathWriteIfError(path, true); - if (key != null) + if (key is not null) { // // the caller already checks for the following exceptions: diff --git a/src/System.Management.Automation/namespaces/SessionStateProviderBase.cs b/src/System.Management.Automation/namespaces/SessionStateProviderBase.cs index 198f53e2631..0bd28b63360 100644 --- a/src/System.Management.Automation/namespaces/SessionStateProviderBase.cs +++ b/src/System.Management.Automation/namespaces/SessionStateProviderBase.cs @@ -100,7 +100,7 @@ public abstract class SessionStateProviderBase : ContainerCmdletProvider, IConte internal virtual object GetValueOfItem(object item) { Dbg.Diagnostics.Assert( - item != null, + item is not null, "Caller should verify the item parameter"); object value = item; @@ -148,7 +148,7 @@ protected override void GetItem(string name) object item = null; IDictionary table = GetSessionStateTable(); - if (table != null) + if (table is not null) { if (string.IsNullOrEmpty(name)) { @@ -161,7 +161,7 @@ protected override void GetItem(string name) } } - if (item != null) + if (item is not null) { if (SessionState.IsVisible(this.Context.Origin, item)) { @@ -393,7 +393,7 @@ protected override void GetChildItems(string path, bool recurse) return; } - if (item != null) + if (item is not null) { if (SessionState.IsVisible(origin, item)) { @@ -485,7 +485,7 @@ protected override void GetChildNames(string path, ReturnContainers returnContai return; } - if (item != null) + if (item is not null) { if (SessionState.IsVisible(origin, item)) { @@ -567,7 +567,7 @@ protected override bool ItemExists(string path) path)); } - if (item != null) + if (item is not null) { result = true; } @@ -796,7 +796,7 @@ protected override void CopyItem(string path, string copyPath, bool recurse) return; } - if (item != null) + if (item is not null) { // Confirm the new item with the user @@ -892,7 +892,7 @@ protected override void RenameItem(string name, string newName) return; } - if (item != null) + if (item is not null) { if (ItemExists(newName) && !Force) { @@ -1140,11 +1140,11 @@ public IList Read(long readCount) { object item = _provider.GetSessionStateItem(_path); - if (item != null) + if (item is not null) { object getItemValueResult = _provider.GetValueOfItem(item); - if (getItemValueResult != null) + if (getItemValueResult is not null) { result = getItemValueResult as IList ?? new object[] { getItemValueResult }; } diff --git a/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs b/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs index dac6f6c0897..cdaee0b6720 100644 --- a/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs +++ b/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs @@ -224,7 +224,7 @@ private TransactedRegistryKey(SafeRegistryHandle hkey, bool writable, bool syste } // We want to take our own clone so we can dispose it when we want and // aren't susceptible to the caller disposing it. - if (transaction != null) + if (transaction is not null) { _myTransaction = transaction.Clone(); _myTransactionHandle = txHandle; @@ -243,7 +243,7 @@ private SafeTransactionHandle GetTransactionHandle() // If myTransaction is not null and is not the same as Transaction.Current // this is an invalid operation. The transaction within which the RegistryKey object was created // needs to be the same as the transaction being used now. - if (_myTransaction != null) + if (_myTransaction is not null) { if (!_myTransaction.Equals(Transaction.Current)) { @@ -273,7 +273,7 @@ public void Close() private void Dispose(bool disposing) { - if (_hkey != null) + if (_hkey is not null) { if (!IsSystemKey()) { @@ -292,7 +292,7 @@ private void Dispose(bool disposing) } } - if (_myTransaction != null) + if (_myTransaction is not null) { // Dispose the transaction because we cloned it. try @@ -317,7 +317,7 @@ public void Flush() { // Require a transaction. This will throw for "Base" keys because they aren't associated with a transaction. VerifyTransaction(); - if (_hkey != null) + if (_hkey is not null) { if (IsDirty()) { @@ -416,7 +416,7 @@ private unsafe TransactedRegistryKey CreateSubKeyInternal(string subkey, Registr // only keys opened under read mode is not writable TransactedRegistryKey existingKey = InternalOpenSubKey(subkey, (permissionCheck != RegistryKeyPermissionCheck.ReadSubTree)); - if (existingKey != null) + if (existingKey is not null) { // Key already exits CheckSubKeyWritePermission(subkey); CheckSubTreePermission(subkey, permissionCheck); @@ -429,7 +429,7 @@ private unsafe TransactedRegistryKey CreateSubKeyInternal(string subkey, Registr Win32Native.SECURITY_ATTRIBUTES secAttrs = null; TransactedRegistrySecurity registrySecurity = registrySecurityObj as TransactedRegistrySecurity; // For ACL's, get the security descriptor from the RegistrySecurity. - if (registrySecurity != null) + if (registrySecurity is not null) { secAttrs = new Win32Native.SECURITY_ATTRIBUTES(); secAttrs.nLength = (int)Marshal.SizeOf(secAttrs); @@ -525,7 +525,7 @@ public void DeleteSubKey(string subkey, bool throwOnMissingSubKey) // explicitly call close to avoid keeping an extra HKEY open. // TransactedRegistryKey key = InternalOpenSubKey(subkey, false); - if (key != null) + if (key is not null) { try { @@ -593,7 +593,7 @@ public void DeleteSubKeyTree(string subkey) CheckSubTreeWritePermission(subkey); TransactedRegistryKey key = InternalOpenSubKey(subkey, true); - if (key != null) + if (key is not null) { try { @@ -633,7 +633,7 @@ private void DeleteSubKeyTreeInternal(string subkey) SafeTransactionHandle safeTransactionHandle = GetTransactionHandle(); TransactedRegistryKey key = InternalOpenSubKey(subkey, true); - if (key != null) + if (key is not null) { try { @@ -1391,7 +1391,7 @@ public unsafe void SetValue(string name, object value, RegistryValueKind valueKi if (value == null) throw new ArgumentNullException(RegistryProviderStrings.Arg_Value); - if (name != null && name.Length > MaxValueNameLength) + if (name is not null && name.Length > MaxValueNameLength) { throw new ArgumentException(RegistryProviderStrings.Arg_RegValueNameStrLenBug); } @@ -1660,7 +1660,7 @@ internal void Win32Error(int errorCode, string str) switch (errorCode) { case Win32Native.ERROR_ACCESS_DENIED: - if (str != null) + if (str is not null) { string resourceTemplate = RegistryProviderStrings.UnauthorizedAccess_RegistryKeyGeneric_Key; string resource = string.Format(CultureInfo.CurrentCulture, resourceTemplate, str); @@ -1706,7 +1706,7 @@ internal static void Win32ErrorStatic(int errorCode, string str) switch (errorCode) { case Win32Native.ERROR_ACCESS_DENIED: - if (str != null) + if (str is not null) { string resourceTemplate = RegistryProviderStrings.UnauthorizedAccess_RegistryKeyGeneric_Key; string resource = string.Format(CultureInfo.CurrentCulture, resourceTemplate, str); @@ -1722,7 +1722,7 @@ internal static void Win32ErrorStatic(int errorCode, string str) internal static string FixupName(string name) { - BCLDebug.Assert(name != null, "[FixupName]name!=null"); + BCLDebug.Assert(name is not null, "[FixupName]name!=null"); if (name.Contains('\\')) return name; diff --git a/src/System.Management.Automation/namespaces/VariableProvider.cs b/src/System.Management.Automation/namespaces/VariableProvider.cs index 705e1b65edd..169cbcc295d 100644 --- a/src/System.Management.Automation/namespaces/VariableProvider.cs +++ b/src/System.Management.Automation/namespaces/VariableProvider.cs @@ -108,7 +108,7 @@ internal override void SetSessionStateItem(string name, object value, bool write PSVariable variable = null; - if (value != null) + if (value is not null) { variable = value as PSVariable; if (variable is null) @@ -134,7 +134,7 @@ internal override void SetSessionStateItem(string name, object value, bool write PSVariable item = SessionState.Internal.SetVariable(variable, Force, Context.Origin) as PSVariable; - if (writeItem && item != null) + if (writeItem && item is not null) { WriteItemObject(item, item.Name, false); } @@ -180,7 +180,7 @@ internal override IDictionary GetSessionStateTable() internal override object GetValueOfItem(object item) { Dbg.Diagnostics.Assert( - item != null, + item is not null, "Caller should verify the item parameter"); // Call the base class to unwrap the DictionaryEntry @@ -189,7 +189,7 @@ internal override object GetValueOfItem(object item) object value = base.GetValueOfItem(item); PSVariable var = item as PSVariable; - if (var != null) + if (var is not null) { value = var.Value; } @@ -212,7 +212,7 @@ internal override bool CanRenameItem(object item) bool result = false; PSVariable variable = item as PSVariable; - if (variable != null) + if (variable is not null) { if ((variable.Options & ScopedItemOptions.Constant) != 0 || ((variable.Options & ScopedItemOptions.ReadOnly) != 0 && !Force)) diff --git a/src/System.Management.Automation/security/Authenticode.cs b/src/System.Management.Automation/security/Authenticode.cs index 524399b7aa6..b3c03fe1b1b 100644 --- a/src/System.Management.Automation/security/Authenticode.cs +++ b/src/System.Management.Automation/security/Authenticode.cs @@ -192,7 +192,7 @@ internal static Signature SignFile(SigningOption option, IntPtr.Zero); #pragma warning restore 56523 - if (si.pSignExtInfo != null) + if (si.pSignExtInfo is not null) { Marshal.DestroyStructure(si.pSignExtInfo); Marshal.FreeCoTaskMem(si.pSignExtInfo); @@ -337,7 +337,7 @@ private static Signature GetSignatureFromCatalog(string filename) // Get the time stamper certificate if available TryGetProviderSigner(phStateData, out IntPtr pProvSigner, out X509Certificate2 timestamperCert); - if (timestamperCert != null) + if (timestamperCert is not null) { signature = new Signature(filename, error, cert, timestamperCert); } @@ -376,7 +376,7 @@ private static Signature GetSignatureFromCatalog(string filename) // ProductFile has to be Catalog signed. Hence validating // to see if the Catalog API is functional using the ProductFile. Signature productFileSignature = GetSignatureFromCatalog(productFile); - Signature.CatalogApiAvailable = (productFileSignature != null && productFileSignature.Status == SignatureStatus.Valid); + Signature.CatalogApiAvailable = (productFileSignature is not null && productFileSignature.Status == SignatureStatus.Valid); } } } @@ -567,9 +567,9 @@ private static Signature GetSignatureFromWintrustData( // X509Certificate2 signerCert = GetCertFromChain(pProvSigner); - if (signerCert != null) + if (signerCert is not null) { - if (timestamperCert != null) + if (timestamperCert is not null) { signature = new Signature(filePath, error, @@ -587,7 +587,7 @@ private static Signature GetSignatureFromWintrustData( } } - Diagnostics.Assert(error != 0 || signature != null, "GetSignatureFromWintrustData: general crypto failure"); + Diagnostics.Assert(error != 0 || signature is not null, "GetSignatureFromWintrustData: general crypto failure"); if ((signature is null) && (error != 0)) { diff --git a/src/System.Management.Automation/security/CatalogHelper.cs b/src/System.Management.Automation/security/CatalogHelper.cs index 050c373af74..e4891969d2c 100644 --- a/src/System.Management.Automation/security/CatalogHelper.cs +++ b/src/System.Management.Automation/security/CatalogHelper.cs @@ -215,7 +215,7 @@ internal static void ProcessFileToBeAddedInCatalogDefinitionFile(FileInfo fileTo { string relativePath = string.Empty; - if (dirInfo != null) + if (dirInfo is not null) { // Relative path of the file is the path inside the containing folder excluding folder Name relativePath = fileToHash.FullName.AsSpan(dirInfo.FullName.Length).TrimStart('\\').ToString(); @@ -310,7 +310,7 @@ internal static void GenerateCatalogFile(string cdfFilePath) } } while (memberAttr != IntPtr.Zero); } - } while (fileName != null); + } while (fileName is not null); } finally { @@ -610,7 +610,7 @@ internal static void ProcessPathFile(FileInfo fileToHash, DirectoryInfo dirInfo, string relativePath = string.Empty; string exclude = string.Empty; - if (dirInfo != null) + if (dirInfo is not null) { // Relative path of the file is the path inside the containing folder excluding folder Name relativePath = fileToHash.FullName.AsSpan(dirInfo.FullName.Length).TrimStart('\\').ToString(); @@ -774,7 +774,7 @@ internal static CatalogInformation ValidateCatalog(PSCmdlet cmdlet, CollectionTrue if match is found else false. internal static bool CheckExcludedCriteria(string filename, WildcardPattern[] excludedPatterns) { - if (excludedPatterns != null) + if (excludedPatterns is not null) { foreach (WildcardPattern patternItem in excludedPatterns) { diff --git a/src/System.Management.Automation/security/SecureStringHelper.cs b/src/System.Management.Automation/security/SecureStringHelper.cs index ad5646d59cf..20c8a87e5f8 100644 --- a/src/System.Management.Automation/security/SecureStringHelper.cs +++ b/src/System.Management.Automation/security/SecureStringHelper.cs @@ -446,7 +446,7 @@ public static byte[] Protect(byte[] userData, byte[] optionalEntropy, DataProtec dataIn.cbData = (uint)userData.Length; dataIn.pbData = pbDataIn.AddrOfPinnedObject(); CAPI.CRYPTOAPI_BLOB entropy = new CAPI.CRYPTOAPI_BLOB(); - if (optionalEntropy != null) + if (optionalEntropy is not null) { pOptionalEntropy = GCHandle.Alloc(optionalEntropy, GCHandleType.Pinned); entropy.cbData = (uint)optionalEntropy.Length; @@ -534,7 +534,7 @@ public static byte[] Unprotect(byte[] encryptedData, byte[] optionalEntropy, Dat dataIn.cbData = (uint)encryptedData.Length; dataIn.pbData = pbDataIn.AddrOfPinnedObject(); CAPI.CRYPTOAPI_BLOB entropy = new CAPI.CRYPTOAPI_BLOB(); - if (optionalEntropy != null) + if (optionalEntropy is not null) { pOptionalEntropy = GCHandle.Alloc(optionalEntropy, GCHandleType.Pinned); entropy.cbData = (uint)optionalEntropy.Length; diff --git a/src/System.Management.Automation/security/SecurityManager.cs b/src/System.Management.Automation/security/SecurityManager.cs index d2a6e621460..5fc560c58ae 100644 --- a/src/System.Management.Automation/security/SecurityManager.cs +++ b/src/System.Management.Automation/security/SecurityManager.cs @@ -568,7 +568,7 @@ protected internal override bool ShouldRun(CommandInfo commandInfo, PSHost host, out Exception reason) { - Dbg.Diagnostics.Assert(commandInfo != null, "caller should validate the parameter"); + Dbg.Diagnostics.Assert(commandInfo is not null, "caller should validate the parameter"); bool allowRun = false; reason = null; diff --git a/src/System.Management.Automation/security/SecuritySupport.cs b/src/System.Management.Automation/security/SecuritySupport.cs index 40b8770b456..afb7a41470b 100644 --- a/src/System.Management.Automation/security/SecuritySupport.cs +++ b/src/System.Management.Automation/security/SecuritySupport.cs @@ -245,7 +245,7 @@ private static bool IsCurrentProcessLaunchedByGpScript() bool foundGpScriptParent = false; try { - while (currentProcess != null) + while (currentProcess is not null) { if (string.Equals(gpScriptPath, PsUtils.GetMainModule(currentProcess).FileName, StringComparison.OrdinalIgnoreCase)) @@ -407,7 +407,7 @@ public static bool IsProductBinary(string file) #else // Check the file signature Signature fileSignature = SignatureHelper.GetSignature(file, null); - if ((fileSignature != null) && (fileSignature.IsOSBinary)) + if ((fileSignature is not null) && (fileSignature.IsOSBinary)) { return true; } @@ -448,7 +448,7 @@ private static string GetGroupPolicyValue(string shellId, ExecutionPolicyScope s } var scriptExecutionSetting = Utils.GetPolicySetting(scopeKey); - if (scriptExecutionSetting != null) + if (scriptExecutionSetting is not null) { if (scriptExecutionSetting.EnableScripts == false) { @@ -517,7 +517,7 @@ internal static SaferPolicy GetSaferPolicy(string path, SafeHandle handle) NativeConstants.SAFER_CRITERIA_AUTHENTICODE); codeProperties.ImagePath = path; - if (handle != null) + if (handle is not null) { codeProperties.hImageFileHandle = handle.DangerousGetHandle(); } @@ -665,7 +665,7 @@ private static bool CertHasKeyUsage(X509Certificate2 c, X509KeyUsageFlags keyUsa foreach (X509Extension extension in c.Extensions) { X509KeyUsageExtension keyUsageExtension = extension as X509KeyUsageExtension; - if (keyUsageExtension != null) + if (keyUsageExtension is not null) { if ((keyUsageExtension.KeyUsages & keyUsage) == keyUsage) { @@ -887,12 +887,12 @@ internal static string Encrypt(byte[] contentBytes, CmsMessageRecipient[] recipi foreach (CmsMessageRecipient recipient in recipients) { // Resolve the recipient, if it hasn't been done yet. - if ((recipient.Certificates != null) && (recipient.Certificates.Count == 0)) + if ((recipient.Certificates is not null) && (recipient.Certificates.Count == 0)) { recipient.Resolve(sessionState, ResolutionPurpose.Encryption, out error); } - if (error != null) + if (error is not null) { return null; } @@ -1030,37 +1030,37 @@ public void Resolve(SessionState sessionState, ResolutionPurpose purpose, out Er error = null; // Process the certificate if that was supplied exactly - if (_pendingCertificate != null) + if (_pendingCertificate is not null) { ProcessResolvedCertificates( purpose, new X509Certificate2Collection(_pendingCertificate), out error); - if ((error != null) || (Certificates.Count != 0)) + if ((error is not null) || (Certificates.Count != 0)) { return; } } - if (_identifier != null) + if (_identifier is not null) { // First try to resolve assuming that the cert was Base64 encoded. ResolveFromBase64Encoding(purpose, out error); - if ((error != null) || (Certificates.Count != 0)) + if ((error is not null) || (Certificates.Count != 0)) { return; } // Then try to resolve by path. ResolveFromPath(sessionState, purpose, out error); - if ((error != null) || (Certificates.Count != 0)) + if ((error is not null) || (Certificates.Count != 0)) { return; } // Then by cert store ResolveFromStoreById(purpose, out error); - if ((error != null) || (Certificates.Count != 0)) + if ((error is not null) || (Certificates.Count != 0)) { return; } @@ -1138,7 +1138,7 @@ private void ResolveFromPath(SessionState sessionState, ResolutionPurpose purpos } // If we got a resolved path, try to load certs from that path. - if ((resolvedPaths != null) && (resolvedPaths.Count != 0)) + if ((resolvedPaths is not null) && (resolvedPaths.Count != 0)) { // Ensure the path is from the file system provider if (!string.Equals(pathProvider.Name, "FileSystem", StringComparison.OrdinalIgnoreCase)) diff --git a/src/System.Management.Automation/security/nativeMethods.cs b/src/System.Management.Automation/security/nativeMethods.cs index 7cda5b88260..cc1a5d67630 100644 --- a/src/System.Management.Automation/security/nativeMethods.cs +++ b/src/System.Management.Automation/security/nativeMethods.cs @@ -642,7 +642,7 @@ internal static CRYPTUI_WIZ_DIGITAL_SIGN_EXTENDED_INFO siex.psAuthenticatedNotUsed = IntPtr.Zero; siex.psUnauthenticatedNotUsed = IntPtr.Zero; - if (hashAlgorithm != null) + if (hashAlgorithm is not null) { siex.pszHashAlg = hashAlgorithm; } diff --git a/src/System.Management.Automation/security/wldpNativeMethods.cs b/src/System.Management.Automation/security/wldpNativeMethods.cs index d89f140e837..36600165958 100644 --- a/src/System.Management.Automation/security/wldpNativeMethods.cs +++ b/src/System.Management.Automation/security/wldpNativeMethods.cs @@ -121,7 +121,7 @@ private static SystemEnforcementMode GetWldpPolicy(string path, SafeHandle handl // If path is NULL, see if we have the cached system-wide lockdown policy. if (string.IsNullOrEmpty(path)) { - if ((s_cachedWldpSystemPolicy != null) && (!InternalTestHooks.BypassAppLockerPolicyCaching)) + if ((s_cachedWldpSystemPolicy is not null) && (!InternalTestHooks.BypassAppLockerPolicyCaching)) { return s_cachedWldpSystemPolicy.Value; } @@ -137,7 +137,7 @@ private static SystemEnforcementMode GetWldpPolicy(string path, SafeHandle handl { hostInformation.szSource = path; - if (handle != null) + if (handle is not null) { IntPtr fileHandle = IntPtr.Zero; fileHandle = handle.DangerousGetHandle(); @@ -187,7 +187,7 @@ private static SystemEnforcementMode GetAppLockerPolicy(string path, SafeHandle // no AppLocker script policy. if (string.IsNullOrEmpty(path)) { - if ((s_cachedSaferSystemPolicy != null) && (!InternalTestHooks.BypassAppLockerPolicyCaching)) + if ((s_cachedSaferSystemPolicy is not null) && (!InternalTestHooks.BypassAppLockerPolicyCaching)) { result = s_cachedSaferSystemPolicy.Value; } @@ -348,7 +348,7 @@ private static SystemEnforcementMode GetDebugLockdownPolicy(string path) s_allowDebugOverridePolicy = true; // Support fall-back debug hook for path exclusions on non-WOA platforms - if (path != null) + if (path is not null) { // Assume everything under SYSTEM32 is trusted, with a purposefully sloppy // check so that we can actually put it in the filename during testing. @@ -361,14 +361,14 @@ private static SystemEnforcementMode GetDebugLockdownPolicy(string path) { using (RegistryKey wldpPolicy = hklm.OpenSubKey("SYSTEM\\CurrentControlSet\\Control\\CI\\TRSData")) { - if (wldpPolicy != null) + if (wldpPolicy is not null) { object exclusionPathsKey = wldpPolicy.GetValue("TestPath"); wldpPolicy.Close(); hklm.Close(); - if (exclusionPathsKey != null) + if (exclusionPathsKey is not null) { string[] exclusionPaths = (string[])exclusionPathsKey; foreach (string exclusionPath in exclusionPaths) @@ -391,7 +391,7 @@ private static SystemEnforcementMode GetDebugLockdownPolicy(string path) // Support fall-back debug hook for system-wide policy on non-WOA platforms uint pdwLockdownState = 0; object result = Environment.GetEnvironmentVariable("__PSLockdownPolicy", EnvironmentVariableTarget.Machine); - if (result != null) + if (result is not null) { pdwLockdownState = LanguagePrimitives.ConvertTo(result); return GetLockdownPolicyForResult(pdwLockdownState); diff --git a/src/System.Management.Automation/singleshell/config/MshConsoleLoadException.cs b/src/System.Management.Automation/singleshell/config/MshConsoleLoadException.cs index 9e8c2585215..62881935421 100644 --- a/src/System.Management.Automation/singleshell/config/MshConsoleLoadException.cs +++ b/src/System.Management.Automation/singleshell/config/MshConsoleLoadException.cs @@ -74,7 +74,7 @@ private void CreateErrorRecord() { StringBuilder sb = new StringBuilder(); - if (PSSnapInExceptions != null) + if (PSSnapInExceptions is not null) { foreach (PSSnapInException e in PSSnapInExceptions) { @@ -103,7 +103,7 @@ public override string Message { get { - if (_errorRecord != null) + if (_errorRecord is not null) { return _errorRecord.ToString(); } diff --git a/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs b/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs index 9a0a433e278..58b40d16e2b 100644 --- a/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs +++ b/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs @@ -367,7 +367,7 @@ internal void LoadIndirectResources(RegistryStringResourceIndirect resourceReade else { RegistryKey mshsnapinKey = MshSnapinKey; - if (mshsnapinKey != null) + if (mshsnapinKey is not null) { _description = resourceReader.GetResourceStringIndirect( @@ -528,7 +528,7 @@ internal static Collection ReadAll() { } - if (oneVersionMshSnapins != null) + if (oneVersionMshSnapins is not null) { foreach (PSSnapInInfo info in oneVersionMshSnapins) { @@ -599,7 +599,7 @@ internal static Collection ReadAll(string psVersion) /// private static Collection ReadAll(RegistryKey monadRootKey, string psVersion) { - Dbg.Assert(monadRootKey != null, "caller should validate the information"); + Dbg.Assert(monadRootKey is not null, "caller should validate the information"); Dbg.Assert(!string.IsNullOrEmpty(psVersion), "caller should validate the information"); Collection mshsnapins = new Collection(); @@ -691,7 +691,7 @@ internal static PSSnapInInfo Read(string psVersion, string mshsnapinId) private static PSSnapInInfo ReadOne(RegistryKey mshSnapInRoot, string mshsnapinId) { Dbg.Assert(!string.IsNullOrEmpty(mshsnapinId), "caller should validate the parameter"); - Dbg.Assert(mshSnapInRoot != null, "caller should validate the parameter"); + Dbg.Assert(mshSnapInRoot is not null, "caller should validate the parameter"); RegistryKey mshsnapinKey; mshsnapinKey = mshSnapInRoot.OpenSubKey(mshsnapinId); @@ -774,7 +774,7 @@ private static Collection ReadMultiStringValue(RegistryKey mshsnapinKey, { // Check if the value is in string format string singleValue = value as string; - if (singleValue != null) + if (singleValue is not null) { msv = new string[1]; msv[0] = singleValue; @@ -813,7 +813,7 @@ private static Collection ReadMultiStringValue(RegistryKey mshsnapinKey, internal static string ReadStringValue(RegistryKey mshsnapinKey, string name, bool mandatory) { Dbg.Assert(!string.IsNullOrEmpty(name), "caller should validate the parameter"); - Dbg.Assert(mshsnapinKey != null, "Caller should validate the parameter"); + Dbg.Assert(mshsnapinKey is not null, "Caller should validate the parameter"); object value = mshsnapinKey.GetValue(name); if (value is null && mandatory) @@ -887,7 +887,7 @@ internal static void ReadRegistryInfo(out Version assemblyVersion, out string pu // Get the PSVersion from Utils..this is hardcoded psVersion = PSVersionInfo.PSVersion; Dbg.Assert( - psVersion != null, + psVersion is not null, string.Format(CultureInfo.CurrentCulture, "{0} is null", RegistryStrings.MonadEngine_MonadVersion)); // Get version number in x.x.x.x format @@ -925,7 +925,7 @@ internal static void ReadRegistryInfo(out Version assemblyVersion, out string pu /// internal static string ConvertByteArrayToString(byte[] tokens) { - Dbg.Assert(tokens != null, "Input tokens should never be null"); + Dbg.Assert(tokens is not null, "Input tokens should never be null"); StringBuilder tokenBuilder = new StringBuilder(tokens.Length * 2); foreach (byte b in tokens) { @@ -1091,7 +1091,7 @@ private static void SetSnapInLoggingInformation(PSSnapInInfo psSnapInInfo) /// private static void SetSnapInLoggingInformation(PSSnapInInfo psSnapInInfo, ModuleCmdletBase.ModuleLoggingGroupPolicyStatus status, IEnumerable moduleOrSnapinNames) { - if (((status & ModuleCmdletBase.ModuleLoggingGroupPolicyStatus.Enabled) != 0) && moduleOrSnapinNames != null) + if (((status & ModuleCmdletBase.ModuleLoggingGroupPolicyStatus.Enabled) != 0) && moduleOrSnapinNames is not null) { foreach (string currentGPModuleOrSnapinName in moduleOrSnapinNames) { @@ -1148,11 +1148,11 @@ internal static RegistryKey GetPSEngineKey(string psVersion) { RegistryKey rootKey = GetMonadRootKey(); // root key wont be null - Dbg.Assert(rootKey != null, "Root Key of Monad installation is not present"); + Dbg.Assert(rootKey is not null, "Root Key of Monad installation is not present"); RegistryKey versionRootKey = GetVersionRootKey(rootKey, psVersion); // version root key wont be null - Dbg.Assert(versionRootKey != null, "Version Rootkey of Monad installation is not present"); + Dbg.Assert(versionRootKey is not null, "Version Rootkey of Monad installation is not present"); RegistryKey psEngineParentKey = rootKey.OpenSubKey(psVersion); if (psEngineParentKey is null) @@ -1186,7 +1186,7 @@ internal static GetVersionRootKey(RegistryKey rootKey, string psVersion) { Dbg.Assert(!string.IsNullOrEmpty(psVersion), "caller should validate the parameter"); - Dbg.Assert(rootKey != null, "caller should validate the parameter"); + Dbg.Assert(rootKey is not null, "caller should validate the parameter"); string versionKey = PSVersionInfo.GetRegistryVersionKeyForSnapinDiscovery(psVersion); RegistryKey versionRoot = rootKey.OpenSubKey(versionKey); @@ -1214,7 +1214,7 @@ private static RegistryKey GetMshSnapinRootKey(RegistryKey versionRootKey, string psVersion) { - Dbg.Assert(versionRootKey != null, "caller should validate the parameter"); + Dbg.Assert(versionRootKey is not null, "caller should validate the parameter"); RegistryKey mshsnapinRoot = versionRootKey.OpenSubKey(RegistryStrings.MshSnapinKey); if (mshsnapinRoot is null) diff --git a/src/System.Management.Automation/singleshell/config/MshSnapinLoadException.cs b/src/System.Management.Automation/singleshell/config/MshSnapinLoadException.cs index 29ae4aa5e5c..087a5761bf2 100644 --- a/src/System.Management.Automation/singleshell/config/MshSnapinLoadException.cs +++ b/src/System.Management.Automation/singleshell/config/MshSnapinLoadException.cs @@ -156,7 +156,7 @@ public override string Message { get { - if (_errorRecord != null && !_isErrorRecordOriginallyNull) + if (_errorRecord is not null && !_isErrorRecordOriginallyNull) { return _errorRecord.ToString(); } diff --git a/src/System.Management.Automation/utils/ClrFacade.cs b/src/System.Management.Automation/utils/ClrFacade.cs index 2d93a1bb67d..3427650c971 100644 --- a/src/System.Management.Automation/utils/ClrFacade.cs +++ b/src/System.Management.Automation/utils/ClrFacade.cs @@ -286,7 +286,7 @@ private static SecurityZone ReadFromZoneIdentifierDataStream(string filePath) // - if matching, check if the ZoneId is valid. Then return the corresponding SecurityZone if valid, or 'NoZone' if invalid. // - if not matching, then continue to do step #3 with the next line. // 4. Reach EOF, then return 'NoZone'. - while ((line = zoneDataReader.ReadLine()) != null) + while ((line = zoneDataReader.ReadLine()) is not null) { line = line.Trim(); if (!zoneTransferMatched) diff --git a/src/System.Management.Automation/utils/CommandDiscoveryExceptions.cs b/src/System.Management.Automation/utils/CommandDiscoveryExceptions.cs index ecc9a45cf03..cfa6d2d17c3 100644 --- a/src/System.Management.Automation/utils/CommandDiscoveryExceptions.cs +++ b/src/System.Management.Automation/utils/CommandDiscoveryExceptions.cs @@ -163,7 +163,7 @@ params object[] messageArgs ) { object[] a; - if (messageArgs != null && 0 < messageArgs.Length) + if (messageArgs is not null && 0 < messageArgs.Length) { a = new object[messageArgs.Length + 1]; a[0] = commandName; @@ -242,7 +242,7 @@ internal ScriptRequiresException( : base(BuildMessage(commandName, requiresPSVersion.ToString(), currentPSVersion, false)) { Diagnostics.Assert(!string.IsNullOrEmpty(commandName), "commandName is null or empty when constructing ScriptRequiresException"); - Diagnostics.Assert(requiresPSVersion != null, "requiresPSVersion is null or empty when constructing ScriptRequiresException"); + Diagnostics.Assert(requiresPSVersion is not null, "requiresPSVersion is null or empty when constructing ScriptRequiresException"); Diagnostics.Assert(!string.IsNullOrEmpty(errorId), "errorId is null or empty when constructing ScriptRequiresException"); _commandName = commandName; _requiresPSVersion = requiresPSVersion; @@ -304,7 +304,7 @@ internal ScriptRequiresException( : base(BuildMessage(commandName, missingItems, forSnapins), null, errorRecord) { Diagnostics.Assert(!string.IsNullOrEmpty(commandName), "commandName is null or empty when constructing ScriptRequiresException"); - Diagnostics.Assert(missingItems != null && missingItems.Count > 0, "missingItems is null or empty when constructing ScriptRequiresException"); + Diagnostics.Assert(missingItems is not null && missingItems.Count > 0, "missingItems is null or empty when constructing ScriptRequiresException"); Diagnostics.Assert(!string.IsNullOrEmpty(errorId), "errorId is null or empty when constructing ScriptRequiresException"); _commandName = commandName; _missingPSSnapIns = new ReadOnlyCollection(missingItems); diff --git a/src/System.Management.Automation/utils/CryptoUtils.cs b/src/System.Management.Automation/utils/CryptoUtils.cs index 80c48b58827..c04c6ade40f 100644 --- a/src/System.Management.Automation/utils/CryptoUtils.cs +++ b/src/System.Management.Automation/utils/CryptoUtils.cs @@ -418,7 +418,7 @@ private PSRSACryptoServiceProvider(bool serverMode) /// Public key as base64 encoded string. internal string GetPublicKeyAsBase64EncodedString() { - Dbg.Assert(_rsa != null, "No public key available."); + Dbg.Assert(_rsa is not null, "No public key available."); byte[] capiPublicKeyBlob = PSCryptoNativeConverter.ToCapiPublicKeyBlob(_rsa); @@ -456,7 +456,7 @@ internal void GenerateSessionKey() /// and encoded as a base 64 string. internal string SafeExportSessionKey() { - Dbg.Assert(_rsa != null, "No public key available."); + Dbg.Assert(_rsa is not null, "No public key available."); // generate one if not already done. GenerateSessionKey(); @@ -616,12 +616,12 @@ protected void Dispose(bool disposing) { if (disposing) { - if (_rsa != null) + if (_rsa is not null) { _rsa.Dispose(); } - if (_aes != null) + if (_aes is not null) { _aes.Dispose(); } @@ -676,7 +676,7 @@ internal abstract class PSRemotingCryptoHelper : IDisposable /// protected void RunKeyExchangeIfRequired() { - Dbg.Assert(Session != null, "data structure handler not set"); + Dbg.Assert(Session is not null, "data structure handler not set"); if (!_rsaCryptoProvider.CanEncrypt) { @@ -784,7 +784,7 @@ protected SecureString DecryptSecureStringCore(string encryptedString) throw new PSCryptoException(); } - if (data != null) + if (data is not null) { byte[] decryptedData = _rsaCryptoProvider.DecryptWithSessionKey(data); @@ -863,7 +863,7 @@ public void Dispose(bool disposing) { if (disposing) { - if (_rsaCryptoProvider != null) + if (_rsaCryptoProvider is not null) { _rsaCryptoProvider.Dispose(); } @@ -923,7 +923,7 @@ internal override string EncryptSecureString(SecureString secureString) // session!=null check required for DRTs TestEncryptSecureString* entries in CryptoUtilsTest/UTUtils.dll // for newer clients, server will never initiate key exchange. // for server, just the session key is required to encrypt/decrypt anything - if ((session != null) && (session.Context.ClientCapability.ProtocolVersion >= RemotingConstants.ProtocolVersionWin8RTM)) + if ((session is not null) && (session.Context.ClientCapability.ProtocolVersion >= RemotingConstants.ProtocolVersionWin8RTM)) { _rsaCryptoProvider.GenerateSessionKey(); } diff --git a/src/System.Management.Automation/utils/ExecutionExceptions.cs b/src/System.Management.Automation/utils/ExecutionExceptions.cs index d9da7cc787e..19da73b33db 100644 --- a/src/System.Management.Automation/utils/ExecutionExceptions.cs +++ b/src/System.Management.Automation/utils/ExecutionExceptions.cs @@ -37,7 +37,7 @@ internal CmdletInvocationException(ErrorRecord errorRecord) } _errorRecord = errorRecord; - if (errorRecord.Exception != null) + if (errorRecord.Exception is not null) { // 2005/04/13-JonN Can't do this in an unsealed class: HelpLink = errorRecord.Exception.HelpLink; // Exception.Source is set by Throw @@ -63,7 +63,7 @@ internal CmdletInvocationException(Exception innerException, // invocationInfo may be null IContainsErrorRecord icer = innerException as IContainsErrorRecord; - if (icer != null && icer.ErrorRecord != null) + if (icer is not null && icer.ErrorRecord is not null) { _errorRecord = new ErrorRecord(icer.ErrorRecord, innerException); } @@ -146,7 +146,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont } base.GetObjectData(info, context); - bool hasErrorRecord = (_errorRecord != null); + bool hasErrorRecord = (_errorRecord is not null); info.AddValue("HasErrorRecord", hasErrorRecord); if (hasErrorRecord) info.AddValue("ErrorRecord", _errorRecord); @@ -541,9 +541,9 @@ protected ActionPreferenceStopException(SerializationInfo info, public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); - if (info != null) + if (info is not null) { - bool hasErrorRecord = (_errorRecord != null); + bool hasErrorRecord = (_errorRecord is not null); info.AddValue("HasErrorRecord", hasErrorRecord); if (hasErrorRecord) { @@ -712,7 +712,7 @@ public override string Message { get { - return _message ?? (_message = (_wrapperException != null) ? _wrapperException.Message : string.Empty); + return _message ?? (_message = (_wrapperException is not null) ? _wrapperException.Message : string.Empty); } } diff --git a/src/System.Management.Automation/utils/ExtensionMethods.cs b/src/System.Management.Automation/utils/ExtensionMethods.cs index 94b9da1f98d..559b1fc5ba5 100644 --- a/src/System.Management.Automation/utils/ExtensionMethods.cs +++ b/src/System.Management.Automation/utils/ExtensionMethods.cs @@ -12,7 +12,7 @@ internal static class ExtensionMethods { public static void SafeInvoke(this EventHandler eventHandler, object sender, EventArgs eventArgs) { - if (eventHandler != null) + if (eventHandler is not null) { eventHandler(sender, eventArgs); } @@ -20,7 +20,7 @@ public static void SafeInvoke(this EventHandler eventHandler, object sender, Eve public static void SafeInvoke(this EventHandler eventHandler, object sender, T eventArgs) where T : EventArgs { - if (eventHandler != null) + if (eventHandler is not null) { eventHandler(sender, eventArgs); } @@ -50,7 +50,7 @@ internal static int SequenceGetHashCode(this IEnumerable xs) foreach (T x in xs) { hash = hash * 59; // 59 is a random prime number - if (x != null) + if (x is not null) { hash = hash + x.GetHashCode(); } @@ -78,7 +78,7 @@ internal static class PSTypeExtensions internal static bool HasDefaultCtor(this Type type) { var ctor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null); - if (ctor != null) + if (ctor is not null) { if (ctor.IsPublic || ctor.IsFamily || ctor.IsFamilyOrAssembly) { @@ -135,7 +135,7 @@ internal static bool TryGetTarget(this WeakReference weakReference, out T tar { var t = weakReference.Target; target = t as T; - return (target != null); + return (target is not null); } } } diff --git a/src/System.Management.Automation/utils/FormatAndTypeDataHelper.cs b/src/System.Management.Automation/utils/FormatAndTypeDataHelper.cs index db68073deb4..54ec678a313 100644 --- a/src/System.Management.Automation/utils/FormatAndTypeDataHelper.cs +++ b/src/System.Management.Automation/utils/FormatAndTypeDataHelper.cs @@ -122,7 +122,7 @@ internal static void ThrowExceptionOnError( Category category) { Collection errors = new Collection(); - if (independentErrors != null) + if (independentErrors is not null) { foreach (string error in independentErrors) { diff --git a/src/System.Management.Automation/utils/GraphicalHostReflectionWrapper.cs b/src/System.Management.Automation/utils/GraphicalHostReflectionWrapper.cs index 7579245980b..e8bc5912a92 100644 --- a/src/System.Management.Automation/utils/GraphicalHostReflectionWrapper.cs +++ b/src/System.Management.Automation/utils/GraphicalHostReflectionWrapper.cs @@ -124,17 +124,17 @@ internal static GraphicalHostReflectionWrapper GetGraphicalHostReflectionWrapper returnValue._graphicalHostHelperType = returnValue._graphicalHostAssembly.GetType(graphicalHostHelperTypeName); - Diagnostics.Assert(returnValue._graphicalHostHelperType != null, "the type exists in Microsoft.PowerShell.GraphicalHost"); + Diagnostics.Assert(returnValue._graphicalHostHelperType is not null, "the type exists in Microsoft.PowerShell.GraphicalHost"); ConstructorInfo constructor = returnValue._graphicalHostHelperType.GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { }, null); - if (constructor != null) + if (constructor is not null) { returnValue._graphicalHostHelperObject = constructor.Invoke(new object[] { }); - Diagnostics.Assert(returnValue._graphicalHostHelperObject != null, "the constructor does not throw anything"); + Diagnostics.Assert(returnValue._graphicalHostHelperObject is not null, "the constructor does not throw anything"); } return returnValue; @@ -158,9 +158,9 @@ internal static string EscapeBinding(string propertyName) /// The method return value. internal object CallMethod(string methodName, params object[] arguments) { - Diagnostics.Assert(_graphicalHostHelperObject != null, "there should be a constructor in order to call an instance method"); + Diagnostics.Assert(_graphicalHostHelperObject is not null, "there should be a constructor in order to call an instance method"); MethodInfo method = _graphicalHostHelperType.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance); - Diagnostics.Assert(method != null, "method " + methodName + " exists in graphicalHostHelperType is verified by caller"); + Diagnostics.Assert(method is not null, "method " + methodName + " exists in graphicalHostHelperType is verified by caller"); return method.Invoke(_graphicalHostHelperObject, arguments); } @@ -173,7 +173,7 @@ internal object CallMethod(string methodName, params object[] arguments) internal object CallStaticMethod(string methodName, params object[] arguments) { MethodInfo method = _graphicalHostHelperType.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Static); - Diagnostics.Assert(method != null, "method " + methodName + " exists in graphicalHostHelperType is verified by caller"); + Diagnostics.Assert(method is not null, "method " + methodName + " exists in graphicalHostHelperType is verified by caller"); return method.Invoke(null, arguments); } @@ -184,9 +184,9 @@ internal object CallStaticMethod(string methodName, params object[] arguments) /// The value of an instance property with name internal object GetPropertyValue(string propertyName) { - Diagnostics.Assert(_graphicalHostHelperObject != null, "there should be a constructor in order to get an instance property value"); + Diagnostics.Assert(_graphicalHostHelperObject is not null, "there should be a constructor in order to get an instance property value"); PropertyInfo property = _graphicalHostHelperType.GetProperty(propertyName, BindingFlags.NonPublic | BindingFlags.Instance); - Diagnostics.Assert(property != null, "property " + propertyName + " exists in graphicalHostHelperType is verified by caller"); + Diagnostics.Assert(property is not null, "property " + propertyName + " exists in graphicalHostHelperType is verified by caller"); return property.GetValue(_graphicalHostHelperObject, new object[] { }); } @@ -198,7 +198,7 @@ internal object GetPropertyValue(string propertyName) internal object GetStaticPropertyValue(string propertyName) { PropertyInfo property = _graphicalHostHelperType.GetProperty(propertyName, BindingFlags.NonPublic | BindingFlags.Static); - Diagnostics.Assert(property != null, "property " + propertyName + " exists in graphicalHostHelperType is verified by caller"); + Diagnostics.Assert(property is not null, "property " + propertyName + " exists in graphicalHostHelperType is verified by caller"); return property.GetValue(null, new object[] { }); } @@ -209,10 +209,10 @@ internal object GetStaticPropertyValue(string propertyName) /// True if the is being run remotely. private static bool IsInputFromRemoting(PSCmdlet parentCmdlet) { - Diagnostics.Assert(parentCmdlet.SessionState != null, "SessionState should always be available."); + Diagnostics.Assert(parentCmdlet.SessionState is not null, "SessionState should always be available."); PSVariable senderInfo = parentCmdlet.SessionState.PSVariable.Get("PSSenderInfo"); - return senderInfo != null; + return senderInfo is not null; } } } diff --git a/src/System.Management.Automation/utils/IObjectWriter.cs b/src/System.Management.Automation/utils/IObjectWriter.cs index 5a6afad9514..93038df1397 100644 --- a/src/System.Management.Automation/utils/IObjectWriter.cs +++ b/src/System.Management.Automation/utils/IObjectWriter.cs @@ -175,7 +175,7 @@ public override int Write(object obj, bool enumerateCollection) int numberOfObjectsWritten = 0; IEnumerable enumerable = LanguagePrimitives.GetEnumerable(obj); - if (enumerable != null) + if (enumerable is not null) { foreach (object o in enumerable) { diff --git a/src/System.Management.Automation/utils/MshTraceSource.cs b/src/System.Management.Automation/utils/MshTraceSource.cs index 3afb3124748..07f68cb634c 100644 --- a/src/System.Management.Automation/utils/MshTraceSource.cs +++ b/src/System.Management.Automation/utils/MshTraceSource.cs @@ -135,7 +135,7 @@ internal static PSTraceSource GetTracer( } } - if (keyName != null) + if (keyName is not null) { // Get the pre-configured trace source from the catalog PSTraceSource preconfiguredSource = PSTraceSource.PreConfiguredTraceSource[keyName]; diff --git a/src/System.Management.Automation/utils/ObjectReader.cs b/src/System.Management.Automation/utils/ObjectReader.cs index e7200600a0c..4e0923fb17a 100644 --- a/src/System.Management.Automation/utils/ObjectReader.cs +++ b/src/System.Management.Automation/utils/ObjectReader.cs @@ -503,7 +503,7 @@ internal class PSDataCollectionReader public PSDataCollectionReader(PSDataCollectionStream stream) : base(stream) { - System.Management.Automation.Diagnostics.Assert(stream.ObjectStore != null, + System.Management.Automation.Diagnostics.Assert(stream.ObjectStore is not null, "Stream should have a valid data store"); _enumerator = (PSDataCollectionEnumerator)stream.ObjectStore.GetEnumerator(); } @@ -664,7 +664,7 @@ internal PSDataCollectionPipelineReader(PSDataCollectionStream st string computerName, Guid runspaceId) : base(stream) { - System.Management.Automation.Diagnostics.Assert(stream.ObjectStore != null, + System.Management.Automation.Diagnostics.Assert(stream.ObjectStore is not null, "Stream should have a valid data store"); _datastore = stream.ObjectStore; ComputerName = computerName; diff --git a/src/System.Management.Automation/utils/ObjectStream.cs b/src/System.Management.Automation/utils/ObjectStream.cs index 6526365778a..767be0d87d5 100644 --- a/src/System.Management.Automation/utils/ObjectStream.cs +++ b/src/System.Management.Automation/utils/ObjectStream.cs @@ -903,7 +903,7 @@ private void RaiseEvents() // immediately be re-blocked. However, I am not // confident that multiple sets/resets might not get // out of order and leave the handle in the wrong state. - if (_readWaitHandle != null) + if (_readWaitHandle is not null) { try { @@ -921,7 +921,7 @@ private void RaiseEvents() } } - if (_writeWaitHandle != null) + if (_writeWaitHandle is not null) { try { @@ -992,7 +992,7 @@ private void RaiseEvents() // AutoResetEvents are set to ensure that an exception in an // event delegate does not leave the reset events in a bad // state. - if (unblockWriters && WriteReady != null) + if (unblockWriters && WriteReady is not null) { WriteReady (this, new EventArgs ()); } @@ -1512,23 +1512,23 @@ protected override void Dispose(bool disposing) _writeClosedHandle.Dispose(); _readClosedHandle.Dispose(); - if (_readWaitHandle != null) + if (_readWaitHandle is not null) { _readWaitHandle.Dispose(); } - if (_writeWaitHandle != null) + if (_writeWaitHandle is not null) { _writeWaitHandle.Dispose(); } - if (_reader != null) + if (_reader is not null) { _reader.Close(); _reader.WaitHandle.Dispose(); } - if (_writer != null) + if (_writer is not null) { _writer.Close(); _writer.WaitHandle.Dispose(); @@ -1965,12 +1965,12 @@ protected override void Dispose(bool disposing) Close(); - if (_objectReaderForPipeline != null) + if (_objectReaderForPipeline is not null) { ((PSDataCollectionPipelineReader)_objectReaderForPipeline).Dispose(); } - if (_psobjectReaderForPipeline != null) + if (_psobjectReaderForPipeline is not null) { ((PSDataCollectionPipelineReader)_psobjectReaderForPipeline).Dispose(); } diff --git a/src/System.Management.Automation/utils/ObjectWriter.cs b/src/System.Management.Automation/utils/ObjectWriter.cs index 08e609684c5..f1b889cbed9 100644 --- a/src/System.Management.Automation/utils/ObjectWriter.cs +++ b/src/System.Management.Automation/utils/ObjectWriter.cs @@ -181,7 +181,7 @@ public override int Write(object obj, bool enumerateCollection) /// Standard event args. private void OnWriteReady (object sender, EventArgs args) { - if (WriteReady != null) + if (WriteReady is not null) { // call any event handlers on this, replacing the // ObjectStream sender with 'this' since receivers diff --git a/src/System.Management.Automation/utils/PSTelemetryMethods.cs b/src/System.Management.Automation/utils/PSTelemetryMethods.cs index b440b649c79..b7e19d0fb72 100644 --- a/src/System.Management.Automation/utils/PSTelemetryMethods.cs +++ b/src/System.Management.Automation/utils/PSTelemetryMethods.cs @@ -56,7 +56,7 @@ public static void ReportStartupTelemetry(IHostProvidesTelemetryData ihptd) bool is32Bit = !Environment.Is64BitProcess; var psversion = PSVersionInfo.PSVersion.ToString(); var hostName = Process.GetCurrentProcess().ProcessName; - if (ihptd != null) + if (ihptd is not null) { TelemetryWrapper.TraceMessage("PSHostStart", new { @@ -92,7 +92,7 @@ public static void ReportExitTelemetry(IHostProvidesTelemetryData ihptd) { TelemetryWrapper.TraceMessage("PSHostStop", new { - InteractiveCommandCount = ihptd != null ? ihptd.InteractiveCommandCount : 0, + InteractiveCommandCount = ihptd is not null ? ihptd.InteractiveCommandCount : 0, TabCompletionTimes = s_tabCompletionTimes, TabCompletionCounts = s_tabCompletionCounts, TabCompletionResultCounts = s_tabCompletionResultCounts, @@ -162,11 +162,11 @@ internal static void ReportModuleLoad(PSModuleInfo foundModule) var modulePath = foundModule.Path; var companyName = foundModule.CompanyName; bool couldBeMicrosoftModule = - (modulePath != null && + (modulePath is not null && (modulePath.StartsWith(Utils.DefaultPowerShellAppBase, StringComparison.OrdinalIgnoreCase) || // The following covers both 64 and 32 bit Program Files by assuming 32bit is just ...\Program Files + " (x86)" modulePath.StartsWith(Platform.GetFolderPath(Environment.SpecialFolder.ProgramFiles), StringComparison.OrdinalIgnoreCase))) || - (companyName != null && + (companyName is not null && foundModule.CompanyName.StartsWith("Microsoft", StringComparison.OrdinalIgnoreCase)); if (couldBeMicrosoftModule) { @@ -185,8 +185,8 @@ internal static void ReportLocalSessionCreated( System.Management.Automation.Runspaces.InitialSessionState iss, System.Management.Automation.Host.TranscriptionData transcriptionData) { - bool isConstrained = (iss != null) && (iss.DefaultCommandVisibility != SessionStateEntryVisibility.Public) && (iss.LanguageMode != PSLanguageMode.FullLanguage); - bool isTranscripting = (transcriptionData != null) && (transcriptionData.SystemTranscript != null); + bool isConstrained = (iss is not null) && (iss.DefaultCommandVisibility != SessionStateEntryVisibility.Public) && (iss.LanguageMode != PSLanguageMode.FullLanguage); + bool isTranscripting = (transcriptionData is not null) && (transcriptionData.SystemTranscript is not null); TelemetryWrapper.TraceMessage("PSNewLocalSession", new { @@ -229,7 +229,7 @@ internal static void ReportRemoteSessionCreated( else { System.Management.Automation.Runspaces.WSManConnectionInfo wsManConnectionInfo = connectionInfo as System.Management.Automation.Runspaces.WSManConnectionInfo; - if (wsManConnectionInfo != null) + if (wsManConnectionInfo is not null) { sessionType = RemoteSessionType.WinRMRemote; @@ -251,7 +251,7 @@ internal static void ReportRemoteSessionCreated( else { System.Management.Automation.Runspaces.VMConnectionInfo vmConnectionInfo = connectionInfo as System.Management.Automation.Runspaces.VMConnectionInfo; - if (vmConnectionInfo != null) + if (vmConnectionInfo is not null) { sessionType = RemoteSessionType.HyperVRemote; configurationType = GetConfigurationTypefromName(vmConnectionInfo.ConfigurationName); @@ -259,11 +259,11 @@ internal static void ReportRemoteSessionCreated( else { System.Management.Automation.Runspaces.ContainerConnectionInfo containerConnectionInfo = connectionInfo as System.Management.Automation.Runspaces.ContainerConnectionInfo; - if (containerConnectionInfo != null) + if (containerConnectionInfo is not null) { sessionType = RemoteSessionType.ContainerRemote; configurationType = GetConfigurationTypefromName( - (containerConnectionInfo.ContainerProc != null) ? containerConnectionInfo.ContainerProc.ConfigurationName : string.Empty); + (containerConnectionInfo.ContainerProc is not null) ? containerConnectionInfo.ContainerProc.ConfigurationName : string.Empty); } } } @@ -278,7 +278,7 @@ internal static void ReportRemoteSessionCreated( private static RemoteConfigurationType GetConfigurationTypefromName(string name) { - string configName = (name != null) ? name.Trim() : string.Empty; + string configName = (name is not null) ? name.Trim() : string.Empty; if (string.IsNullOrEmpty(configName) || configName.Equals("microsoft.powershell", StringComparison.OrdinalIgnoreCase) || @@ -316,7 +316,7 @@ private enum ScriptFileType /// internal static void ReportScriptTelemetry(Ast ast, bool dotSourced, long compileTimeInMS) { - if (ast.Parent != null || !TelemetryWrapper.IsEnabled) + if (ast.Parent is not null || !TelemetryWrapper.IsEnabled) return; Task.Run(() => @@ -336,7 +336,7 @@ internal static void ReportScriptTelemetry(Ast ast, bool dotSourced, long compil var scriptFileType = ScriptFileType.None; var fileName = extent.File; - if (fileName != null) + if (fileName is not null) { var ext = System.IO.Path.GetExtension(fileName); if (".ps1".Equals(ext, StringComparison.OrdinalIgnoreCase)) @@ -404,7 +404,7 @@ public override AstVisitAction VisitCommand(CommandAst commandAst) { CountOfCommands++; var commandName = commandAst.GetCommandName(); - if (commandName != null) + if (commandName is not null) { int commandCount; CommandsCalled.TryGetValue(commandName, out commandCount); diff --git a/src/System.Management.Automation/utils/PSTelemetryWrapper.cs b/src/System.Management.Automation/utils/PSTelemetryWrapper.cs index 12932d07fc3..d418564070b 100644 --- a/src/System.Management.Automation/utils/PSTelemetryWrapper.cs +++ b/src/System.Management.Automation/utils/PSTelemetryWrapper.cs @@ -80,7 +80,7 @@ static TelemetryWrapper() internal static bool IsEnabled { - get { return s_eventSourceInstance != null && ((EventSource)s_eventSourceInstance.BaseObject).IsEnabled(); } + get { return s_eventSourceInstance is not null && ((EventSource)s_eventSourceInstance.BaseObject).IsEnabled(); } } /// @@ -125,7 +125,7 @@ internal static bool IsEnabled public static void TraceMessage(string message, T arguments) { - if (s_eventSourceOptionsForWrite != null) + if (s_eventSourceOptionsForWrite is not null) { try { diff --git a/src/System.Management.Automation/utils/ParameterBinderExceptions.cs b/src/System.Management.Automation/utils/ParameterBinderExceptions.cs index ca5a241c86f..3a0e1c886f1 100644 --- a/src/System.Management.Automation/utils/ParameterBinderExceptions.cs +++ b/src/System.Management.Automation/utils/ParameterBinderExceptions.cs @@ -96,7 +96,7 @@ internal ParameterBindingException( _invocationInfo = invocationInfo; - if (_invocationInfo != null) + if (_invocationInfo is not null) { _commandName = invocationInfo.MyCommand.Name; } @@ -105,12 +105,12 @@ internal ParameterBindingException( _parameterType = parameterType; _typeSpecified = typeSpecified; - if ((errorPosition is null) && (_invocationInfo != null)) + if ((errorPosition is null) && (_invocationInfo is not null)) { errorPosition = invocationInfo.ScriptPosition; } - if (errorPosition != null) + if (errorPosition is not null) { _line = errorPosition.StartLineNumber; _offset = errorPosition.StartColumnNumber; @@ -119,7 +119,7 @@ internal ParameterBindingException( _resourceString = resourceString; _errorId = errorId; - if (args != null) + if (args is not null) { _args = args; } @@ -218,7 +218,7 @@ internal ParameterBindingException( errorPosition = invocationInfo.ScriptPosition; } - if (errorPosition != null) + if (errorPosition is not null) { _line = errorPosition.StartLineNumber; _offset = errorPosition.StartColumnNumber; @@ -227,7 +227,7 @@ internal ParameterBindingException( _resourceString = resourceString; _errorId = errorId; - if (args != null) + if (args is not null) { _args = args; } @@ -257,13 +257,13 @@ internal ParameterBindingException( } _invocationInfo = pbex.CommandInvocation; - if (_invocationInfo != null) + if (_invocationInfo is not null) { _commandName = _invocationInfo.MyCommand.Name; } IScriptExtent errorPosition = null; - if (_invocationInfo != null) + if (_invocationInfo is not null) { errorPosition = _invocationInfo.ScriptPosition; } @@ -278,14 +278,14 @@ internal ParameterBindingException( _resourceString = resourceString; - if (args != null) + if (args is not null) { _args = args; } base.SetErrorCategory(pbex.ErrorRecord._category); base.SetErrorId(_errorId); - if (_invocationInfo != null) + if (_invocationInfo is not null) { base.ErrorRecord.SetInvocationInfo(new InvocationInfo(_invocationInfo.MyCommand, errorPosition)); } @@ -494,7 +494,7 @@ private string BuildMessage() { object[] messageArgs = Array.Empty(); - if (_args != null) + if (_args is not null) { messageArgs = new object[_args.Length + 6]; messageArgs[0] = _commandName; @@ -671,7 +671,7 @@ internal ParameterBindingValidationException( args) { ValidationMetadataException validationException = innerException as ValidationMetadataException; - if (validationException != null && validationException.SwallowException) + if (validationException is not null && validationException.SwallowException) { _swallowException = true; } diff --git a/src/System.Management.Automation/utils/ParserException.cs b/src/System.Management.Automation/utils/ParserException.cs index b0aad85c5fc..fe8635a035f 100644 --- a/src/System.Management.Automation/utils/ParserException.cs +++ b/src/System.Management.Automation/utils/ParserException.cs @@ -141,7 +141,7 @@ public ParseException(Language.ParseError[] errors) base.SetErrorId(_errors[0].ErrorId); base.SetErrorCategory(ErrorCategory.ParserError); - if (errors[0].Extent != null) + if (errors[0].Extent is not null) this.ErrorRecord.SetInvocationInfo(new InvocationInfo(null, errors[0].Extent)); } diff --git a/src/System.Management.Automation/utils/PathUtils.cs b/src/System.Management.Automation/utils/PathUtils.cs index ad92bc37fff..203de119427 100644 --- a/src/System.Management.Automation/utils/PathUtils.cs +++ b/src/System.Management.Automation/utils/PathUtils.cs @@ -350,7 +350,7 @@ internal static void ReportWildcardingFailure(Cmdlet cmdlet, string filePath) internal static DirectoryInfo CreateModuleDirectory(PSCmdlet cmdlet, string moduleNameOrPath, bool force) { - Dbg.Assert(cmdlet != null, "Caller should verify cmdlet != null"); + Dbg.Assert(cmdlet is not null, "Caller should verify cmdlet is not null"); Dbg.Assert(!string.IsNullOrEmpty(moduleNameOrPath), "Caller should verify !string.IsNullOrEmpty(moduleNameOrPath)"); DirectoryInfo directoryInfo = null; diff --git a/src/System.Management.Automation/utils/PlatformInvokes.cs b/src/System.Management.Automation/utils/PlatformInvokes.cs index 8e99cdff4b0..608e5ac6579 100644 --- a/src/System.Management.Automation/utils/PlatformInvokes.cs +++ b/src/System.Management.Automation/utils/PlatformInvokes.cs @@ -621,19 +621,19 @@ public void Dispose(bool disposing) { if (disposing) { - if ((this.hStdInput != null) && !this.hStdInput.IsInvalid) + if ((this.hStdInput is not null) && !this.hStdInput.IsInvalid) { this.hStdInput.Dispose(); this.hStdInput = null; } - if ((this.hStdOutput != null) && !this.hStdOutput.IsInvalid) + if ((this.hStdOutput is not null) && !this.hStdOutput.IsInvalid) { this.hStdOutput.Dispose(); this.hStdOutput = null; } - if ((this.hStdError != null) && !this.hStdError.IsInvalid) + if ((this.hStdError is not null) && !this.hStdError.IsInvalid) { this.hStdError.Dispose(); this.hStdError = null; diff --git a/src/System.Management.Automation/utils/PowerShellETWTracer.cs b/src/System.Management.Automation/utils/PowerShellETWTracer.cs index 2812830af7a..3c12ef6083b 100644 --- a/src/System.Management.Automation/utils/PowerShellETWTracer.cs +++ b/src/System.Management.Automation/utils/PowerShellETWTracer.cs @@ -854,7 +854,7 @@ private bool Trace(PowerShellTraceEvent traceEvent, PowerShellTraceLevel level, * Not using locks because the _provider is thread safe itself. **/ - if (args != null) + if (args is not null) { for (int i = 0; i < args.Length; i++) { @@ -1000,11 +1000,11 @@ private bool IsEtwSupported /// public bool TraceErrorRecord(ErrorRecord errorRecord) { - if (errorRecord != null) + if (errorRecord is not null) { Exception exception = errorRecord.Exception; string innerException = "None"; - if (exception.InnerException != null) + if (exception.InnerException is not null) { innerException = exception.InnerException.Message; } @@ -1012,7 +1012,7 @@ public bool TraceErrorRecord(ErrorRecord errorRecord) ErrorCategoryInfo cinfo = errorRecord.CategoryInfo; string message = "None"; - if (errorRecord.ErrorDetails != null) + if (errorRecord.ErrorDetails is not null) { message = errorRecord.ErrorDetails.Message; } @@ -1037,10 +1037,10 @@ public bool TraceErrorRecord(ErrorRecord errorRecord) /// public bool TraceException(Exception exception) { - if (exception != null) + if (exception is not null) { string innerException = "None"; - if (exception.InnerException != null) + if (exception.InnerException is not null) { innerException = exception.InnerException.Message; } @@ -1071,7 +1071,7 @@ public bool TracePowerShellObject(PSObject powerShellObject) /// public bool TraceJob(Job job) { - if (job != null) + if (job is not null) { return DebugChannel.TraceDebug(PowerShellTraceEvent.Job, PowerShellTraceOperationCode.Method, PowerShellTraceTask.None, @@ -1156,7 +1156,7 @@ public void WriteMessage(string className, string methodName, Guid workflowId, J { StringBuilder sb = new StringBuilder(); - if (job != null) + if (job is not null) { try { diff --git a/src/System.Management.Automation/utils/PowerShellExecutionHelper.cs b/src/System.Management.Automation/utils/PowerShellExecutionHelper.cs index e8947b64449..c6b62b4808c 100644 --- a/src/System.Management.Automation/utils/PowerShellExecutionHelper.cs +++ b/src/System.Management.Automation/utils/PowerShellExecutionHelper.cs @@ -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 is not null || streamResults is null || streamResults.Count == 0) { return false; } @@ -71,7 +71,7 @@ internal string ExecuteCommandAndGetResultAsString() Exception exceptionThrown; Collection streamResults = ExecuteCurrentPowerShell(out exceptionThrown); - if (exceptionThrown != null || streamResults is null || streamResults.Count == 0) + if (exceptionThrown is not null || streamResults is null || streamResults.Count == 0) { return null; } @@ -88,7 +88,7 @@ internal string ExecuteCommandAndGetResultAsString() internal Collection ExecuteCommand(string command, bool isScript, out Exception exceptionThrown, Hashtable args) { - Diagnostics.Assert(command != null, "caller to verify command is not null"); + Diagnostics.Assert(command is not null, "caller to verify command is not null"); exceptionThrown = null; @@ -101,7 +101,7 @@ internal Collection ExecuteCommand(string command, bool isScript, out CurrentPowerShell.AddCommand(command); Command cmd = new Command(command, isScript); - if (args != null) + if (args is not null) { foreach (DictionaryEntry arg in args) { @@ -186,10 +186,10 @@ internal static string SafeToString(object obj) { PSObject pso = obj as PSObject; string result; - if (pso != null) + if (pso is not null) { object baseObject = pso.BaseObject; - if (baseObject != null && !(baseObject is PSCustomObject)) + if (baseObject is not null && !(baseObject is PSCustomObject)) result = baseObject.ToString(); else result = pso.ToString(); @@ -235,11 +235,11 @@ internal static PowerShell AddCommandWithPreferenceSetting(this PowerShellExecut internal static PowerShell AddCommandWithPreferenceSetting(this PowerShell powershell, string command, Type type = null) { - Diagnostics.Assert(powershell != null, "the passed-in powershell cannot be null"); + Diagnostics.Assert(powershell is not null, "the passed-in powershell cannot be null"); Diagnostics.Assert(!string.IsNullOrWhiteSpace(command), "the passed-in command name should not be null or whitespaces"); - if (type != null) + if (type is not null) { var cmdletInfo = new CmdletInfo(command, type); diff --git a/src/System.Management.Automation/utils/PsUtils.cs b/src/System.Management.Automation/utils/PsUtils.cs index dc735a92049..9369780d35f 100644 --- a/src/System.Management.Automation/utils/PsUtils.cs +++ b/src/System.Management.Automation/utils/PsUtils.cs @@ -212,7 +212,7 @@ private static class NativeMethods /// Base64 encoded string as the key of the UsingExpressionAst. internal static string GetUsingExpressionKey(Language.UsingExpressionAst usingAst) { - Diagnostics.Assert(usingAst != null, "Caller makes sure the parameter is not null"); + Diagnostics.Assert(usingAst is not null, "Caller makes sure the parameter is not null"); // We cannot call ToLowerInvariant unconditionally, because usingAst might // contain IndexExpressionAst in its SubExpression, such as @@ -435,16 +435,16 @@ internal static Hashtable GetModuleManifestProperties(string psDataFilePath, str string unused1; string unused2; var pipeline = ast.GetSimplePipeline(false, out unused1, out unused2); - if (pipeline != null) + if (pipeline is not null) { var hashtableAst = pipeline.GetPureExpression() as HashtableAst; - if (hashtableAst != null) + if (hashtableAst is not null) { var result = new Hashtable(StringComparer.OrdinalIgnoreCase); foreach (var pair in hashtableAst.KeyValuePairs) { var key = pair.Item1 as StringConstantExpressionAst; - if (key != null && keys.Contains(key.Value, StringComparer.OrdinalIgnoreCase)) + if (key is not null && keys.Contains(key.Value, StringComparer.OrdinalIgnoreCase)) { try { diff --git a/src/System.Management.Automation/utils/ResourceManagerCache.cs b/src/System.Management.Automation/utils/ResourceManagerCache.cs index 7b081edb33c..f9175869778 100644 --- a/src/System.Management.Automation/utils/ResourceManagerCache.cs +++ b/src/System.Management.Automation/utils/ResourceManagerCache.cs @@ -61,7 +61,7 @@ internal static ResourceManager GetResourceManager( { // First do the lookup based on the assembly location - if (s_resourceManagerCache.TryGetValue(assemblyManifestFileLocation, out baseNameCache) && baseNameCache != null) + if (s_resourceManagerCache.TryGetValue(assemblyManifestFileLocation, out baseNameCache) && baseNameCache is not null) { // Now do the lookup based on the resource base name baseNameCache.TryGetValue(baseName, out manager); @@ -75,7 +75,7 @@ internal static ResourceManager GetResourceManager( // Add the new resource manager to the hash - if (baseNameCache != null) + if (baseNameCache is not null) { lock (s_syncRoot) { @@ -103,7 +103,7 @@ internal static ResourceManager GetResourceManager( } Diagnostics.Assert( - manager != null, + manager is not null, "If the manager was not already created, it should have been dynamically created or an exception should have been thrown"); return manager; @@ -227,7 +227,7 @@ private static ResourceManager InitRMWithAssembly(string baseName, Assembly asse { ResourceManager rm = null; - if (baseName != null && assemblyToUse != null) + if (baseName is not null && assemblyToUse is not null) { rm = new ResourceManager(baseName, assemblyToUse); } diff --git a/src/System.Management.Automation/utils/RuntimeException.cs b/src/System.Management.Automation/utils/RuntimeException.cs index 120edd8228e..bfd17616bbf 100644 --- a/src/System.Management.Automation/utils/RuntimeException.cs +++ b/src/System.Management.Automation/utils/RuntimeException.cs @@ -118,7 +118,7 @@ internal RuntimeException(ErrorCategory errorCategory, SetErrorCategory(errorCategory); SetErrorId(errorIdAndResourceId); - if ((errorPosition is null) && (invocationInfo != null)) + if ((errorPosition is null) && (invocationInfo is not null)) { errorPosition = invocationInfo.ScriptPosition; } @@ -216,7 +216,7 @@ internal void SetErrorCategory(ErrorCategory errorCategory) internal void SetTargetObject(object targetObject) { _targetObject = targetObject; - if (_errorRecord != null) + if (_errorRecord is not null) _errorRecord.SetTargetObject(targetObject); } #endregion ErrorRecord @@ -271,10 +271,10 @@ public bool WasThrownFromThrowStatement set { _thrownByThrowStatement = value; - if (_errorRecord != null) + if (_errorRecord is not null) { RuntimeException exception = _errorRecord.Exception as RuntimeException; - if (exception != null) + if (exception is not null) { exception.WasThrownFromThrowStatement = value; } diff --git a/src/System.Management.Automation/utils/SessionStateExceptions.cs b/src/System.Management.Automation/utils/SessionStateExceptions.cs index 1f90aa2b944..534ec140cdc 100644 --- a/src/System.Management.Automation/utils/SessionStateExceptions.cs +++ b/src/System.Management.Automation/utils/SessionStateExceptions.cs @@ -68,7 +68,7 @@ internal ProviderInvocationException(ProviderInfo provider, Exception innerExcep _providerInfo = provider; IContainsErrorRecord icer = innerException as IContainsErrorRecord; - if (icer != null && icer.ErrorRecord != null) + if (icer is not null && icer.ErrorRecord is not null) { _errorRecord = new ErrorRecord(icer.ErrorRecord, innerException); } @@ -204,7 +204,7 @@ internal ProviderInvocationException( } IContainsErrorRecord icer = innerException as IContainsErrorRecord; - if (icer != null && icer.ErrorRecord != null) + if (icer is not null && icer.ErrorRecord is not null) { _errorRecord = new ErrorRecord(icer.ErrorRecord, errorRecordException); } @@ -545,7 +545,7 @@ private static string BuildMessage( params object[] messageArgs) { object[] a; - if (messageArgs != null && 0 < messageArgs.Length) + if (messageArgs is not null && 0 < messageArgs.Length) { a = new object[messageArgs.Length + 1]; a[0] = itemName; diff --git a/src/System.Management.Automation/utils/StringUtil.cs b/src/System.Management.Automation/utils/StringUtil.cs index 469c7a2c024..a5e0d463111 100644 --- a/src/System.Management.Automation/utils/StringUtil.cs +++ b/src/System.Management.Automation/utils/StringUtil.cs @@ -36,7 +36,7 @@ internal static string TruncateToBufferCellWidth(PSHostRawUserInterface rawUI, string toTruncate, int maxWidthInBufferCells) { - Dbg.Assert(rawUI != null, "need a reference"); + Dbg.Assert(rawUI is not null, "need a reference"); Dbg.Assert(maxWidthInBufferCells >= 0, "maxWidthInBufferCells must be positive"); string result; diff --git a/src/System.Management.Automation/utils/StructuredTraceSource.cs b/src/System.Management.Automation/utils/StructuredTraceSource.cs index fb898310059..6ae05590aa5 100644 --- a/src/System.Management.Automation/utils/StructuredTraceSource.cs +++ b/src/System.Management.Automation/utils/StructuredTraceSource.cs @@ -291,7 +291,7 @@ internal PSTraceSource(string fullName, string name, string description, bool tr StringComparison.OrdinalIgnoreCase)) { string options = this.TraceSource.Attributes["Options"]; - if (options != null) + if (options is not null) { _flags = (PSTraceSourceOptions)Enum.Parse(typeof(PSTraceSourceOptions), options, true); } @@ -405,7 +405,7 @@ internal void TracerObjectHeader( "\tDescription: {0}", Description); - if (callingAssembly != null) + if (callingAssembly is not null) { // Assembly name @@ -1116,12 +1116,12 @@ private void FormatOutputLine( // user provided format string together StringBuilder output = new StringBuilder(); - if (classFormatter != null) + if (classFormatter is not null) { output.Append(classFormatter); } - if (format != null) + if (format is not null) { output.AppendFormat( CultureInfo.CurrentCulture, @@ -1347,7 +1347,7 @@ internal void OutputLine( try { Diagnostics.Assert( - format != null, + format is not null, "The format string should not be null"); StringBuilder lineBuilder = new StringBuilder(); @@ -1362,7 +1362,7 @@ internal void OutputLine( // Add the spaces for the indent AddTab(lineBuilder); - if (arg != null) + if (arg is not null) { lineBuilder.AppendFormat( CultureInfo.CurrentCulture, @@ -1650,7 +1650,7 @@ internal ScopeTracer( // Call the helper - if (format != null) + if (format is not null) { ScopeTracerHelper( flag, diff --git a/src/System.Management.Automation/utils/Verbs.cs b/src/System.Management.Automation/utils/Verbs.cs index aeb6a3ee530..bd78d4b11e6 100644 --- a/src/System.Management.Automation/utils/Verbs.cs +++ b/src/System.Management.Automation/utils/Verbs.cs @@ -1104,7 +1104,7 @@ internal static class VerbAliasPrefixes public static string GetVerbAliasPrefix(string verb) { FieldInfo aliasField = typeof(VerbAliasPrefixes).GetField(verb); - if (aliasField != null) + if (aliasField is not null) { return (string)aliasField.GetValue(null); } diff --git a/src/System.Management.Automation/utils/perfCounters/CounterSetInstanceBase.cs b/src/System.Management.Automation/utils/perfCounters/CounterSetInstanceBase.cs index 89b2a69e7b4..a10e8c7a701 100644 --- a/src/System.Management.Automation/utils/perfCounters/CounterSetInstanceBase.cs +++ b/src/System.Management.Automation/utils/perfCounters/CounterSetInstanceBase.cs @@ -246,7 +246,7 @@ private void CreateCounterSetInstance() private void UpdateCounterByValue(CounterData TargetCounterData, long stepAmount) { - Debug.Assert(TargetCounterData != null); + Debug.Assert(TargetCounterData is not null); if (stepAmount == -1) { TargetCounterData.Decrement(); @@ -361,7 +361,7 @@ public override bool UpdateCounterByValue(int counterId, long stepAmount, bool i if (base.RetrieveTargetCounterIdIfValid(counterId, isNumerator, out targetCounterId)) { CounterData targetCounterData = _CounterSetInstance.Counters[targetCounterId]; - if (targetCounterData != null) + if (targetCounterData is not null) { this.UpdateCounterByValue(targetCounterData, stepAmount); return true; @@ -443,7 +443,7 @@ public override bool SetCounterValue(int counterId, long counterValue, bool isNu { CounterData targetCounterData = _CounterSetInstance.Counters[targetCounterId]; - if (targetCounterData != null) + if (targetCounterData is not null) { targetCounterData.Value = counterValue; return true; @@ -527,7 +527,7 @@ public override bool GetCounterValue(int counterId, bool isNumerator, out long c { CounterData targetCounterData = _CounterSetInstance.Counters[targetCounterId]; - if (targetCounterData != null) + if (targetCounterData is not null) { counterValue = targetCounterData.Value; return true; diff --git a/src/System.Management.Automation/utils/tracing/EtwActivity.cs b/src/System.Management.Automation/utils/tracing/EtwActivity.cs index 577c6f72d4d..83bd4b3d6f4 100644 --- a/src/System.Management.Automation/utils/tracing/EtwActivity.cs +++ b/src/System.Management.Automation/utils/tracing/EtwActivity.cs @@ -211,7 +211,7 @@ public CorrelatedCallback(EtwActivity tracer, CallbackWithStateAndArgs callback) /// public void Callback(object state, System.Timers.ElapsedEventArgs args) { - Debug.Assert(callbackWithStateAndArgs != null, "callback is NULL. There MUST always ba a valid callback!"); + Debug.Assert(callbackWithStateAndArgs is not null, "callback is NULL. There MUST always ba a valid callback!"); Correlate(); this.callbackWithStateAndArgs(state, args); @@ -230,7 +230,7 @@ private void Correlate() /// public void Callback() { - Debug.Assert(callbackNoParam != null, "callback is NULL. There MUST always ba a valid callback"); + Debug.Assert(callbackNoParam is not null, "callback is NULL. There MUST always ba a valid callback"); Correlate(); this.callbackNoParam(); @@ -241,7 +241,7 @@ public void Callback() /// public void Callback(object state) { - Debug.Assert(callbackWithState != null, "callback is NULL. There MUST always ba a valid callback!"); + Debug.Assert(callbackWithState is not null, "callback is NULL. There MUST always ba a valid callback!"); Correlate(); this.callbackWithState(state); @@ -252,7 +252,7 @@ public void Callback(object state) /// public void Callback(IAsyncResult asyncResult) { - Debug.Assert(asyncCallback != null, "callback is NULL. There MUST always ba a valid callback!"); + Debug.Assert(asyncCallback is not null, "callback is NULL. There MUST always ba a valid callback!"); Correlate(); this.asyncCallback(asyncResult); @@ -469,7 +469,7 @@ protected void WriteEvent(EventDescriptor ed, params object[] payload) if (!provider.IsEnabled()) return; - if (payload != null) + if (payload is not null) { for (int i = 0; i < payload.Length; i++) { @@ -481,7 +481,7 @@ protected void WriteEvent(EventDescriptor ed, params object[] payload) } bool success = provider.WriteEvent(ref ed, payload); - if (EventWritten != null) + if (EventWritten is not null) { EventWritten.Invoke(this, new EtwEventArgs(ed, success, payload)); } @@ -489,12 +489,12 @@ protected void WriteEvent(EventDescriptor ed, params object[] payload) private EventProvider GetProvider() { - if (currentProvider != null) + if (currentProvider is not null) return currentProvider; lock (syncLock) { - if (currentProvider != null) + if (currentProvider is not null) return currentProvider; if (!providers.TryGetValue(ProviderId, out currentProvider)) diff --git a/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs b/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs index 0b9c972196c..1854378a94b 100755 --- a/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs +++ b/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs @@ -115,7 +115,7 @@ internal override void LogCommandLifecycleEvent(Func getLogContext, LogContext logContext = getLogContext(); StringBuilder payload = new StringBuilder(); - if (logContext.CommandType != null) + if (logContext.CommandType is not null) { if (logContext.CommandType.Equals(StringLiterals.Script, StringComparison.OrdinalIgnoreCase)) { @@ -148,7 +148,7 @@ internal override void LogPipelineExecutionDetailEvent(LogContext logContext, Li { StringBuilder payload = new StringBuilder(); - if (pipelineExecutionDetail != null) + if (pipelineExecutionDetail is not null) { foreach (string detail in pipelineExecutionDetail) { diff --git a/src/System.Management.Automation/utils/tracing/PSSysLogProvider.cs b/src/System.Management.Automation/utils/tracing/PSSysLogProvider.cs index 8e15f10345c..43b6cdb0742 100755 --- a/src/System.Management.Automation/utils/tracing/PSSysLogProvider.cs +++ b/src/System.Management.Automation/utils/tracing/PSSysLogProvider.cs @@ -151,7 +151,7 @@ internal override void LogCommandLifecycleEvent(Func getLogContext, StringBuilder payload = PayloadBuilder; payload.Clear(); - if (logContext.CommandType != null) + if (logContext.CommandType is not null) { if (logContext.CommandType.Equals(StringLiterals.Script, StringComparison.OrdinalIgnoreCase)) { @@ -185,7 +185,7 @@ internal override void LogPipelineExecutionDetailEvent(LogContext logContext, Li StringBuilder payload = PayloadBuilder; payload.Clear(); - if (pipelineExecutionDetail != null) + if (pipelineExecutionDetail is not null) { foreach (string detail in pipelineExecutionDetail) { diff --git a/src/powershell/Program.cs b/src/powershell/Program.cs index e4d3b51c5d6..8d3b1c6b3ae 100644 --- a/src/powershell/Program.cs +++ b/src/powershell/Program.cs @@ -81,7 +81,7 @@ public static int Main(string[] args) private static void AttemptExecPwshLogin(string[] args) { // If the login environment variable is set, we have already done the login logic and have been exec'd - if (Environment.GetEnvironmentVariable(LOGIN_ENV_VAR_NAME) != null) + if (Environment.GetEnvironmentVariable(LOGIN_ENV_VAR_NAME) is not null) { Environment.SetEnvironmentVariable(LOGIN_ENV_VAR_NAME, null); return; diff --git a/test/tools/TestService/Service1.Designer.cs b/test/tools/TestService/Service1.Designer.cs index 861c596757c..d0b33828e7a 100644 --- a/test/tools/TestService/Service1.Designer.cs +++ b/test/tools/TestService/Service1.Designer.cs @@ -8,7 +8,7 @@ partial class Service1 protected override void Dispose(bool disposing) { - if (disposing && (components != null)) + if (disposing && (components is not null)) { components.Dispose(); } diff --git a/test/tools/WebListener/Controllers/CertController.cs b/test/tools/WebListener/Controllers/CertController.cs index bdfe805765f..7c46bcb448b 100644 --- a/test/tools/WebListener/Controllers/CertController.cs +++ b/test/tools/WebListener/Controllers/CertController.cs @@ -20,7 +20,7 @@ public JsonResult Index() { {"Status", "FAILED"} }; - if (HttpContext.Connection.ClientCertificate != null) + if (HttpContext.Connection.ClientCertificate is not null) { output = new Hashtable { diff --git a/test/tools/WebListener/Controllers/ResumeController.cs b/test/tools/WebListener/Controllers/ResumeController.cs index ebcfad40d78..e961f2e6721 100644 --- a/test/tools/WebListener/Controllers/ResumeController.cs +++ b/test/tools/WebListener/Controllers/ResumeController.cs @@ -30,12 +30,12 @@ public async void Index() if (TryGetRangeHeader(out rangeHeader)) { var range = GetRange(rangeHeader); - if(range.From != null) + if(range.From is not null) { from = (int)range.From; } - if(range.To != null) + if(range.To is not null) { to = (int)range.To; } diff --git a/test/xUnit/csharp/test_PSConfiguration.cs b/test/xUnit/csharp/test_PSConfiguration.cs index 7744044338a..c5058ec0c16 100644 --- a/test/xUnit/csharp/test_PSConfiguration.cs +++ b/test/xUnit/csharp/test_PSConfiguration.cs @@ -97,12 +97,12 @@ public PowerShellPolicyFixture() public void Dispose() { CleanupConfigFiles(); - if (systemWideConfigBackupFile != null) + if (systemWideConfigBackupFile is not null) { File.Move(systemWideConfigBackupFile, systemWideConfigFile); } - if (currentUserConfigBackupFile != null) + if (currentUserConfigBackupFile is not null) { File.Move(currentUserConfigBackupFile, currentUserConfigFile); } From c20f29054bb63011c984b6e5999e17537c004882 Mon Sep 17 00:00:00 2001 From: xtqqczze Date: Mon, 27 Jul 2020 11:49:46 +0100 Subject: [PATCH 3/3] Fix CS0037 --- src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs | 4 ++-- .../commands/utility/ImplicitRemotingCommands.cs | 2 +- src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs | 2 +- .../engine/remoting/fanin/WSManPluginFacade.cs | 2 +- .../engine/remoting/fanin/WSManTransportManager.cs | 4 ++-- src/System.Management.Automation/help/CabinetNativeApi.cs | 2 +- .../help/UpdatableHelpModuleInfo.cs | 2 +- src/System.Management.Automation/help/UpdatableHelpUri.cs | 2 +- src/System.Management.Automation/security/Authenticode.cs | 2 +- 9 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs index e111d0e1cae..6863bde18db 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs @@ -462,7 +462,7 @@ private uint GetCounterInfoPlus(IntPtr hCounter, out UInt32 counterType, out UIn defaultScale = 0; timeBase = 0; - Debug.Assert(hCounter is not null); + Debug.Assert(hCounter != null); IntPtr pBufferSize = new IntPtr(0); res = PdhGetCounterInfo(hCounter, false, ref pBufferSize, IntPtr.Zero); @@ -1190,7 +1190,7 @@ public uint ReadNextSet(out PerformanceCounterSampleSet nextSet, bool bSkipReadi UInt64 timeBase = 0; IntPtr hCounter = _consumerPathToHandleAndInstanceMap[path].hCounter; - Debug.Assert(hCounter is not null); + Debug.Assert(hCounter != null); res = GetCounterInfoPlus(hCounter, out counterType, out defaultScale, out timeBase); if (res != 0) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs index 14375897947..26cd01988d5 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs @@ -1915,7 +1915,7 @@ internal ImplicitRemotingCodeGenerator( InvocationInfo invocationInfo) { Dbg.Assert(remoteRunspaceInfo is not null, "Caller should validate remoteRunspaceInfo is not null"); - Dbg.Assert(moduleGuid is not null, "Caller should validate moduleGuid is not null"); + Dbg.Assert(moduleGuid != null, "Caller should validate moduleGuid is not null"); Dbg.Assert(invocationInfo is not null, "Caller should validate invocationInfo is not null"); _remoteRunspaceInfo = remoteRunspaceInfo; diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs index bc5fd9ea88f..146e94a2e7b 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs @@ -1206,7 +1206,7 @@ private void Dispose(bool isDisposingNotFinalizing) if (!_isDisposed) { #if !UNIX - Dbg.Assert(breakHandlerGcHandle is not null, "break handler should be set"); + Dbg.Assert(breakHandlerGcHandle != null, "break handler should be set"); ConsoleControl.RemoveBreakHandler(); if (breakHandlerGcHandle.IsAllocated) { diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs index c3c458ca348..c1c29224bf2 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs @@ -318,7 +318,7 @@ private void populateDelegates() private void CleanUpDelegates() { // Free GCHandles so that the memory they point to may be unpinned (garbage collected) - if (_pluginShellGCHandle is not null) + if (_pluginShellGCHandle != null) { _pluginShellGCHandle.Free(); _pluginReleaseShellContextGCHandle.Free(); diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs index 5dd5751aa5f..4f9d1ad77b0 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs @@ -2280,9 +2280,9 @@ private static void OnRemoteSessionConnectCallback(IntPtr operationContext, } // process returned Xml - Dbg.Assert(data is not null, "WSManConnectShell callback returned null data"); + Dbg.Assert(data != null, "WSManConnectShell callback returned null data"); WSManNativeApi.WSManConnectDataResult connectData = WSManNativeApi.WSManConnectDataResult.UnMarshal(data); - if (connectData.data is not null) + if (connectData.data != null) { byte[] connectResponse = ServerOperationHelpers.ExtractEncodedXmlElement(connectData.data, WSManNativeApi.PS_CONNECTRESPONSE_XML_TAG); sessionTM.ProcessRawData(connectResponse, WSManNativeApi.WSMAN_STREAM_ID_STDOUT); diff --git a/src/System.Management.Automation/help/CabinetNativeApi.cs b/src/System.Management.Automation/help/CabinetNativeApi.cs index 120253f5128..b769ef3c734 100644 --- a/src/System.Management.Automation/help/CabinetNativeApi.cs +++ b/src/System.Management.Automation/help/CabinetNativeApi.cs @@ -152,7 +152,7 @@ private void populateDelegates() private void CleanUpDelegates() { // Free GCHandles so that the memory they point to may be unpinned (garbage collected) - if (_fdiAllocHandle is not null) + if (_fdiAllocHandle != null) { _fdiAllocHandle.Free(); _fdiFreeHandle.Free(); diff --git a/src/System.Management.Automation/help/UpdatableHelpModuleInfo.cs b/src/System.Management.Automation/help/UpdatableHelpModuleInfo.cs index 34d1263c0a2..352ac50a5b5 100644 --- a/src/System.Management.Automation/help/UpdatableHelpModuleInfo.cs +++ b/src/System.Management.Automation/help/UpdatableHelpModuleInfo.cs @@ -28,7 +28,7 @@ internal class UpdatableHelpModuleInfo internal UpdatableHelpModuleInfo(string name, Guid guid, string path, string uri) { Debug.Assert(!string.IsNullOrEmpty(name)); - Debug.Assert(guid is not null); + Debug.Assert(guid != null); Debug.Assert(!string.IsNullOrEmpty(path)); Debug.Assert(!string.IsNullOrEmpty(uri)); diff --git a/src/System.Management.Automation/help/UpdatableHelpUri.cs b/src/System.Management.Automation/help/UpdatableHelpUri.cs index 781780c843b..28683a3e2a8 100644 --- a/src/System.Management.Automation/help/UpdatableHelpUri.cs +++ b/src/System.Management.Automation/help/UpdatableHelpUri.cs @@ -21,7 +21,7 @@ internal class UpdatableHelpUri internal UpdatableHelpUri(string moduleName, Guid moduleGuid, CultureInfo culture, string resolvedUri) { Debug.Assert(!string.IsNullOrEmpty(moduleName)); - Debug.Assert(moduleGuid is not null); + Debug.Assert(moduleGuid != null); Debug.Assert(!string.IsNullOrEmpty(resolvedUri)); ModuleName = moduleName; diff --git a/src/System.Management.Automation/security/Authenticode.cs b/src/System.Management.Automation/security/Authenticode.cs index b3c03fe1b1b..2a19cbd6463 100644 --- a/src/System.Management.Automation/security/Authenticode.cs +++ b/src/System.Management.Automation/security/Authenticode.cs @@ -192,7 +192,7 @@ internal static Signature SignFile(SigningOption option, IntPtr.Zero); #pragma warning restore 56523 - if (si.pSignExtInfo is not null) + if (si.pSignExtInfo != null) { Marshal.DestroyStructure(si.pSignExtInfo); Marshal.FreeCoTaskMem(si.pSignExtInfo);