From 4b4f1d144ff3ff863098a7c61d09d22b3dac313e Mon Sep 17 00:00:00 2001 From: Frode Flaten <3436158+fflaten@users.noreply.github.com> Date: Fri, 29 Jul 2022 06:06:07 +0200 Subject: [PATCH] Use null propagation operator in /engine (#17789) --- .../engine/COM/ComTypeInfo.cs | 10 +-- .../engine/CmdletParameterBinderController.cs | 10 +-- .../PseudoParameterBinder.cs | 5 +- .../engine/CommandInfo.cs | 7 +- .../engine/EventManager.cs | 10 +-- .../engine/ExecutionContext.cs | 32 ++------- .../engine/InternalCommands.cs | 19 +++-- .../engine/Modules/ModuleCmdletBase.cs | 24 +++---- .../engine/MshCmdlet.cs | 9 +-- .../engine/MshCommandRuntime.cs | 5 +- .../engine/NativeCommand.cs | 3 +- .../engine/NativeCommandProcessor.cs | 5 +- .../engine/ParameterBinderBase.cs | 16 ++--- .../engine/Pipe.cs | 6 +- .../engine/SessionStateVariableAPIs.cs | 5 +- .../engine/Utils.cs | 20 ++---- .../engine/debugger/debugger.cs | 63 +++++----------- .../engine/hostifaces/AsyncResult.cs | 5 +- .../hostifaces/InternalHostUserInterface.cs | 37 ++-------- .../engine/hostifaces/LocalConnection.cs | 13 +--- .../engine/hostifaces/LocalPipeline.cs | 5 +- .../engine/hostifaces/PSCommand.cs | 45 +++--------- .../engine/hostifaces/PSDataCollection.cs | 62 +++------------- .../engine/hostifaces/PSTask.cs | 8 +-- .../engine/hostifaces/PowerShell.cs | 72 ++++--------------- .../engine/lang/scriptblock.cs | 5 +- .../engine/parser/Compiler.cs | 5 +- .../engine/parser/Parser.cs | 5 +- .../engine/parser/PreOrderVisitor.cs | 5 +- .../engine/parser/SymbolResolver.cs | 7 +- .../engine/parser/TypeResolver.cs | 5 +- .../engine/parser/VariableAnalysis.cs | 16 +---- .../engine/parser/tokenizer.cs | 5 +- .../engine/pipeline.cs | 5 +- .../engine/runtime/Binding/Binders.cs | 5 +- .../engine/runtime/Operations/MiscOps.cs | 57 ++++----------- 36 files changed, 137 insertions(+), 479 deletions(-) diff --git a/src/System.Management.Automation/engine/COM/ComTypeInfo.cs b/src/System.Management.Automation/engine/COM/ComTypeInfo.cs index 851325e82..eab301db3 100644 --- a/src/System.Management.Automation/engine/COM/ComTypeInfo.cs +++ b/src/System.Management.Automation/engine/COM/ComTypeInfo.cs @@ -183,10 +183,7 @@ namespace System.Management.Automation _properties[strName] = prop; } - if (prop != null) - { - prop.UpdateFuncDesc(funcdesc, index); - } + prop?.UpdateFuncDesc(funcdesc, index); } private void AddMethod(string strName, int index) @@ -198,10 +195,7 @@ namespace System.Management.Automation _methods[strName] = method; } - if (method != null) - { - method.AddFuncDesc(index); - } + method?.AddFuncDesc(index); } /// diff --git a/src/System.Management.Automation/engine/CmdletParameterBinderController.cs b/src/System.Management.Automation/engine/CmdletParameterBinderController.cs index c3de48a43..ee2fec058 100644 --- a/src/System.Management.Automation/engine/CmdletParameterBinderController.cs +++ b/src/System.Management.Automation/engine/CmdletParameterBinderController.cs @@ -202,10 +202,7 @@ namespace System.Management.Automation internal void BindCommandLineParametersNoValidation(Collection arguments) { var psCompiledScriptCmdlet = this.Command as PSScriptCmdlet; - if (psCompiledScriptCmdlet != null) - { - psCompiledScriptCmdlet.PrepareForBinding(this.CommandLineParameters); - } + psCompiledScriptCmdlet?.PrepareForBinding(this.CommandLineParameters); InitUnboundArguments(arguments); CommandMetadata cmdletMetadata = _commandMetadata; @@ -1044,10 +1041,7 @@ namespace System.Management.Automation _commandMetadata.ImplementsDynamicParameters, "The metadata for the dynamic parameters should only be available if the command supports IDynamicParameters"); - if (_dynamicParameterBinder != null) - { - _dynamicParameterBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue, parameter.Parameter); - } + _dynamicParameterBinder?.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue, parameter.Parameter); break; } diff --git a/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs b/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs index 44f18d7c6..97b39cf39 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs @@ -1222,10 +1222,7 @@ namespace System.Management.Automation.Language var parameter = _commandElements[commandIndex] as CommandParameterAst; if (parameter != null) { - if (argumentsToGetDynamicParameters != null) - { - argumentsToGetDynamicParameters.Add(parameter.Extent.Text); - } + argumentsToGetDynamicParameters?.Add(parameter.Extent.Text); AstPair parameterArg = parameter.Argument != null ? new AstPair(parameter) diff --git a/src/System.Management.Automation/engine/CommandInfo.cs b/src/System.Management.Automation/engine/CommandInfo.cs index 1acca145f..eb2e71634 100644 --- a/src/System.Management.Automation/engine/CommandInfo.cs +++ b/src/System.Management.Automation/engine/CommandInfo.cs @@ -467,11 +467,8 @@ namespace System.Management.Automation processInCurrentThread: true, waitForCompletionInCurrentThread: true); - if (eventArgs.Exception != null) - { - // An exception happened on a different thread, rethrow it here on the correct thread. - eventArgs.Exception.Throw(); - } + // An exception happened on a different thread, rethrow it here on the correct thread. + eventArgs.Exception?.Throw(); return eventArgs.Result; } diff --git a/src/System.Management.Automation/engine/EventManager.cs b/src/System.Management.Automation/engine/EventManager.cs index 3df9153f4..783048192 100644 --- a/src/System.Management.Automation/engine/EventManager.cs +++ b/src/System.Management.Automation/engine/EventManager.cs @@ -862,10 +862,7 @@ namespace System.Management.Automation } // Stop the job - if (subscriber.Action != null) - { - subscriber.Action.NotifyJobStopped(); - } + subscriber.Action?.NotifyJobStopped(); lock (_eventSubscribers) { @@ -1532,10 +1529,7 @@ namespace System.Management.Automation { lock (_eventSubscribers) { - if (_timer != null) - { - _timer.Dispose(); - } + _timer?.Dispose(); foreach (PSEventSubscriber currentSubscriber in _eventSubscribers.Keys.ToArray()) { diff --git a/src/System.Management.Automation/engine/ExecutionContext.cs b/src/System.Management.Automation/engine/ExecutionContext.cs index aa13b2aa7..0f2fb0822 100644 --- a/src/System.Management.Automation/engine/ExecutionContext.cs +++ b/src/System.Management.Automation/engine/ExecutionContext.cs @@ -53,22 +53,12 @@ namespace System.Management.Automation /// internal void ResetManagers() { - if (_debugger != null) - { - _debugger.ResetDebugger(); - } - - if (Events != null) - { - Events.Dispose(); - } + _debugger?.ResetDebugger(); + Events?.Dispose(); Events = new PSLocalEventManager(this); - if (this.transactionManager != null) - { - this.transactionManager.Dispose(); - } + this.transactionManager?.Dispose(); this.transactionManager = new PSTransactionManager(); } /// @@ -1155,22 +1145,12 @@ namespace System.Management.Automation { EngineSessionState.RunspaceClosingNotification(); - if (_debugger != null) - { - _debugger.Dispose(); - } - - if (Events != null) - { - Events.Dispose(); - } + _debugger?.Dispose(); + Events?.Dispose(); Events = null; - if (this.transactionManager != null) - { - this.transactionManager.Dispose(); - } + this.transactionManager?.Dispose(); this.transactionManager = null; } diff --git a/src/System.Management.Automation/engine/InternalCommands.cs b/src/System.Management.Automation/engine/InternalCommands.cs index f86478e74..f1c5f57c8 100644 --- a/src/System.Management.Automation/engine/InternalCommands.cs +++ b/src/System.Management.Automation/engine/InternalCommands.cs @@ -919,17 +919,14 @@ namespace Microsoft.PowerShell.Commands // 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) - { - _scripts[i].InvokeUsingCmdlet( - contextCmdlet: this, - useLocalScope: false, - errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, - dollarUnder: InputObject, - input: new object[] { InputObject }, - scriptThis: AutomationNull.Value, - args: Array.Empty()); - } + _scripts[i]?.InvokeUsingCmdlet( + contextCmdlet: this, + useLocalScope: false, + errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, + dollarUnder: InputObject, + input: new object[] { InputObject }, + scriptThis: AutomationNull.Value, + args: Array.Empty()); } } diff --git a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs index eaa4fe4fb..dc5f500f5 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs @@ -5013,17 +5013,14 @@ namespace Microsoft.PowerShell.Commands if (Context.Modules.ModuleTable.ContainsKey(module.Path)) { // We should try to run OnRemove as the very first thing - if (module.OnRemove != null) - { - module.OnRemove.InvokeUsingCmdlet( - contextCmdlet: this, - useLocalScope: true, - errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, - dollarUnder: AutomationNull.Value, - input: AutomationNull.Value, - scriptThis: AutomationNull.Value, - args: new object[] { module }); - } + module.OnRemove?.InvokeUsingCmdlet( + contextCmdlet: this, + useLocalScope: true, + errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, + dollarUnder: AutomationNull.Value, + input: AutomationNull.Value, + scriptThis: AutomationNull.Value, + args: new object[] { module }); if (module.ImplementingAssembly != null && !module.ImplementingAssembly.IsDynamic) { @@ -6893,10 +6890,7 @@ namespace Microsoft.PowerShell.Commands targetSessionState.ModuleTableKeys.Add(moduleTableKey); } - if (targetSessionState.Module != null) - { - targetSessionState.Module.AddNestedModule(module); - } + targetSessionState.Module?.AddNestedModule(module); } /// diff --git a/src/System.Management.Automation/engine/MshCmdlet.cs b/src/System.Management.Automation/engine/MshCmdlet.cs index c11e67466..232140d57 100644 --- a/src/System.Management.Automation/engine/MshCmdlet.cs +++ b/src/System.Management.Automation/engine/MshCmdlet.cs @@ -283,8 +283,7 @@ namespace System.Management.Automation /// public string ExpandString(string source) { - if (_cmdlet != null) - _cmdlet.ThrowIfStopping(); + _cmdlet?.ThrowIfStopping(); return _context.Engine.Expand(source); } @@ -818,8 +817,7 @@ namespace System.Management.Automation IList input, params object[] args) { - if (_cmdlet != null) - _cmdlet.ThrowIfStopping(); + _cmdlet?.ThrowIfStopping(); Cmdlet cmdletToUse = null; ScriptBlock.ErrorHandlingBehavior errorHandlingBehavior = ScriptBlock.ErrorHandlingBehavior.WriteToExternalErrorPipe; @@ -910,8 +908,7 @@ namespace System.Management.Automation /// public ScriptBlock NewScriptBlock(string scriptText) { - if (_commandRuntime != null) - _commandRuntime.ThrowIfStopping(); + _commandRuntime?.ThrowIfStopping(); ScriptBlock result = ScriptBlock.Create(_context, scriptText); return result; diff --git a/src/System.Management.Automation/engine/MshCommandRuntime.cs b/src/System.Management.Automation/engine/MshCommandRuntime.cs index 2050f636e..642020189 100644 --- a/src/System.Management.Automation/engine/MshCommandRuntime.cs +++ b/src/System.Management.Automation/engine/MshCommandRuntime.cs @@ -2395,10 +2395,7 @@ namespace System.Management.Automation if (e == null) throw PSTraceSource.NewArgumentNullException(nameof(e)); - if (PipelineProcessor != null) - { - PipelineProcessor.RecordFailure(e, _thisCommand); - } + PipelineProcessor?.RecordFailure(e, _thisCommand); // 1021203-2005/05/09-JonN // HaltCommandException will cause the command diff --git a/src/System.Management.Automation/engine/NativeCommand.cs b/src/System.Management.Automation/engine/NativeCommand.cs index 822d4cf82..80748605a 100644 --- a/src/System.Management.Automation/engine/NativeCommand.cs +++ b/src/System.Management.Automation/engine/NativeCommand.cs @@ -26,8 +26,7 @@ namespace System.Management.Automation { try { - if (_myCommandProcessor != null) - _myCommandProcessor.StopProcessing(); + _myCommandProcessor?.StopProcessing(); } catch (Exception) { diff --git a/src/System.Management.Automation/engine/NativeCommandProcessor.cs b/src/System.Management.Automation/engine/NativeCommandProcessor.cs index 0077e13d9..1538da813 100644 --- a/src/System.Management.Automation/engine/NativeCommandProcessor.cs +++ b/src/System.Management.Automation/engine/NativeCommandProcessor.cs @@ -2126,10 +2126,7 @@ namespace System.Management.Automation { if (_inputFormat == NativeCommandIOFormat.Xml) { - if (_xmlSerializer != null) - { - _xmlSerializer.Done(); - } + _xmlSerializer?.Done(); } else // Text { diff --git a/src/System.Management.Automation/engine/ParameterBinderBase.cs b/src/System.Management.Automation/engine/ParameterBinderBase.cs index 4d72055b1..e190c4aac 100644 --- a/src/System.Management.Automation/engine/ParameterBinderBase.cs +++ b/src/System.Management.Automation/engine/ParameterBinderBase.cs @@ -559,15 +559,13 @@ namespace System.Management.Automation parameterMetadata.ObsoleteAttribute.Message); var mshCommandRuntime = this.Command.commandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) - { - // Write out warning only if we are in the context of MshCommandRuntime. - // This is because - // 1. The overload method WriteWarning(WarningRecord) is only available in MshCommandRuntime; - // 2. We write out warnings for obsolete commands and obsolete cmdlet parameters only when in - // the context of MshCommandRuntime. So we do it here to keep consistency. - mshCommandRuntime.WriteWarning(new WarningRecord(FQIDParameterObsolete, obsoleteWarning)); - } + + // Write out warning only if we are in the context of MshCommandRuntime. + // This is because + // 1. The overload method WriteWarning(WarningRecord) is only available in MshCommandRuntime; + // 2. We write out warnings for obsolete commands and obsolete cmdlet parameters only when in + // the context of MshCommandRuntime. So we do it here to keep consistency. + mshCommandRuntime?.WriteWarning(new WarningRecord(FQIDParameterObsolete, obsoleteWarning)); } // Finally bind the argument to the parameter diff --git a/src/System.Management.Automation/engine/Pipe.cs b/src/System.Management.Automation/engine/Pipe.cs index c4050a2e8..d43a0f96a 100644 --- a/src/System.Management.Automation/engine/Pipe.cs +++ b/src/System.Management.Automation/engine/Pipe.cs @@ -603,11 +603,7 @@ namespace System.Management.Automation.Internal /// /// Removes all the objects from the Pipe. /// - internal void Clear() - { - if (ObjectQueue != null) - ObjectQueue.Clear(); - } + internal void Clear() => ObjectQueue?.Clear(); /// /// Returns the currently queued items in the pipe. Note that this will diff --git a/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs b/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs index 45d8db280..336c2b779 100644 --- a/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs @@ -1827,10 +1827,7 @@ namespace System.Management.Automation dottedScope.GetVariableTable(result, includePrivate); } - if (scope.LocalsTuple != null) - { - scope.LocalsTuple.GetVariableTable(result, includePrivate); - } + scope.LocalsTuple?.GetVariableTable(result, includePrivate); } /// diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index eb6adb8b7..a252f1c24 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -1067,10 +1067,7 @@ namespace System.Management.Automation finally { context.AutoLoadingModuleInProgress.Remove(module); - if (ps != null) - { - ps.Dispose(); - } + ps?.Dispose(); } } } @@ -1127,10 +1124,7 @@ namespace System.Management.Automation } finally { - if (ps != null) - { - ps.Dispose(); - } + ps?.Dispose(); } return result; @@ -1188,10 +1182,7 @@ namespace System.Management.Automation } finally { - if (ps != null) - { - ps.Dispose(); - } + ps?.Dispose(); } return result; @@ -1617,10 +1608,7 @@ namespace System.Management.Automation.Internal public static void SetTestHook(string property, object value) { var fieldInfo = typeof(InternalTestHooks).GetField(property, BindingFlags.Static | BindingFlags.NonPublic); - if (fieldInfo != null) - { - fieldInfo.SetValue(null, value); - } + fieldInfo?.SetValue(null, value); } /// diff --git a/src/System.Management.Automation/engine/debugger/debugger.cs b/src/System.Management.Automation/engine/debugger/debugger.cs index ced9b4ed6..149fca2a6 100644 --- a/src/System.Management.Automation/engine/debugger/debugger.cs +++ b/src/System.Management.Automation/engine/debugger/debugger.cs @@ -2386,10 +2386,7 @@ namespace System.Management.Automation } PowerShell ps = _psDebuggerCommand; - if (ps != null) - { - ps.BeginStop(null, null); - } + ps?.BeginStop(null, null); } /// @@ -3240,11 +3237,7 @@ namespace System.Management.Automation try { Debugger nestedDebugger = item.NestedDebugger; - - if (nestedDebugger != null) - { - nestedDebugger.SetDebuggerStepMode(enableStepping); - } + nestedDebugger?.SetDebuggerStepMode(enableStepping); } catch (PSNotImplementedException) { } } @@ -4536,10 +4529,7 @@ namespace System.Management.Automation // 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) - { - serverRemoteDebugger.ReleaseAndRaiseDebugStopLocal(); - } + serverRemoteDebugger?.ReleaseAndRaiseDebugStopLocal(); } } @@ -4951,10 +4941,7 @@ namespace System.Management.Automation else { Pipeline pipelineCommand = runningCmd as Pipeline; - if (pipelineCommand != null) - { - pipelineCommand.ResumeIncomingData(); - } + pipelineCommand?.ResumeIncomingData(); } } @@ -5329,47 +5316,29 @@ namespace System.Management.Automation private static void WriteLine(string line, PSHost host, IList output) { - if (host != null) - { - host.UI.WriteLine(line); - } + host?.UI.WriteLine(line); - if (output != null) - { - output.Add(new PSObject(line)); - } + output?.Add(new PSObject(line)); } private static void WriteCR(PSHost host, IList output) { - if (host != null) - { - host.UI.WriteLine(); - } + host?.UI.WriteLine(); - if (output != null) - { - output.Add(new PSObject(Crlf)); - } + output?.Add(new PSObject(Crlf)); } private static void WriteErrorLine(string error, PSHost host, IList output) { - if (host != null) - { - host.UI.WriteErrorLine(error); - } + host?.UI.WriteErrorLine(error); - if (output != null) - { - output.Add( - new PSObject( - new ErrorRecord( - new RuntimeException(error), - "DebuggerError", - ErrorCategory.InvalidOperation, - null))); - } + output?.Add( + new PSObject( + new ErrorRecord( + new RuntimeException(error), + "DebuggerError", + ErrorCategory.InvalidOperation, + null))); } } diff --git a/src/System.Management.Automation/engine/hostifaces/AsyncResult.cs b/src/System.Management.Automation/engine/hostifaces/AsyncResult.cs index 30e28d765..74bcefae2 100644 --- a/src/System.Management.Automation/engine/hostifaces/AsyncResult.cs +++ b/src/System.Management.Automation/engine/hostifaces/AsyncResult.cs @@ -175,10 +175,7 @@ namespace System.Management.Automation.Runspaces { lock (SyncObject) { - if (_completedWaitHandle != null) - { - _completedWaitHandle.Set(); - } + _completedWaitHandle?.Set(); } } diff --git a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs index 57f3f675f..1e820196c 100644 --- a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs @@ -338,13 +338,7 @@ namespace System.Management.Automation.Internal.Host /// Writes the DebugRecord to informational buffers. /// /// DebugRecord. - internal void WriteDebugInfoBuffers(DebugRecord record) - { - if (_informationalBuffers != null) - { - _informationalBuffers.AddDebug(record); - } - } + internal void WriteDebugInfoBuffers(DebugRecord record) => _informationalBuffers?.AddDebug(record); /// /// Helper function for WriteDebugLine. @@ -538,10 +532,7 @@ namespace System.Management.Automation.Internal.Host } // Write to Information Buffers - if (_informationalBuffers != null) - { - _informationalBuffers.AddProgress(record); - } + _informationalBuffers?.AddProgress(record); if (_externalUI == null) { @@ -588,13 +579,7 @@ namespace System.Management.Automation.Internal.Host /// Writes the VerboseRecord to informational buffers. /// /// VerboseRecord. - internal void WriteVerboseInfoBuffers(VerboseRecord record) - { - if (_informationalBuffers != null) - { - _informationalBuffers.AddVerbose(record); - } - } + internal void WriteVerboseInfoBuffers(VerboseRecord record) => _informationalBuffers?.AddVerbose(record); /// /// See base class. @@ -631,13 +616,7 @@ namespace System.Management.Automation.Internal.Host /// Writes the WarningRecord to informational buffers. /// /// WarningRecord. - internal void WriteWarningInfoBuffers(WarningRecord record) - { - if (_informationalBuffers != null) - { - _informationalBuffers.AddWarning(record); - } - } + internal void WriteWarningInfoBuffers(WarningRecord record) => _informationalBuffers?.AddWarning(record); /// /// @@ -657,13 +636,7 @@ namespace System.Management.Automation.Internal.Host /// Writes the InformationRecord to informational buffers. /// /// WarningRecord. - internal void WriteInformationInfoBuffers(InformationRecord record) - { - if (_informationalBuffers != null) - { - _informationalBuffers.AddInformation(record); - } - } + internal void WriteInformationInfoBuffers(InformationRecord record) => _informationalBuffers?.AddInformation(record); internal static Type GetFieldType(FieldDescription field) { diff --git a/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs b/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs index 62ff66dff..e640e6f11 100644 --- a/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs +++ b/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs @@ -834,18 +834,14 @@ namespace System.Management.Automation.Runspaces if (executionContext != null) { PSHostUserInterface hostUI = executionContext.EngineHostInterface.UI; - if (hostUI != null) - { - hostUI.StopAllTranscribing(); - } + hostUI?.StopAllTranscribing(); } AmsiUtils.Uninitialize(); } // Generate the shutdown event - if (Events != null) - Events.GenerateEvent(PSEngineEvent.Exiting, null, Array.Empty(), null, true, false); + Events?.GenerateEvent(PSEngineEvent.Exiting, null, Array.Empty(), null, true, false); // Stop all running pipelines // Note:Do not perform the Cancel in lock. Reason is @@ -1266,10 +1262,7 @@ namespace System.Management.Automation.Runspaces base.Close(); // call base.Close() first to make it stop the pipeline - if (_pipelineThread != null) - { - _pipelineThread.Close(); - } + _pipelineThread?.Close(); } #endregion IDisposable Members diff --git a/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs b/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs index 5392c1781..f77fda65f 100644 --- a/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs +++ b/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs @@ -487,10 +487,7 @@ namespace System.Management.Automation.Runspaces } PSLocalEventManager eventManager = LocalRunspace.Events as PSLocalEventManager; - if (eventManager != null) - { - eventManager.ProcessPendingActions(); - } + eventManager?.ProcessPendingActions(); // restore the trap state... this.LocalRunspace.ExecutionContext.PropagateExceptionsToEnclosingStatementBlock = oldTrapState; diff --git a/src/System.Management.Automation/engine/hostifaces/PSCommand.cs b/src/System.Management.Automation/engine/hostifaces/PSCommand.cs index 32ec57e08..6db408503 100644 --- a/src/System.Management.Automation/engine/hostifaces/PSCommand.cs +++ b/src/System.Management.Automation/engine/hostifaces/PSCommand.cs @@ -92,10 +92,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException(nameof(command)); } - if (_owner != null) - { - _owner.AssertChangesAreAccepted(); - } + _owner?.AssertChangesAreAccepted(); _currentCommand = new Command(command, false); _commands.Add(_currentCommand); @@ -136,10 +133,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException(nameof(cmdlet)); } - if (_owner != null) - { - _owner.AssertChangesAreAccepted(); - } + _owner?.AssertChangesAreAccepted(); _currentCommand = new Command(cmdlet, false, useLocalScope); _commands.Add(_currentCommand); @@ -178,10 +172,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException(nameof(script)); } - if (_owner != null) - { - _owner.AssertChangesAreAccepted(); - } + _owner?.AssertChangesAreAccepted(); _currentCommand = new Command(script, true); _commands.Add(_currentCommand); @@ -223,10 +214,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException(nameof(script)); } - if (_owner != null) - { - _owner.AssertChangesAreAccepted(); - } + _owner?.AssertChangesAreAccepted(); _currentCommand = new Command(script, true, useLocalScope); _commands.Add(_currentCommand); @@ -261,10 +249,7 @@ namespace System.Management.Automation throw PSTraceSource.NewArgumentNullException(nameof(command)); } - if (_owner != null) - { - _owner.AssertChangesAreAccepted(); - } + _owner?.AssertChangesAreAccepted(); _currentCommand = command; _commands.Add(_currentCommand); @@ -309,10 +294,7 @@ namespace System.Management.Automation new object[] { "PSCommand" }); } - if (_owner != null) - { - _owner.AssertChangesAreAccepted(); - } + _owner?.AssertChangesAreAccepted(); _currentCommand.Parameters.Add(parameterName, value); return this; @@ -352,10 +334,7 @@ namespace System.Management.Automation new object[] { "PSCommand" }); } - if (_owner != null) - { - _owner.AssertChangesAreAccepted(); - } + _owner?.AssertChangesAreAccepted(); _currentCommand.Parameters.Add(parameterName, true); return this; @@ -372,10 +351,7 @@ namespace System.Management.Automation new object[] { "PSCommand" }); } - if (_owner != null) - { - _owner.AssertChangesAreAccepted(); - } + _owner?.AssertChangesAreAccepted(); _currentCommand.Parameters.Add(parameter); return this; @@ -415,10 +391,7 @@ namespace System.Management.Automation new object[] { "PSCommand" }); } - if (_owner != null) - { - _owner.AssertChangesAreAccepted(); - } + _owner?.AssertChangesAreAccepted(); _currentCommand.Parameters.Add(null, value); return this; diff --git a/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs b/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs index 516bc4869..9f928eca2 100644 --- a/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs +++ b/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs @@ -553,11 +553,8 @@ namespace System.Management.Automation // raise the events outside of the lock. if (raiseEvents) { - if (_readWaitHandle != null) - { - // unblock any readers waiting on the handle - _readWaitHandle.Set(); - } + // unblock any readers waiting on the handle + _readWaitHandle?.Set(); // A temporary variable is used as the Completed may // reach null (because of -='s) after the null check @@ -798,10 +795,7 @@ namespace System.Management.Automation { lock (SyncObject) { - if (_data != null) - { - _data.Clear(); - } + _data?.Clear(); } } @@ -1557,10 +1551,7 @@ namespace System.Management.Automation if (_refCount != 0 && (!_blockingEnumerator || _refCount != 1)) return; // release threads blocked on waithandle - if (_readWaitHandle != null) - { - _readWaitHandle.Set(); - } + _readWaitHandle?.Set(); // release any threads to notify refCount is 0. Enumerator // blocks on this syncObject and it needs to be notified @@ -1792,10 +1783,7 @@ namespace System.Management.Automation _readWaitHandle = null; } - if (_data != null) - { - _data.Clear(); - } + _data?.Clear(); } } } @@ -2096,65 +2084,35 @@ namespace System.Management.Automation /// The item is added to the buffer along with PowerShell InstanceId. /// /// - internal void AddProgress(ProgressRecord item) - { - if (progress != null) - { - progress.InternalAdd(_psInstanceId, item); - } - } + internal void AddProgress(ProgressRecord item) => progress?.InternalAdd(_psInstanceId, item); /// /// Adds item to the verbose buffer. /// The item is added to the buffer along with PowerShell InstanceId. /// /// - internal void AddVerbose(VerboseRecord item) - { - if (verbose != null) - { - verbose.InternalAdd(_psInstanceId, item); - } - } + internal void AddVerbose(VerboseRecord item) => verbose?.InternalAdd(_psInstanceId, item); /// /// Adds item to the debug buffer. /// The item is added to the buffer along with PowerShell InstanceId. /// /// - internal void AddDebug(DebugRecord item) - { - if (debug != null) - { - debug.InternalAdd(_psInstanceId, item); - } - } + internal void AddDebug(DebugRecord item) => debug?.InternalAdd(_psInstanceId, item); /// /// Adds item to the warning buffer. /// The item is added to the buffer along with PowerShell InstanceId. /// /// - internal void AddWarning(WarningRecord item) - { - if (Warning != null) - { - Warning.InternalAdd(_psInstanceId, item); - } - } + internal void AddWarning(WarningRecord item) => Warning?.InternalAdd(_psInstanceId, item); /// /// Adds item to the information buffer. /// The item is added to the buffer along with PowerShell InstanceId. /// /// - internal void AddInformation(InformationRecord item) - { - if (Information != null) - { - Information.InternalAdd(_psInstanceId, item); - } - } + internal void AddInformation(InformationRecord item) => Information?.InternalAdd(_psInstanceId, item); #endregion } diff --git a/src/System.Management.Automation/engine/hostifaces/PSTask.cs b/src/System.Management.Automation/engine/hostifaces/PSTask.cs index d7e500203..fb492706a 100644 --- a/src/System.Management.Automation/engine/hostifaces/PSTask.cs +++ b/src/System.Management.Automation/engine/hostifaces/PSTask.cs @@ -496,13 +496,7 @@ namespace System.Management.Automation.PSTasks /// /// Signals the running task to stop. /// - public void SignalStop() - { - if (_powershell != null) - { - _powershell.BeginStop(null, null); - } - } + public void SignalStop() => _powershell?.BeginStop(null, null); #endregion } diff --git a/src/System.Management.Automation/engine/hostifaces/PowerShell.cs b/src/System.Management.Automation/engine/hostifaces/PowerShell.cs index 91b657511..07d17589c 100644 --- a/src/System.Management.Automation/engine/hostifaces/PowerShell.cs +++ b/src/System.Management.Automation/engine/hostifaces/PowerShell.cs @@ -4161,10 +4161,7 @@ namespace System.Management.Automation _runspace.Dispose(); } - if (RemotePowerShell != null) - { - RemotePowerShell.Dispose(); - } + RemotePowerShell?.Dispose(); _invokeAsyncResult = null; _stopAsyncResult = null; @@ -4178,10 +4175,7 @@ namespace System.Management.Automation { lock (_syncObject) { - if (_worker != null) - { - _worker.InternalClearSuppressExceptions(); - } + _worker?.InternalClearSuppressExceptions(); } } @@ -4307,10 +4301,7 @@ namespace System.Management.Automation { if (RunningExtraCommands) { - if (tempInvokeAsyncResult != null) - { - tempInvokeAsyncResult.SetAsCompleted(InvocationStateInfo.Reason); - } + tempInvokeAsyncResult?.SetAsCompleted(InvocationStateInfo.Reason); RaiseStateChangeEvent(InvocationStateInfo.Clone()); } @@ -4318,16 +4309,10 @@ namespace System.Management.Automation { RaiseStateChangeEvent(InvocationStateInfo.Clone()); - if (tempInvokeAsyncResult != null) - { - tempInvokeAsyncResult.SetAsCompleted(InvocationStateInfo.Reason); - } + tempInvokeAsyncResult?.SetAsCompleted(InvocationStateInfo.Reason); } - if (tempStopAsyncResult != null) - { - tempStopAsyncResult.SetAsCompleted(null); - } + tempStopAsyncResult?.SetAsCompleted(null); } catch (Exception) { @@ -4366,10 +4351,7 @@ namespace System.Management.Automation // 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) - { - tempStopAsyncResult.SetAsCompleted(null); - } + tempStopAsyncResult?.SetAsCompleted(null); // Only raise the Disconnected state changed event if the PowerShell state // actually transitions to Disconnected from some other state. This condition @@ -4435,10 +4417,7 @@ namespace System.Management.Automation { lock (_syncObject) { - if (RemotePowerShell != null) - { - RemotePowerShell.Clear(); - } + RemotePowerShell?.Clear(); } } @@ -5152,11 +5131,8 @@ namespace System.Management.Automation // cannot complete with this object. if (isDisconnected) { - if (_invokeAsyncResult != null) - { - // Since object is stopped, allow result wait to end. - _invokeAsyncResult.SetAsCompleted(null); - } + // Since object is stopped, allow result wait to end. + _invokeAsyncResult?.SetAsCompleted(null); _stopAsyncResult.SetAsCompleted(null); @@ -5217,10 +5193,7 @@ namespace System.Management.Automation private void ReleaseDebugger() { LocalRunspace localRunspace = _runspace as LocalRunspace; - if (localRunspace != null) - { - localRunspace.ReleaseDebugger(); - } + localRunspace?.ReleaseDebugger(); } /// @@ -5321,10 +5294,7 @@ namespace System.Management.Automation else { RemoteRunspacePoolInternal remoteRunspacePoolInternal = GetRemoteRunspacePoolInternal(); - if (remoteRunspacePoolInternal != null) - { - remoteRunspacePoolInternal.PushRunningPowerShell(this); - } + remoteRunspacePoolInternal?.PushRunningPowerShell(this); } } @@ -5340,10 +5310,7 @@ namespace System.Management.Automation else { RemoteRunspacePoolInternal remoteRunspacePoolInternal = GetRemoteRunspacePoolInternal(); - if (remoteRunspacePoolInternal != null) - { - remoteRunspacePoolInternal.PopRunningPowerShell(); - } + remoteRunspacePoolInternal?.PopRunningPowerShell(); } } @@ -5712,10 +5679,7 @@ namespace System.Management.Automation else { RunspacePool pool = _shell._rsConnection as RunspacePool; - if (pool != null) - { - pool.ReleaseRunspace(CurrentlyRunningPipeline.Runspace); - } + pool?.ReleaseRunspace(CurrentlyRunningPipeline.Runspace); } CurrentlyRunningPipeline.Dispose(); @@ -5886,10 +5850,7 @@ namespace System.Management.Automation throw new PSNotSupportedException(); } - if (RemotePowerShell.DataStructureHandler != null) - { - RemotePowerShell.DataStructureHandler.TransportManager.SuspendQueue(true); - } + RemotePowerShell.DataStructureHandler?.TransportManager.SuspendQueue(true); } /// @@ -5902,10 +5863,7 @@ namespace System.Management.Automation throw new PSNotSupportedException(); } - if (RemotePowerShell.DataStructureHandler != null) - { - RemotePowerShell.DataStructureHandler.TransportManager.ResumeQueue(); - } + RemotePowerShell.DataStructureHandler?.TransportManager.ResumeQueue(); } /// diff --git a/src/System.Management.Automation/engine/lang/scriptblock.cs b/src/System.Management.Automation/engine/lang/scriptblock.cs index 1ce9c9a42..451d015fd 100644 --- a/src/System.Management.Automation/engine/lang/scriptblock.cs +++ b/src/System.Management.Automation/engine/lang/scriptblock.cs @@ -1035,10 +1035,7 @@ namespace System.Management.Automation processInCurrentThread: true, waitForCompletionInCurrentThread: true); - if (scriptBlockInvocationEventArgs.Exception != null) - { - scriptBlockInvocationEventArgs.Exception.Throw(); - } + scriptBlockInvocationEventArgs.Exception?.Throw(); } } diff --git a/src/System.Management.Automation/engine/parser/Compiler.cs b/src/System.Management.Automation/engine/parser/Compiler.cs index dab439bd5..cdf053dcb 100644 --- a/src/System.Management.Automation/engine/parser/Compiler.cs +++ b/src/System.Management.Automation/engine/parser/Compiler.cs @@ -6965,10 +6965,7 @@ namespace System.Management.Automation.Language compiler.PopLabelBlock(LabelScopeKind.Statement); // If enterLoop is null, we will never JIT compile the loop. - if (enterLoop != null) - { - enterLoop.FinishLoop(compiler.Instructions.Count); - } + enterLoop?.FinishLoop(compiler.Instructions.Count); } } diff --git a/src/System.Management.Automation/engine/parser/Parser.cs b/src/System.Management.Automation/engine/parser/Parser.cs index 4a42dd262..31e7618a3 100644 --- a/src/System.Management.Automation/engine/parser/Parser.cs +++ b/src/System.Management.Automation/engine/parser/Parser.cs @@ -3080,10 +3080,7 @@ namespace System.Management.Automation.Language } finally { - if (p != null) - { - p.Dispose(); - } + p?.Dispose(); // // Put the parser back... diff --git a/src/System.Management.Automation/engine/parser/PreOrderVisitor.cs b/src/System.Management.Automation/engine/parser/PreOrderVisitor.cs index 33b2fadec..91c0c6247 100644 --- a/src/System.Management.Automation/engine/parser/PreOrderVisitor.cs +++ b/src/System.Management.Automation/engine/parser/PreOrderVisitor.cs @@ -37,10 +37,7 @@ namespace System.Management.Automation.Language internal AstVisitAction CheckForPostAction(Ast ast, AstVisitAction action) { var postActionHandler = this as IAstPostVisitHandler; - if (postActionHandler != null) - { - postActionHandler.PostVisit(ast); - } + postActionHandler?.PostVisit(ast); return action; } diff --git a/src/System.Management.Automation/engine/parser/SymbolResolver.cs b/src/System.Management.Automation/engine/parser/SymbolResolver.cs index b97496dcc..18f694bf7 100644 --- a/src/System.Management.Automation/engine/parser/SymbolResolver.cs +++ b/src/System.Management.Automation/engine/parser/SymbolResolver.cs @@ -111,11 +111,8 @@ namespace System.Management.Automation.Language TypeLookupResult result; if (_typeTable.TryGetValue(typeDefinitionAst.Name, out result)) { - if (result.ExternalNamespaces != null) - { - // override external type by the type defined in the current namespace - result.ExternalNamespaces.Add(moduleInfo.Name); - } + // override external type by the type defined in the current namespace + result.ExternalNamespaces?.Add(moduleInfo.Name); } else { diff --git a/src/System.Management.Automation/engine/parser/TypeResolver.cs b/src/System.Management.Automation/engine/parser/TypeResolver.cs index acbf9bef2..83d031686 100644 --- a/src/System.Management.Automation/engine/parser/TypeResolver.cs +++ b/src/System.Management.Automation/engine/parser/TypeResolver.cs @@ -927,10 +927,7 @@ namespace System.Management.Automation public static bool Remove(string typeName) { userTypeAccelerators.Remove(typeName); - if (s_allTypeAccelerators != null) - { - s_allTypeAccelerators.Remove(typeName); - } + s_allTypeAccelerators?.Remove(typeName); return true; } diff --git a/src/System.Management.Automation/engine/parser/VariableAnalysis.cs b/src/System.Management.Automation/engine/parser/VariableAnalysis.cs index e07329c99..8bf14d79a 100644 --- a/src/System.Management.Automation/engine/parser/VariableAnalysis.cs +++ b/src/System.Management.Automation/engine/parser/VariableAnalysis.cs @@ -1302,10 +1302,7 @@ namespace System.Management.Automation.Language public object VisitForStatement(ForStatementAst forStatementAst) { - if (forStatementAst.Initializer != null) - { - forStatementAst.Initializer.Accept(this); - } + forStatementAst.Initializer?.Accept(this); var generateCondition = forStatementAst.Condition != null ? () => forStatementAst.Condition.Accept(this) @@ -1453,10 +1450,7 @@ namespace System.Management.Automation.Language private Block ControlFlowStatement(PipelineBaseAst pipelineAst) { - if (pipelineAst != null) - { - pipelineAst.Accept(this); - } + pipelineAst?.Accept(this); _currentBlock.FlowsTo(_exitBlock); var lastBlockInStatement = _currentBlock; @@ -1627,11 +1621,7 @@ namespace System.Management.Automation.Language public object VisitCommandParameter(CommandParameterAst commandParameterAst) { - if (commandParameterAst.Argument != null) - { - commandParameterAst.Argument.Accept(this); - } - + commandParameterAst.Argument?.Accept(this); return null; } diff --git a/src/System.Management.Automation/engine/parser/tokenizer.cs b/src/System.Management.Automation/engine/parser/tokenizer.cs index 664dbe0ac..1c5654b34 100644 --- a/src/System.Management.Automation/engine/parser/tokenizer.cs +++ b/src/System.Management.Automation/engine/parser/tokenizer.cs @@ -1226,10 +1226,7 @@ namespace System.Management.Automation.Language private T SaveToken(T token) where T : Token { - if (TokenList != null) - { - TokenList.Add(token); - } + TokenList?.Add(token); // Keep track of the first and last token even if we're not saving tokens // for the special variables $$ and $^. diff --git a/src/System.Management.Automation/engine/pipeline.cs b/src/System.Management.Automation/engine/pipeline.cs index 7212b5793..3373b5e56 100644 --- a/src/System.Management.Automation/engine/pipeline.cs +++ b/src/System.Management.Automation/engine/pipeline.cs @@ -213,10 +213,7 @@ namespace System.Management.Automation.Internal // Log the cmdlet invocation execution details if we didn't have an associated script line with it. if ((invocation == null) || string.IsNullOrEmpty(invocation.Line)) { - if (hostInterface != null) - { - hostInterface.TranscribeCommand(logElement, invocation); - } + hostInterface?.TranscribeCommand(logElement, invocation); } if (_needToLog && !string.IsNullOrEmpty(logElement)) diff --git a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs index 318684253..e6f7eee43 100644 --- a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs +++ b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs @@ -5678,10 +5678,7 @@ namespace System.Management.Automation.Language restrictions = versionRestriction; // When returning aliasRestrictions always include the version restriction - if (aliasRestrictions != null) - { - aliasRestrictions.Add(versionRestriction); - } + aliasRestrictions?.Add(versionRestriction); var alias = memberInfo as PSAliasProperty; if (alias != null) diff --git a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs index fdcbaf98f..a85bc8a8e 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs @@ -426,10 +426,7 @@ namespace System.Management.Automation try { - if (context.Events != null) - { - context.Events.ProcessPendingActions(); - } + context.Events?.ProcessPendingActions(); if (input == AutomationNull.Value && !ignoreInput) { @@ -519,10 +516,7 @@ namespace System.Management.Automation try { - if (context.Events != null) - { - context.Events.ProcessPendingActions(); - } + context.Events?.ProcessPendingActions(); CommandProcessorBase commandProcessor = null; @@ -841,10 +835,7 @@ namespace System.Management.Automation internal static void CheckForInterrupts(ExecutionContext context) { - if (context.Events != null) - { - context.Events.ProcessPendingActions(); - } + context.Events?.ProcessPendingActions(); if (context.CurrentPipelineStopping) { @@ -1065,10 +1056,7 @@ namespace System.Management.Automation // 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) - { - context.CurrentCommandProcessor.CommandRuntime.OutputPipe.SetVariableListForTemporaryPipe(pipe); - } + context.CurrentCommandProcessor?.CommandRuntime.OutputPipe.SetVariableListForTemporaryPipe(pipe); commandProcessor.CommandRuntime.OutputPipe = pipe; commandProcessor.CommandRuntime.ErrorOutputPipe = pipe; @@ -1079,10 +1067,7 @@ namespace System.Management.Automation 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) - { - context.CurrentCommandProcessor.CommandRuntime.OutputPipe.SetVariableListForTemporaryPipe(pipe); - } + context.CurrentCommandProcessor?.CommandRuntime.OutputPipe.SetVariableListForTemporaryPipe(pipe); commandProcessor.CommandRuntime.OutputPipe = pipe; break; @@ -1214,11 +1199,8 @@ namespace System.Management.Automation throw; } - if (parentPipelineProcessor != null) - { - // I think this is only necessary for calling Dispose on the commands in the redirection pipe. - parentPipelineProcessor.AddRedirectionPipe(PipelineProcessor); - } + // I think this is only necessary for calling Dispose on the commands in the redirection pipe. + parentPipelineProcessor?.AddRedirectionPipe(PipelineProcessor); return new Pipe(context, PipelineProcessor); } @@ -1234,10 +1216,7 @@ namespace System.Management.Automation internal void CallDoCompleteForExpression() { // The pipe returned from 'GetRedirectionPipe' could be a NullPipe - if (PipelineProcessor != null) - { - PipelineProcessor.DoComplete(); - } + PipelineProcessor?.DoComplete(); } private bool _disposed; @@ -1255,10 +1234,7 @@ namespace System.Management.Automation if (disposing) { - if (PipelineProcessor != null) - { - PipelineProcessor.Dispose(); - } + PipelineProcessor?.Dispose(); } _disposed = true; @@ -1754,10 +1730,7 @@ namespace System.Management.Automation ErrorRecord err = rte.ErrorRecord; // CurrentCommandProcessor is normally not null, but it is null // when executing some unit tests through reflection. - if (context.CurrentCommandProcessor != null) - { - context.CurrentCommandProcessor.ForgetScriptException(); - } + context.CurrentCommandProcessor?.ForgetScriptException(); try { @@ -1951,10 +1924,7 @@ namespace System.Management.Automation if (rte is not PipelineStoppedException) { - if (outputPipe != null) - { - outputPipe.AppendVariableList(VariableStreamKind.Error, errRec); - } + outputPipe?.AppendVariableList(VariableStreamKind.Error, errRec); context.AppendDollarError(errRec); } @@ -3530,10 +3500,7 @@ namespace System.Management.Automation if (dispose) { var disposable = enumerator as IDisposable; - if (disposable != null) - { - disposable.Dispose(); - } + disposable?.Dispose(); } } }