diff --git a/.globalconfig b/.globalconfig index cdddd9f2630..34ee397fc2b 100644 --- a/.globalconfig +++ b/.globalconfig @@ -817,7 +817,7 @@ dotnet_diagnostic.IDE0029.severity = silent dotnet_diagnostic.IDE0030.severity = silent # IDE0031: UseNullPropagation -dotnet_diagnostic.IDE0031.severity = silent +dotnet_diagnostic.IDE0031.severity = warning # IDE0032: UseAutoProperty dotnet_diagnostic.IDE0032.severity = silent diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs index 198c86e96af..f64316bd6c7 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs @@ -81,7 +81,7 @@ public CimInstance NewEvent { get { - return (result == null) ? null : result.Instance; + return result?.Instance; } } @@ -92,7 +92,7 @@ public string MachineId { get { - return (result == null) ? null : result.MachineId; + return result?.MachineId; } } @@ -103,7 +103,7 @@ public string Bookmark { get { - return (result == null) ? null : result.Bookmark; + return result?.Bookmark; } } 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 092103d6fe7..624f47297a3 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs @@ -201,7 +201,7 @@ private void InitializeErrorRecordCore(CimJobContext jobContext, Exception excep exception: exception, errorId: errorId, errorCategory: errorCategory, - targetObject: jobContext != null ? jobContext.TargetObject : null); + targetObject: jobContext?.TargetObject); if (jobContext != null) { @@ -242,7 +242,7 @@ private void InitializeErrorRecord(CimJobContext jobContext, CimException cimExc if (cimException.ErrorData != null) { _errorRecord.CategoryInfo.TargetName = cimException.ErrorSource; - _errorRecord.CategoryInfo.TargetType = jobContext != null ? jobContext.CmdletizationClassName : null; + _errorRecord.CategoryInfo.TargetType = jobContext?.CmdletizationClassName; } } 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 990c31c73a5..d7c7be87a78 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ExtrinsicMethodInvocationJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ExtrinsicMethodInvocationJob.cs @@ -58,7 +58,7 @@ private void ProcessOutParameter(CimMethodResult methodResult, MethodParameter m Dbg.Assert(this.MethodSubject != null, "MethodSubject property should be initialized before starting main job processing"); CimMethodParameter outParameter = methodResult.OutParameters[methodParameter.Name]; - object valueReturnedFromMethod = (outParameter == null) ? null : outParameter.Value; + object valueReturnedFromMethod = outParameter?.Value; object dotNetValue = CimValueConverter.ConvertFromCimToDotNet(valueReturnedFromMethod, methodParameter.ParameterType); if (MethodParameterBindings.Out == (methodParameter.Bindings & MethodParameterBindings.Out)) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs index f478a18e421..3c0f4e2f0ff 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs @@ -1142,7 +1142,7 @@ internal static string GetLocaleName(string locale) } } - return culture == null ? null : culture.Name; + return culture?.Name; } /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs index daecd606b89..94dbf8aab3d 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?.ToString(); } set { 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 8e28c630e17..9eedb3ee293 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs @@ -83,7 +83,7 @@ internal static StringBuilder GetRawContentHeader(HttpResponseMessage response) HttpHeaders[] headerCollections = { response.Headers, - response.Content == null ? null : response.Content.Headers + response.Content?.Headers }; foreach (var headerCollection in headerCollections) diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData.cs index 717ea07bdcd..f126dddcadc 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData.cs @@ -774,7 +774,7 @@ internal static PSControlGroupBy Get(GroupBy groupBy) return new PSControlGroupBy { Expression = new DisplayEntry(expressionToken), - Label = (groupBy.startGroup.labelTextToken != null) ? groupBy.startGroup.labelTextToken.text : null + Label = groupBy.startGroup.labelTextToken?.text }; } diff --git a/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs b/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs index 25cd6a2e8bc..023ac60fc41 100644 --- a/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs +++ b/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs @@ -31,9 +31,7 @@ internal Type TargetType { get { - return _convertTypes == null - ? null - : _convertTypes.LastOrDefault(); + return _convertTypes?.LastOrDefault(); } } diff --git a/src/System.Management.Automation/engine/CmdletParameterBinderController.cs b/src/System.Management.Automation/engine/CmdletParameterBinderController.cs index a9afe8f004e..bc8b51ef031 100644 --- a/src/System.Management.Automation/engine/CmdletParameterBinderController.cs +++ b/src/System.Management.Automation/engine/CmdletParameterBinderController.cs @@ -4224,7 +4224,7 @@ private void RestoreDefaultParameterValues(IEnumerable /// public PSEventJob(PSEventManager eventManager, PSEventSubscriber subscriber, ScriptBlock action, string name) : - base(action == null ? null : action.ToString(), name) + base(action?.ToString(), name) { if (eventManager == null) throw new ArgumentNullException(nameof(eventManager)); diff --git a/src/System.Management.Automation/engine/ExternalScriptInfo.cs b/src/System.Management.Automation/engine/ExternalScriptInfo.cs index d87e3027f2e..ab328556ccf 100644 --- a/src/System.Management.Automation/engine/ExternalScriptInfo.cs +++ b/src/System.Management.Automation/engine/ExternalScriptInfo.cs @@ -403,7 +403,7 @@ internal string RequiresApplicationID get { var data = GetRequiresData(); - return data == null ? null : data.RequiredApplicationId; + return data?.RequiredApplicationId; } } @@ -417,7 +417,7 @@ internal Version RequiresPSVersion get { var data = GetRequiresData(); - return data == null ? null : data.RequiredPSVersion; + return data?.RequiredPSVersion; } } @@ -426,7 +426,7 @@ internal IEnumerable RequiresPSEditions get { var data = GetRequiresData(); - return data == null ? null : data.RequiredPSEditions; + return data?.RequiredPSEditions; } } @@ -435,7 +435,7 @@ internal IEnumerable RequiresModules get { var data = GetRequiresData(); - return data == null ? null : data.RequiredModules; + return data?.RequiredModules; } } @@ -458,7 +458,7 @@ internal IEnumerable RequiresPSSnapIns get { var data = GetRequiresData(); - return data == null ? null : data.RequiresPSSnapIns; + return data?.RequiresPSSnapIns; } } diff --git a/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs b/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs index d6f4d9b7fe1..69f06253b74 100644 --- a/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs +++ b/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs @@ -360,7 +360,7 @@ private static ErrorRecord GetErrorRecordForRemotePipelineInvocation(Exception i Exception outerException = new InvalidOperationException(errorMessage, innerException); RemoteException remoteException = innerException as RemoteException; - ErrorRecord remoteErrorRecord = remoteException != null ? remoteException.ErrorRecord : null; + ErrorRecord remoteErrorRecord = remoteException?.ErrorRecord; string errorId = remoteErrorRecord != null ? remoteErrorRecord.FullyQualifiedErrorId : innerException.GetType().Name; ErrorCategory errorCategory = remoteErrorRecord != null ? remoteErrorRecord.CategoryInfo.Category : ErrorCategory.NotSpecified; ErrorRecord errorRecord = new ErrorRecord(outerException, errorId, errorCategory, null); diff --git a/src/System.Management.Automation/engine/ParameterBinderBase.cs b/src/System.Management.Automation/engine/ParameterBinderBase.cs index f3572cdbeb5..5769846dd47 100644 --- a/src/System.Management.Automation/engine/ParameterBinderBase.cs +++ b/src/System.Management.Automation/engine/ParameterBinderBase.cs @@ -439,7 +439,7 @@ internal virtual bool BindParameter( GetErrorExtent(parameter), parameterMetadata.Name, parameterMetadata.Type, - (parameterValue == null) ? null : parameterValue.GetType(), + parameterValue?.GetType(), ParameterBinderStrings.ParameterArgumentTransformationError, "ParameterArgumentTransformationError", e.Message); @@ -522,7 +522,7 @@ internal virtual bool BindParameter( GetErrorExtent(parameter), parameterMetadata.Name, parameterMetadata.Type, - (parameterValue == null) ? null : parameterValue.GetType(), + parameterValue?.GetType(), ParameterBinderStrings.ParameterArgumentValidationError, "ParameterArgumentValidationError", e.Message); @@ -586,7 +586,7 @@ internal virtual bool BindParameter( if (bindError != null) { - Type specifiedType = (parameterValue == null) ? null : parameterValue.GetType(); + Type specifiedType = parameterValue?.GetType(); ParameterBindingException bindingException = new ParameterBindingException( bindError, @@ -736,7 +736,7 @@ private void ValidateNullOrEmptyArgument( GetErrorExtent(parameter), parameterMetadata.Name, parameterMetadata.Type, - (parameterValue == null) ? null : parameterValue.GetType(), + parameterValue?.GetType(), ParameterBinderStrings.ParameterArgumentValidationErrorEmptyStringNotAllowed, "ParameterArgumentValidationErrorEmptyStringNotAllowed"); throw bindingException; @@ -813,7 +813,7 @@ private void ValidateNullOrEmptyArgument( GetErrorExtent(parameter), parameterMetadata.Name, parameterMetadata.Type, - (parameterValue == null) ? null : parameterValue.GetType(), + parameterValue?.GetType(), resourceString, errorId); throw bindingException; @@ -1781,7 +1781,7 @@ private object EncodeCollection( GetErrorExtent(argument), parameterName, toType, - (currentValueElement == null) ? null : currentValueElement.GetType(), + currentValueElement?.GetType(), ParameterBinderStrings.CannotConvertArgument, "CannotConvertArgument", currentValueElement ?? "null", @@ -1878,7 +1878,7 @@ private object EncodeCollection( GetErrorExtent(argument), parameterName, toType, - (currentValue == null) ? null : currentValue.GetType(), + currentValue?.GetType(), ParameterBinderStrings.CannotConvertArgument, "CannotConvertArgument", currentValue ?? "null", diff --git a/src/System.Management.Automation/engine/PseudoParameterBinder.cs b/src/System.Management.Automation/engine/PseudoParameterBinder.cs index bddbe643f59..9bebe01b2e7 100644 --- a/src/System.Management.Automation/engine/PseudoParameterBinder.cs +++ b/src/System.Management.Automation/engine/PseudoParameterBinder.cs @@ -36,7 +36,7 @@ internal RuntimeDefinedParameterBinder( { string key = pair.Key; RuntimeDefinedParameter pp = pair.Value; - string ppName = (pp == null) ? null : pp.Name; + string ppName = pp?.Name; if (pp == null || key != ppName) { ParameterBindingException bindingException = diff --git a/src/System.Management.Automation/engine/SessionStateScope.cs b/src/System.Management.Automation/engine/SessionStateScope.cs index 19e08a5119c..92ac34dde6b 100644 --- a/src/System.Management.Automation/engine/SessionStateScope.cs +++ b/src/System.Management.Automation/engine/SessionStateScope.cs @@ -489,7 +489,7 @@ internal PSVariable SetVariable(string name, object value, bool asValue, bool fo } else { - variable = (LocalsTuple != null ? LocalsTuple.TrySetVariable(name, value) : null) ?? new PSVariable(name, value); + variable = (LocalsTuple?.TrySetVariable(name, value)) ?? new PSVariable(name, value); } if (ExecutionContext.HasEverUsedConstrainedLanguage) diff --git a/src/System.Management.Automation/engine/debugger/debugger.cs b/src/System.Management.Automation/engine/debugger/debugger.cs index 95567feb2f4..fd0eb2912b1 100644 --- a/src/System.Management.Automation/engine/debugger/debugger.cs +++ b/src/System.Management.Automation/engine/debugger/debugger.cs @@ -1447,7 +1447,7 @@ private List GetVariableBreakpointsToTrigger(string variable return null; var callStackInfo = _callStack.Last(); - var currentScriptFile = (callStackInfo != null) ? callStackInfo.File : null; + var currentScriptFile = callStackInfo?.File; return breakpoints.Values.Where(bp => bp.Trigger(currentScriptFile, read: read)).ToList(); } finally @@ -1633,7 +1633,7 @@ internal CallStackInfo Last() internal FunctionContext LastFunctionContext() { var last = Last(); - return last != null ? last.FunctionContext : null; + return last?.FunctionContext; } internal bool Any() @@ -3678,7 +3678,7 @@ private void RemoveFromRunningRunspaceList(Runspace runspace) } // Clean up nested debugger. - NestedRunspaceDebugger nestedDebugger = (runspaceInfo != null) ? runspaceInfo.NestedDebugger : null; + NestedRunspaceDebugger nestedDebugger = runspaceInfo?.NestedDebugger; if (nestedDebugger != null) { nestedDebugger.DebuggerStop -= HandleMonitorRunningRSDebuggerStop; @@ -4449,7 +4449,7 @@ protected virtual DebuggerCommandResults HandlePromptCommand(PSDataCollection]: [RunspaceName]: PS C:\> - string computerName = (_runspace.ConnectionInfo != null) ? _runspace.ConnectionInfo.ComputerName : null; + string computerName = _runspace.ConnectionInfo?.ComputerName; string processPartPattern = "{0}[{1}:{2}]:{3}"; string processPart = StringUtil.Format(processPartPattern, @"""", diff --git a/src/System.Management.Automation/engine/hostifaces/Connection.cs b/src/System.Management.Automation/engine/hostifaces/Connection.cs index 29e86c91b9b..4f71cc93c21 100644 --- a/src/System.Management.Automation/engine/hostifaces/Connection.cs +++ b/src/System.Management.Automation/engine/hostifaces/Connection.cs @@ -952,7 +952,7 @@ internal void UpdateRunspaceAvailability(PipelineState pipelineState, bool raise { RemoteRunspace remoteRunspace = this as RemoteRunspace; RemoteDebugger remoteDebugger = (remoteRunspace != null) ? remoteRunspace.Debugger as RemoteDebugger : null; - Internal.ConnectCommandInfo remoteCommand = (remoteRunspace != null) ? remoteRunspace.RemoteCommand : null; + Internal.ConnectCommandInfo remoteCommand = remoteRunspace?.RemoteCommand; if (((pipelineState == PipelineState.Completed) || (pipelineState == PipelineState.Failed) || ((pipelineState == PipelineState.Stopped) && (this.RunspaceStateInfo.State == RunspaceState.Opened))) && (remoteCommand != null) && (cmdInstanceId != null) && (remoteCommand.CommandId == cmdInstanceId)) @@ -1590,7 +1590,7 @@ public virtual Debugger Debugger get { var context = GetExecutionContext; - return (context != null) ? context.Debugger : null; + return context?.Debugger; } } diff --git a/src/System.Management.Automation/engine/hostifaces/History.cs b/src/System.Management.Automation/engine/hostifaces/History.cs index 9fe392413f9..1f980b86f7a 100644 --- a/src/System.Management.Automation/engine/hostifaces/History.cs +++ b/src/System.Management.Automation/engine/hostifaces/History.cs @@ -759,7 +759,7 @@ private int GetHistorySize() { int historySize = 0; var executionContext = LocalPipeline.GetExecutionContextFromTLS(); - object obj = (executionContext != null) ? executionContext.GetVariableValue(SpecialVariables.HistorySizeVarPath) : null; + object obj = executionContext?.GetVariableValue(SpecialVariables.HistorySizeVarPath); if (obj != null) { try diff --git a/src/System.Management.Automation/engine/interpreter/InstructionList.cs b/src/System.Management.Automation/engine/interpreter/InstructionList.cs index 79aca5b48ba..818dfd4bf62 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?.ToArray(), BuildRuntimeLabels(), _debugCookies ); diff --git a/src/System.Management.Automation/engine/interpreter/LightCompiler.cs b/src/System.Management.Automation/engine/interpreter/LightCompiler.cs index 4f130751fd4..895f4b87a4a 100644 --- a/src/System.Management.Automation/engine/interpreter/LightCompiler.cs +++ b/src/System.Management.Automation/engine/interpreter/LightCompiler.cs @@ -1532,7 +1532,7 @@ private void CompileTryExpression(Expression expr) enterTryInstr.SetTryHandler( new TryCatchFinallyHandler(tryStart, tryEnd, gotoEnd.TargetIndex, startOfFinally.TargetIndex, _instructions.Count, - exHandlers != null ? exHandlers.ToArray() : null)); + exHandlers?.ToArray())); PopLabelBlock(LabelScopeKind.Finally); } else diff --git a/src/System.Management.Automation/engine/lang/parserutils.cs b/src/System.Management.Automation/engine/lang/parserutils.cs index 5b73e3914ec..746d47e92cf 100644 --- a/src/System.Management.Automation/engine/lang/parserutils.cs +++ b/src/System.Management.Automation/engine/lang/parserutils.cs @@ -378,8 +378,8 @@ internal static object ImplicitOp(object lval, object rval, string op, IScriptEx lval = PSObject.Base(lval); rval = PSObject.Base(rval); - Type lvalType = lval != null ? lval.GetType() : null; - Type rvalType = rval != null ? rval.GetType() : null; + Type lvalType = lval?.GetType(); + Type rvalType = rval?.GetType(); Type opType; if (lvalType == null || (lvalType.IsPrimitive)) { diff --git a/src/System.Management.Automation/engine/lang/scriptblock.cs b/src/System.Management.Automation/engine/lang/scriptblock.cs index 6bf326ae81c..33e1e13205f 100644 --- a/src/System.Management.Automation/engine/lang/scriptblock.cs +++ b/src/System.Management.Automation/engine/lang/scriptblock.cs @@ -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?.Module; } /// /// Return the PSToken object for this function definition... @@ -709,7 +709,7 @@ internal SessionState SessionState } } - return SessionStateInternal != null ? SessionStateInternal.PublicSessionState : null; + return SessionStateInternal?.PublicSessionState; } set @@ -1138,7 +1138,7 @@ public void Begin(bool expectInput, EngineIntrinsics contextToRedirectTo) ExecutionContext executionContext = contextToRedirectTo.SessionState.Internal.ExecutionContext; CommandProcessorBase commandProcessor = executionContext.CurrentCommandProcessor; - ICommandRuntime crt = commandProcessor == null ? null : commandProcessor.CommandRuntime; + ICommandRuntime crt = commandProcessor?.CommandRuntime; Begin(expectInput, crt); } diff --git a/src/System.Management.Automation/engine/parser/Compiler.cs b/src/System.Management.Automation/engine/parser/Compiler.cs index 8bfada27aa5..30c7aa24ce6 100644 --- a/src/System.Management.Automation/engine/parser/Compiler.cs +++ b/src/System.Management.Automation/engine/parser/Compiler.cs @@ -1166,7 +1166,7 @@ internal static Type GetTypeConstraintForMethodResolution(ExpressionAst expr) expr = ((AttributedExpressionAst)expr).Child; } - return firstConvert == null ? null : firstConvert.Type.TypeName.GetReflectionType(); + return firstConvert?.Type.TypeName.GetReflectionType(); } internal static PSMethodInvocationConstraints CombineTypeConstraintForMethodResolution(Type targetType, Type argType) @@ -6313,7 +6313,7 @@ internal static PSMethodInvocationConstraints GetInvokeMemberConstraints(InvokeM var targetTypeConstraint = GetTypeConstraintForMethodResolution(invokeMemberExpressionAst.Expression); return CombineTypeConstraintForMethodResolution( targetTypeConstraint, - arguments != null ? arguments.Select(Compiler.GetTypeConstraintForMethodResolution).ToArray() : null); + arguments?.Select(Compiler.GetTypeConstraintForMethodResolution).ToArray()); } internal static PSMethodInvocationConstraints GetInvokeMemberConstraints(BaseCtorInvokeMemberExpressionAst invokeMemberExpressionAst) @@ -6332,7 +6332,7 @@ internal static PSMethodInvocationConstraints GetInvokeMemberConstraints(BaseCto return CombineTypeConstraintForMethodResolution( targetTypeConstraint, - arguments != null ? arguments.Select(Compiler.GetTypeConstraintForMethodResolution).ToArray() : null); + arguments?.Select(Compiler.GetTypeConstraintForMethodResolution).ToArray()); } internal Expression InvokeMember( @@ -6345,7 +6345,7 @@ internal Expression InvokeMember( bool nullConditional = false) { var callInfo = new CallInfo(args.Count()); - var classScope = _memberFunctionType != null ? _memberFunctionType.Type : null; + var classScope = _memberFunctionType?.Type; var binder = name.Equals("new", StringComparison.OrdinalIgnoreCase) && @static ? (CallSiteBinder)PSCreateInstanceBinder.Get(callInfo, constraints, publicTypeOnly: true) : PSInvokeMemberBinder.Get(name, callInfo, @static, propertySet, constraints, classScope); diff --git a/src/System.Management.Automation/engine/parser/Parser.cs b/src/System.Management.Automation/engine/parser/Parser.cs index 33ab679e803..99c1a92fa82 100644 --- a/src/System.Management.Automation/engine/parser/Parser.cs +++ b/src/System.Management.Automation/engine/parser/Parser.cs @@ -1668,7 +1668,7 @@ private ScriptBlockAst ScriptBlockBodyRule(Token lCurly, List statements.Add(predefinedStatementAst); } - IScriptExtent statementListExtent = paramBlockAst != null ? paramBlockAst.Extent : null; + IScriptExtent statementListExtent = paramBlockAst?.Extent; IScriptExtent scriptBlockExtent; while (true) @@ -1709,7 +1709,7 @@ private ScriptBlockAst NamedBlockListRule(Token lCurly, List NamedBlockAst endBlock = null; IScriptExtent startExtent = lCurly != null ? lCurly.Extent - : (paramBlockAst != null) ? paramBlockAst.Extent : null; + : paramBlockAst?.Extent; IScriptExtent endExtent = null; IScriptExtent extent = null; IScriptExtent scriptBlockExtent = null; @@ -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?.OfType(), token); break; case TokenKind.From: case TokenKind.Define: @@ -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?.LabelText, condition, flags, clauses, @default); } private StatementAst ConfigurationStatementRule(IEnumerable customAttributes, Token configurationToken) @@ -3441,7 +3441,7 @@ private StatementAst ForeachStatementRule(LabelToken labelToken, Token forEachTo } return new ForEachStatementAst(ExtentOf(startOfStatement, body), - labelToken != null ? labelToken.LabelText : null, + labelToken?.LabelText, flags, throttleLimit, variableAst, pipeline, body); } @@ -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?.LabelText, 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?.LabelText, condition, body); } /// @@ -4131,7 +4131,7 @@ private StatementAst DoWhileStatementRule(LabelToken labelToken, Token doToken) } IScriptExtent extent = ExtentOf(startExtent, rParen); - string label = (labelToken != null) ? labelToken.LabelText : null; + string label = labelToken?.LabelText; if (whileOrUntilToken.Kind == TokenKind.Until) { return new DoUntilStatementAst(extent, label, condition, body); @@ -4285,7 +4285,7 @@ private StatementAst ClassDefinitionRule(List customAttributes ? customAttributes[0].Extent : classToken.Extent; var extent = ExtentOf(startExtent, lastExtent); - var classDefn = new TypeDefinitionAst(extent, name.Value, customAttributes == null ? null : customAttributes.OfType(), members, TypeAttributes.Class, superClassesList); + var classDefn = new TypeDefinitionAst(extent, name.Value, customAttributes?.OfType(), members, TypeAttributes.Class, superClassesList); if (customAttributes != null && customAttributes.OfType().Any()) { if (nestedAsts == null) @@ -4746,7 +4746,7 @@ private StatementAst EnumDefinitionRule(List customAttributes, ? customAttributes[0].Extent : enumToken.Extent; var extent = ExtentOf(startExtent, rCurly); - var enumDefn = new TypeDefinitionAst(extent, name.Value, customAttributes == null ? null : customAttributes.OfType(), members, TypeAttributes.Enum, underlyingTypeConstraint == null ? null : new[] { underlyingTypeConstraint }); + var enumDefn = new TypeDefinitionAst(extent, name.Value, customAttributes?.OfType(), members, TypeAttributes.Enum, underlyingTypeConstraint == null ? null : new[] { underlyingTypeConstraint }); if (customAttributes != null && customAttributes.OfType().Any()) { // No need to report error since there is error reported in method StatementRule @@ -5625,7 +5625,7 @@ private StatementAst DataStatementRule(Token dataToken) IScriptExtent endErrorStatement = null; SkipNewlines(); var dataVariableNameAst = SimpleNameRule(); - string dataVariableName = (dataVariableNameAst != null) ? dataVariableNameAst.Value : null; + string dataVariableName = dataVariableNameAst?.Value; SkipNewlines(); Token supportedCommandToken = PeekToken(); @@ -6631,7 +6631,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?.Where(r => r != null)); } #endregion Pipelines diff --git a/src/System.Management.Automation/engine/parser/SemanticChecks.cs b/src/System.Management.Automation/engine/parser/SemanticChecks.cs index a56e849811c..38386303913 100644 --- a/src/System.Management.Automation/engine/parser/SemanticChecks.cs +++ b/src/System.Management.Automation/engine/parser/SemanticChecks.cs @@ -670,7 +670,7 @@ private static string GetLabel(ExpressionAst expr) } var str = expr as StringConstantExpressionAst; - return str != null ? str.Value : null; + return str?.Value; } public override AstVisitAction VisitBreakStatement(BreakStatementAst breakStatementAst) diff --git a/src/System.Management.Automation/engine/parser/TypeResolver.cs b/src/System.Management.Automation/engine/parser/TypeResolver.cs index fa054554b2a..966872dba3e 100644 --- a/src/System.Management.Automation/engine/parser/TypeResolver.cs +++ b/src/System.Management.Automation/engine/parser/TypeResolver.cs @@ -246,7 +246,7 @@ private static Type CallResolveTypeNameWorkerHelper(TypeName typeName, try { exception = null; - var currentScope = context != null ? context.EngineSessionState.CurrentScope : null; + var currentScope = context?.EngineSessionState.CurrentScope; Type result = ResolveTypeNameWorker(typeName, currentScope, typeResolutionState.assemblies, t_searchedAssemblies, typeResolutionState, /*onlySearchInGivenAssemblies*/ false, /* reportAmbiguousException */ true, out exception); if (exception == null && result == null) diff --git a/src/System.Management.Automation/engine/parser/ast.cs b/src/System.Management.Automation/engine/parser/ast.cs index a15cf6e6a90..6ad5c2c4fc7 100644 --- a/src/System.Management.Automation/engine/parser/ast.cs +++ b/src/System.Management.Automation/engine/parser/ast.cs @@ -2656,7 +2656,7 @@ public override Ast Copy() internal override object Accept(ICustomAstVisitor visitor) { var visitor2 = visitor as ICustomAstVisitor2; - return visitor2 != null ? visitor2.VisitTypeDefinition(this) : null; + return visitor2?.VisitTypeDefinition(this); } internal override AstVisitAction InternalVisit(AstVisitor visitor) @@ -2904,7 +2904,7 @@ public override Ast Copy() internal override object Accept(ICustomAstVisitor visitor) { var visitor2 = visitor as ICustomAstVisitor2; - return visitor2 != null ? visitor2.VisitUsingStatement(this) : null; + return visitor2?.VisitUsingStatement(this); } internal override AstVisitAction InternalVisit(AstVisitor visitor) @@ -3132,7 +3132,7 @@ internal override string GetTooltip() internal override object Accept(ICustomAstVisitor visitor) { var visitor2 = visitor as ICustomAstVisitor2; - return visitor2 != null ? visitor2.VisitPropertyMember(this) : null; + return visitor2?.VisitPropertyMember(this); } internal override AstVisitAction InternalVisit(AstVisitor visitor) @@ -3352,7 +3352,7 @@ internal override string GetTooltip() internal override object Accept(ICustomAstVisitor visitor) { var visitor2 = visitor as ICustomAstVisitor2; - return visitor2 != null ? visitor2.VisitFunctionMember(this) : null; + return visitor2?.VisitFunctionMember(this); } internal override AstVisitAction InternalVisit(AstVisitor visitor) @@ -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?.Parameters); } } PowerShell IParameterMetadataProvider.GetPowerShell(ExecutionContext context, Dictionary variables, bool isTrustedInput, @@ -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?.Value; } /// @@ -6422,7 +6422,7 @@ public override Ast Copy() { LCurlyToken = this.LCurlyToken, ConfigurationToken = this.ConfigurationToken, - CustomAttributes = this.CustomAttributes == null ? null : this.CustomAttributes.Select(e => (AttributeAst)e.Copy()) + CustomAttributes = this.CustomAttributes?.Select(e => (AttributeAst)e.Copy()) }; } @@ -6431,7 +6431,7 @@ public override Ast Copy() internal override object Accept(ICustomAstVisitor visitor) { var visitor2 = visitor as ICustomAstVisitor2; - return visitor2 != null ? visitor2.VisitConfigurationDefinition(this) : null; + return visitor2?.VisitConfigurationDefinition(this); } internal override AstVisitAction InternalVisit(AstVisitor visitor) @@ -6521,7 +6521,7 @@ internal PipelineAst GenerateSetItemPipelineAst() cea.Add(new CommandParameterAst(PositionUtilities.EmptyExtent, "ResourceModuleTuplesToImport", new ConstantExpressionAst(PositionUtilities.EmptyExtent, resourceModulePairsToImport), PositionUtilities.EmptyExtent)); var scriptBlockBody = new ScriptBlockAst(Body.Extent, - CustomAttributes == null ? null : CustomAttributes.Select(att => (AttributeAst)att.Copy()).ToList(), + CustomAttributes?.Select(att => (AttributeAst)att.Copy()).ToList(), null, new StatementBlockAst(Body.Extent, resourceBody, null), false, false); @@ -6580,7 +6580,7 @@ internal PipelineAst GenerateSetItemPipelineAst() var statmentBlockAst = new StatementBlockAst(this.Extent, funcStatements, null); var funcBody = new ScriptBlockAst(Body.Extent, - CustomAttributes == null ? null : CustomAttributes.Select(att => (AttributeAst)att.Copy()).ToList(), + CustomAttributes?.Select(att => (AttributeAst)att.Copy()).ToList(), paramBlockAst, statmentBlockAst, false, true); var funcBodyExp = new ScriptBlockExpressionAst(this.Extent, funcBody); @@ -6898,7 +6898,7 @@ public override Ast Copy() internal override object Accept(ICustomAstVisitor visitor) { var visitor2 = visitor as ICustomAstVisitor2; - return visitor2 != null ? visitor2.VisitDynamicKeywordStatement(this) : null; + return visitor2?.VisitDynamicKeywordStatement(this); } internal override AstVisitAction InternalVisit(AstVisitor visitor) @@ -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?.VisitBaseCtorInvokeMemberExpression(this); } } diff --git a/src/System.Management.Automation/engine/remoting/client/ClientRemotePowerShell.cs b/src/System.Management.Automation/engine/remoting/client/ClientRemotePowerShell.cs index 4f966f5bdba..4c6dce2c7aa 100644 --- a/src/System.Management.Automation/engine/remoting/client/ClientRemotePowerShell.cs +++ b/src/System.Management.Automation/engine/remoting/client/ClientRemotePowerShell.cs @@ -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?.SessionStateInfo.Reason; PSInvocationState finishedState = (shell.InvocationStateInfo.State == PSInvocationState.Disconnected) ? PSInvocationState.Failed : PSInvocationState.Stopped; diff --git a/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs b/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs index 11ce70dd186..cba829acfc1 100644 --- a/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs +++ b/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs @@ -1412,7 +1412,7 @@ 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?.Reason); Dbg.Assert(InvocationStateInfoReceived != null, "ClientRemotePowerShell should subscribe to all data structure handler events"); diff --git a/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs b/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs index cbedc14c2a6..f64370e6634 100644 --- a/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs +++ b/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs @@ -1939,7 +1939,7 @@ public override DebuggerCommandResults ProcessCommand(PSCommand command, PSDataC if (re.ErrorRecord.CategoryInfo.Reason == typeof(IncompleteParseException).Name) { throw new IncompleteParseException( - (re.ErrorRecord.Exception != null) ? re.ErrorRecord.Exception.Message : null, + re.ErrorRecord.Exception?.Message, re.ErrorRecord.FullyQualifiedErrorId); } @@ -2660,7 +2660,7 @@ 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?.EndInvokeAsyncResult; bool invokedOnBlockedThread = false; if ((invokeAsyncResult != null) && (!invokeAsyncResult.IsCompleted)) diff --git a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs index 1254c5ca420..b6b7c7d7af0 100644 --- a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs +++ b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs @@ -589,8 +589,8 @@ protected override void ProcessRecord() restartServiceTarget, restartServiceAction, restartWSManRequiredForUI, - runAsCredential != null ? runAsCredential.UserName : null, - runAsCredential != null ? runAsCredential.Password : null, + runAsCredential?.UserName, + runAsCredential?.Password, AccessMode, isSddlSpecified, _configTableSDDL, diff --git a/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs b/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs index 85079617952..5e8d7b8a241 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs @@ -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?.UserInfo.Identity.Name; // Set user drive max drive if provided. if (_configHash.ContainsKey(ConfigFileConstants.UserDriveMaxSize)) diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs index 921f9f456f1..01c16b42e82 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs @@ -335,7 +335,7 @@ 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; + PSEventManager localEventManager = Runspace?.Events; _hostSupportsPSEdit = (localEventManager != null) ? localEventManager.GetEventSubscribers(HostUtilities.RemoteSessionOpenFileEvent).GetEnumerator().MoveNext() : false; if (_hostSupportsPSEdit) { diff --git a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs index 9ea707c67db..9f502849b63 100644 --- a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs +++ b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs @@ -1202,7 +1202,7 @@ internal static PSInvokeDynamicMemberBinder Get(CallInfo callInfo, TypeDefinitio { PSInvokeDynamicMemberBinder result; - var classScope = classScopeAst != null ? classScopeAst.Type : null; + var classScope = classScopeAst?.Type; lock (s_binderCache) { var key = Tuple.Create(callInfo, constraints, propertySetter, @static, classScope); @@ -1296,7 +1296,7 @@ internal static PSGetDynamicMemberBinder Get(TypeDefinitionAst classScope, bool PSGetDynamicMemberBinder binder; lock (s_binderCache) { - var type = classScope != null ? classScope.Type : null; + var type = classScope?.Type; var tuple = Tuple.Create(type, @static); if (!s_binderCache.TryGetValue(tuple, out binder)) { @@ -1406,7 +1406,7 @@ internal static PSSetDynamicMemberBinder Get(TypeDefinitionAst classScope, bool PSSetDynamicMemberBinder binder; lock (s_binderCache) { - var type = classScope != null ? classScope.Type : null; + var type = classScope?.Type; var tuple = Tuple.Create(type, @static); if (!s_binderCache.TryGetValue(tuple, out binder)) { @@ -5071,7 +5071,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?.Type, @static, false); } public static PSGetMemberBinder Get(string memberName, Type classScope, bool @static) @@ -5629,7 +5629,7 @@ 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?.TypeTable; if (hasTypeTableMember) { @@ -5842,7 +5842,7 @@ internal static object GetAdaptedValue(object obj, string member) } } - var adapterSet = PSObject.GetMappedAdapter(obj, context != null ? context.TypeTable : null); + var adapterSet = PSObject.GetMappedAdapter(obj, context?.TypeTable); if (memberInfo == null) { memberInfo = adapterSet.OriginalAdapter.BaseGetMember(obj, member); @@ -5881,7 +5881,7 @@ internal static bool IsTypeNameSame(object value, string typeName) internal static TypeTable GetTypeTableFromTLS() { var executionContext = LocalPipeline.GetExecutionContextFromTLS(); - return executionContext != null ? executionContext.TypeTable : null; + return executionContext?.TypeTable; } internal static bool TryGetInstanceMember(object value, string memberName, out PSMemberInfo memberInfo) @@ -5964,7 +5964,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?.Type; return Get(memberName, classScope, @static); } @@ -6446,7 +6446,7 @@ internal static object SetAdaptedValue(object obj, string member, object value) } } - var adapterSet = PSObject.GetMappedAdapter(obj, context != null ? context.TypeTable : null); + var adapterSet = PSObject.GetMappedAdapter(obj, context?.TypeTable); if (memberInfo == null) { memberInfo = adapterSet.OriginalAdapter.BaseGetMember(obj, member); @@ -7401,7 +7401,7 @@ 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?.TypeTable); var methodInfo = adapterSet.OriginalAdapter.BaseGetMember(obj, methodName) as PSMethodInfo; if (methodInfo == null && adapterSet.DotNetAdapter != null) { @@ -7446,7 +7446,7 @@ 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?.TypeTable); var methodInfo = adapterSet.OriginalAdapter.BaseGetMember(obj, methodName); if (methodInfo == null && adapterSet.DotNetAdapter != null) { diff --git a/src/System.Management.Automation/engine/runtime/Operations/ClassOps.cs b/src/System.Management.Automation/engine/runtime/Operations/ClassOps.cs index 7b06697afa1..5afe23a6362 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/ClassOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/ClassOps.cs @@ -284,7 +284,7 @@ public static void ValidateSetProperty(Type type, string propertyName, object va { var validateAttributes = type.GetProperty(propertyName).GetCustomAttributes(); var executionContext = LocalPipeline.GetExecutionContextFromTLS(); - var engineIntrinsics = executionContext == null ? null : executionContext.EngineIntrinsics; + var engineIntrinsics = executionContext?.EngineIntrinsics; foreach (var validateAttribute in validateAttributes) { validateAttribute.InternalValidate(value, engineIntrinsics); diff --git a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs index 82b53b0f290..52899f5d93a 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs @@ -449,7 +449,7 @@ internal static void InvokePipeline(object input, for (int i = 0; i < pipeElements.Length; i++) { - commandRedirection = commandRedirections != null ? commandRedirections[i] : null; + commandRedirection = commandRedirections?[i]; commandProcessor = AddCommand(pipelineProcessor, pipeElements[i], pipeElementAsts[i], commandRedirection, context); } diff --git a/src/System.Management.Automation/engine/serialization.cs b/src/System.Management.Automation/engine/serialization.cs index c569c2764c4..fa299365706 100644 --- a/src/System.Management.Automation/engine/serialization.cs +++ b/src/System.Management.Automation/engine/serialization.cs @@ -4659,7 +4659,7 @@ internal static object DeserializeProgressRecord(InternalDeserializer deserializ activityId = int.Parse(deserializer.ReadDecodedElementString(SerializationStrings.ProgressRecordActivityId), CultureInfo.InvariantCulture); object tmp = deserializer.ReadOneObject(); - currentOperation = (tmp == null) ? null : tmp.ToString(); + currentOperation = tmp?.ToString(); parentActivityId = int.Parse(deserializer.ReadDecodedElementString(SerializationStrings.ProgressRecordParentActivityId), CultureInfo.InvariantCulture); percentComplete = int.Parse(deserializer.ReadDecodedElementString(SerializationStrings.ProgressRecordPercentComplete), CultureInfo.InvariantCulture); diff --git a/src/System.Management.Automation/help/UpdateHelpCommand.cs b/src/System.Management.Automation/help/UpdateHelpCommand.cs index bccd7418476..9580027e989 100644 --- a/src/System.Management.Automation/help/UpdateHelpCommand.cs +++ b/src/System.Management.Automation/help/UpdateHelpCommand.cs @@ -348,7 +348,7 @@ internal override bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, foreach (UpdatableHelpUri contentUri in newHelpInfo.HelpContentUriCollection) { - Version currentHelpVersion = (currentHelpInfo != null) ? currentHelpInfo.GetCultureVersion(contentUri.Culture) : null; + Version currentHelpVersion = currentHelpInfo?.GetCultureVersion(contentUri.Culture); string updateHelpShouldProcessAction = string.Format(CultureInfo.InvariantCulture, HelpDisplayStrings.UpdateHelpShouldProcessActionMessage, module.ModuleName, diff --git a/src/System.Management.Automation/utils/ExecutionExceptions.cs b/src/System.Management.Automation/utils/ExecutionExceptions.cs index eb392f7536a..450797a7534 100644 --- a/src/System.Management.Automation/utils/ExecutionExceptions.cs +++ b/src/System.Management.Automation/utils/ExecutionExceptions.cs @@ -285,9 +285,7 @@ public ProviderInfo ProviderInfo { get { - return (_providerInvocationException == null) - ? null - : _providerInvocationException.ProviderInfo; + return _providerInvocationException?.ProviderInfo; } } @@ -296,7 +294,7 @@ public ProviderInfo ProviderInfo #region Internal private static Exception GetInnerException(Exception e) { - return (e == null) ? null : e.InnerException; + return e?.InnerException; } #endregion Internal }