Enable IDE0031: Null check can be simplified (#13548)

https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0031
This commit is contained in:
xtqqczze 2020-11-20 06:42:51 +00:00 committed by GitHub
parent b5902a6e9f
commit 9e285298c0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
43 changed files with 104 additions and 108 deletions

View File

@ -819,7 +819,7 @@ dotnet_diagnostic.IDE0029.severity = silent
dotnet_diagnostic.IDE0030.severity = silent dotnet_diagnostic.IDE0030.severity = silent
# IDE0031: UseNullPropagation # IDE0031: UseNullPropagation
dotnet_diagnostic.IDE0031.severity = silent dotnet_diagnostic.IDE0031.severity = warning
# IDE0032: UseAutoProperty # IDE0032: UseAutoProperty
dotnet_diagnostic.IDE0032.severity = silent dotnet_diagnostic.IDE0032.severity = silent

View File

@ -81,7 +81,7 @@ namespace Microsoft.Management.Infrastructure.CimCmdlets
{ {
get get
{ {
return (result == null) ? null : result.Instance; return result?.Instance;
} }
} }
@ -92,7 +92,7 @@ namespace Microsoft.Management.Infrastructure.CimCmdlets
{ {
get get
{ {
return (result == null) ? null : result.MachineId; return result?.MachineId;
} }
} }
@ -103,7 +103,7 @@ namespace Microsoft.Management.Infrastructure.CimCmdlets
{ {
get get
{ {
return (result == null) ? null : result.Bookmark; return result?.Bookmark;
} }
} }

View File

@ -201,7 +201,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim
exception: exception, exception: exception,
errorId: errorId, errorId: errorId,
errorCategory: errorCategory, errorCategory: errorCategory,
targetObject: jobContext != null ? jobContext.TargetObject : null); targetObject: jobContext?.TargetObject);
if (jobContext != null) if (jobContext != null)
{ {
@ -242,7 +242,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim
if (cimException.ErrorData != null) if (cimException.ErrorData != null)
{ {
_errorRecord.CategoryInfo.TargetName = cimException.ErrorSource; _errorRecord.CategoryInfo.TargetName = cimException.ErrorSource;
_errorRecord.CategoryInfo.TargetType = jobContext != null ? jobContext.CmdletizationClassName : null; _errorRecord.CategoryInfo.TargetType = jobContext?.CmdletizationClassName;
} }
} }

View File

@ -58,7 +58,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim
Dbg.Assert(this.MethodSubject != null, "MethodSubject property should be initialized before starting main job processing"); Dbg.Assert(this.MethodSubject != null, "MethodSubject property should be initialized before starting main job processing");
CimMethodParameter outParameter = methodResult.OutParameters[methodParameter.Name]; CimMethodParameter outParameter = methodResult.OutParameters[methodParameter.Name];
object valueReturnedFromMethod = (outParameter == null) ? null : outParameter.Value; object valueReturnedFromMethod = outParameter?.Value;
object dotNetValue = CimValueConverter.ConvertFromCimToDotNet(valueReturnedFromMethod, methodParameter.ParameterType); object dotNetValue = CimValueConverter.ConvertFromCimToDotNet(valueReturnedFromMethod, methodParameter.ParameterType);
if (MethodParameterBindings.Out == (methodParameter.Bindings & MethodParameterBindings.Out)) if (MethodParameterBindings.Out == (methodParameter.Bindings & MethodParameterBindings.Out))

View File

@ -1142,7 +1142,7 @@ namespace Microsoft.PowerShell.Commands
} }
} }
return culture == null ? null : culture.Name; return culture?.Name;
} }
/// <summary> /// <summary>

View File

@ -57,7 +57,7 @@ namespace Microsoft.PowerShell.Commands
[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")] [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 public string Culture
{ {
get { return _cultureInfo != null ? _cultureInfo.ToString() : null; } get { return _cultureInfo?.ToString(); }
set set
{ {

View File

@ -82,7 +82,7 @@ namespace Microsoft.PowerShell.Commands
HttpHeaders[] headerCollections = HttpHeaders[] headerCollections =
{ {
response.Headers, response.Headers,
response.Content == null ? null : response.Content.Headers response.Content?.Headers
}; };
foreach (var headerCollection in headerCollections) foreach (var headerCollection in headerCollections)

View File

@ -774,7 +774,7 @@ namespace System.Management.Automation
return new PSControlGroupBy return new PSControlGroupBy
{ {
Expression = new DisplayEntry(expressionToken), Expression = new DisplayEntry(expressionToken),
Label = (groupBy.startGroup.labelTextToken != null) ? groupBy.startGroup.labelTextToken.text : null Label = groupBy.startGroup.labelTextToken?.text
}; };
} }

View File

@ -31,9 +31,7 @@ namespace System.Management.Automation
{ {
get get
{ {
return _convertTypes == null return _convertTypes?.LastOrDefault();
? null
: _convertTypes.LastOrDefault();
} }
} }

View File

@ -4223,7 +4223,7 @@ namespace System.Management.Automation
if (error != null) if (error != null)
{ {
Type specifiedType = (argumentToBind.ArgumentValue == null) ? null : argumentToBind.ArgumentValue.GetType(); Type specifiedType = argumentToBind.ArgumentValue?.GetType();
ParameterBindingException bindingException = ParameterBindingException bindingException =
new ParameterBindingException( new ParameterBindingException(
error, error,

View File

@ -157,7 +157,7 @@ namespace System.Management.Automation
} }
// If we are in a debugger stop, let the debugger do the command completion. // If we are in a debugger stop, let the debugger do the command completion.
var debugger = (powershell.Runspace != null) ? powershell.Runspace.Debugger : null; var debugger = powershell.Runspace?.Debugger;
if ((debugger != null) && debugger.InBreakpoint) if ((debugger != null) && debugger.InBreakpoint)
{ {
return CompleteInputInDebugger(input, cursorIndex, options, debugger); return CompleteInputInDebugger(input, cursorIndex, options, debugger);
@ -236,7 +236,7 @@ namespace System.Management.Automation
} }
// If we are in a debugger stop, let the debugger do the command completion. // If we are in a debugger stop, let the debugger do the command completion.
var debugger = (powershell.Runspace != null) ? powershell.Runspace.Debugger : null; var debugger = powershell.Runspace?.Debugger;
if ((debugger != null) && debugger.InBreakpoint) if ((debugger != null) && debugger.InBreakpoint)
{ {
return CompleteInputInDebugger(ast, tokens, cursorPosition, options, debugger); return CompleteInputInDebugger(ast, tokens, cursorPosition, options, debugger);

View File

@ -201,9 +201,9 @@ namespace System.Management.Automation.Language
ParameterArgumentType = AstParameterArgumentType.AstPair; ParameterArgumentType = AstParameterArgumentType.AstPair;
ParameterSpecified = parameterAst != null; ParameterSpecified = parameterAst != null;
ArgumentSpecified = argumentAst != null; ArgumentSpecified = argumentAst != null;
ParameterName = parameterAst != null ? parameterAst.ParameterName : null; ParameterName = parameterAst?.ParameterName;
ParameterText = parameterAst != null ? parameterAst.ParameterName : null; ParameterText = parameterAst?.ParameterName;
ArgumentType = argumentAst != null ? argumentAst.StaticType : null; ArgumentType = argumentAst?.StaticType;
ParameterContainsArgument = false; ParameterContainsArgument = false;
Argument = argumentAst; Argument = argumentAst;

View File

@ -607,7 +607,7 @@ namespace System.Management.Automation
string errorId, string errorId,
params object[] args) params object[] args)
{ {
Type inputObjectType = (inputObject == null) ? null : inputObject.GetType(); Type inputObjectType = inputObject?.GetType();
ParameterBindingException bindingException = new ParameterBindingException( ParameterBindingException bindingException = new ParameterBindingException(
ErrorCategory.InvalidArgument, ErrorCategory.InvalidArgument,

View File

@ -2457,7 +2457,7 @@ namespace System.Management.Automation
/// </param> /// </param>
/// </summary> /// </summary>
public PSEventJob(PSEventManager eventManager, PSEventSubscriber subscriber, ScriptBlock action, string name) : public PSEventJob(PSEventManager eventManager, PSEventSubscriber subscriber, ScriptBlock action, string name) :
base(action == null ? null : action.ToString(), name) base(action?.ToString(), name)
{ {
if (eventManager == null) if (eventManager == null)
throw new ArgumentNullException(nameof(eventManager)); throw new ArgumentNullException(nameof(eventManager));

View File

@ -403,7 +403,7 @@ namespace System.Management.Automation
get get
{ {
var data = GetRequiresData(); var data = GetRequiresData();
return data == null ? null : data.RequiredApplicationId; return data?.RequiredApplicationId;
} }
} }
@ -417,7 +417,7 @@ namespace System.Management.Automation
get get
{ {
var data = GetRequiresData(); var data = GetRequiresData();
return data == null ? null : data.RequiredPSVersion; return data?.RequiredPSVersion;
} }
} }
@ -426,7 +426,7 @@ namespace System.Management.Automation
get get
{ {
var data = GetRequiresData(); var data = GetRequiresData();
return data == null ? null : data.RequiredPSEditions; return data?.RequiredPSEditions;
} }
} }
@ -435,7 +435,7 @@ namespace System.Management.Automation
get get
{ {
var data = GetRequiresData(); var data = GetRequiresData();
return data == null ? null : data.RequiredModules; return data?.RequiredModules;
} }
} }
@ -458,7 +458,7 @@ namespace System.Management.Automation
get get
{ {
var data = GetRequiresData(); var data = GetRequiresData();
return data == null ? null : data.RequiresPSSnapIns; return data?.RequiresPSSnapIns;
} }
} }

View File

@ -360,7 +360,7 @@ namespace System.Management.Automation
Exception outerException = new InvalidOperationException(errorMessage, innerException); Exception outerException = new InvalidOperationException(errorMessage, innerException);
RemoteException remoteException = innerException as RemoteException; 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; string errorId = remoteErrorRecord != null ? remoteErrorRecord.FullyQualifiedErrorId : innerException.GetType().Name;
ErrorCategory errorCategory = remoteErrorRecord != null ? remoteErrorRecord.CategoryInfo.Category : ErrorCategory.NotSpecified; ErrorCategory errorCategory = remoteErrorRecord != null ? remoteErrorRecord.CategoryInfo.Category : ErrorCategory.NotSpecified;
ErrorRecord errorRecord = new ErrorRecord(outerException, errorId, errorCategory, null); ErrorRecord errorRecord = new ErrorRecord(outerException, errorId, errorCategory, null);

View File

@ -439,7 +439,7 @@ namespace System.Management.Automation
GetErrorExtent(parameter), GetErrorExtent(parameter),
parameterMetadata.Name, parameterMetadata.Name,
parameterMetadata.Type, parameterMetadata.Type,
(parameterValue == null) ? null : parameterValue.GetType(), parameterValue?.GetType(),
ParameterBinderStrings.ParameterArgumentTransformationError, ParameterBinderStrings.ParameterArgumentTransformationError,
"ParameterArgumentTransformationError", "ParameterArgumentTransformationError",
e.Message); e.Message);
@ -522,7 +522,7 @@ namespace System.Management.Automation
GetErrorExtent(parameter), GetErrorExtent(parameter),
parameterMetadata.Name, parameterMetadata.Name,
parameterMetadata.Type, parameterMetadata.Type,
(parameterValue == null) ? null : parameterValue.GetType(), parameterValue?.GetType(),
ParameterBinderStrings.ParameterArgumentValidationError, ParameterBinderStrings.ParameterArgumentValidationError,
"ParameterArgumentValidationError", "ParameterArgumentValidationError",
e.Message); e.Message);
@ -586,7 +586,7 @@ namespace System.Management.Automation
if (bindError != null) if (bindError != null)
{ {
Type specifiedType = (parameterValue == null) ? null : parameterValue.GetType(); Type specifiedType = parameterValue?.GetType();
ParameterBindingException bindingException = ParameterBindingException bindingException =
new ParameterBindingException( new ParameterBindingException(
bindError, bindError,
@ -736,7 +736,7 @@ namespace System.Management.Automation
GetErrorExtent(parameter), GetErrorExtent(parameter),
parameterMetadata.Name, parameterMetadata.Name,
parameterMetadata.Type, parameterMetadata.Type,
(parameterValue == null) ? null : parameterValue.GetType(), parameterValue?.GetType(),
ParameterBinderStrings.ParameterArgumentValidationErrorEmptyStringNotAllowed, ParameterBinderStrings.ParameterArgumentValidationErrorEmptyStringNotAllowed,
"ParameterArgumentValidationErrorEmptyStringNotAllowed"); "ParameterArgumentValidationErrorEmptyStringNotAllowed");
throw bindingException; throw bindingException;
@ -813,7 +813,7 @@ namespace System.Management.Automation
GetErrorExtent(parameter), GetErrorExtent(parameter),
parameterMetadata.Name, parameterMetadata.Name,
parameterMetadata.Type, parameterMetadata.Type,
(parameterValue == null) ? null : parameterValue.GetType(), parameterValue?.GetType(),
resourceString, resourceString,
errorId); errorId);
throw bindingException; throw bindingException;
@ -1781,7 +1781,7 @@ namespace System.Management.Automation
GetErrorExtent(argument), GetErrorExtent(argument),
parameterName, parameterName,
toType, toType,
(currentValueElement == null) ? null : currentValueElement.GetType(), currentValueElement?.GetType(),
ParameterBinderStrings.CannotConvertArgument, ParameterBinderStrings.CannotConvertArgument,
"CannotConvertArgument", "CannotConvertArgument",
currentValueElement ?? "null", currentValueElement ?? "null",
@ -1878,7 +1878,7 @@ namespace System.Management.Automation
GetErrorExtent(argument), GetErrorExtent(argument),
parameterName, parameterName,
toType, toType,
(currentValue == null) ? null : currentValue.GetType(), currentValue?.GetType(),
ParameterBinderStrings.CannotConvertArgument, ParameterBinderStrings.CannotConvertArgument,
"CannotConvertArgument", "CannotConvertArgument",
currentValue ?? "null", currentValue ?? "null",

View File

@ -36,7 +36,7 @@ namespace System.Management.Automation
{ {
string key = pair.Key; string key = pair.Key;
RuntimeDefinedParameter pp = pair.Value; RuntimeDefinedParameter pp = pair.Value;
string ppName = (pp == null) ? null : pp.Name; string ppName = pp?.Name;
if (pp == null || key != ppName) if (pp == null || key != ppName)
{ {
ParameterBindingException bindingException = ParameterBindingException bindingException =

View File

@ -489,7 +489,7 @@ namespace System.Management.Automation
} }
else 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) if (ExecutionContext.HasEverUsedConstrainedLanguage)

View File

@ -1447,7 +1447,7 @@ namespace System.Management.Automation
return null; return null;
var callStackInfo = _callStack.Last(); 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(); return breakpoints.Values.Where(bp => bp.Trigger(currentScriptFile, read: read)).ToList();
} }
finally finally
@ -1633,7 +1633,7 @@ namespace System.Management.Automation
internal FunctionContext LastFunctionContext() internal FunctionContext LastFunctionContext()
{ {
var last = Last(); var last = Last();
return last != null ? last.FunctionContext : null; return last?.FunctionContext;
} }
internal bool Any() internal bool Any()
@ -3677,7 +3677,7 @@ namespace System.Management.Automation
} }
// Clean up nested debugger. // Clean up nested debugger.
NestedRunspaceDebugger nestedDebugger = (runspaceInfo != null) ? runspaceInfo.NestedDebugger : null; NestedRunspaceDebugger nestedDebugger = runspaceInfo?.NestedDebugger;
if (nestedDebugger != null) if (nestedDebugger != null)
{ {
nestedDebugger.DebuggerStop -= HandleMonitorRunningRSDebuggerStop; nestedDebugger.DebuggerStop -= HandleMonitorRunningRSDebuggerStop;
@ -4447,7 +4447,7 @@ namespace System.Management.Automation
{ {
// Nested debugged runspace prompt should look like: // Nested debugged runspace prompt should look like:
// [ComputerName]: [DBG]: [Process:<id>]: [RunspaceName]: PS C:\> // [ComputerName]: [DBG]: [Process:<id>]: [RunspaceName]: PS C:\>
string computerName = (_runspace.ConnectionInfo != null) ? _runspace.ConnectionInfo.ComputerName : null; string computerName = _runspace.ConnectionInfo?.ComputerName;
string processPartPattern = "{0}[{1}:{2}]:{3}"; string processPartPattern = "{0}[{1}:{2}]:{3}";
string processPart = StringUtil.Format(processPartPattern, string processPart = StringUtil.Format(processPartPattern,
@"""", @"""",

View File

@ -952,7 +952,7 @@ namespace System.Management.Automation.Runspaces
{ {
RemoteRunspace remoteRunspace = this as RemoteRunspace; RemoteRunspace remoteRunspace = this as RemoteRunspace;
RemoteDebugger remoteDebugger = (remoteRunspace != null) ? remoteRunspace.Debugger as RemoteDebugger : null; 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) || if (((pipelineState == PipelineState.Completed) || (pipelineState == PipelineState.Failed) ||
((pipelineState == PipelineState.Stopped) && (this.RunspaceStateInfo.State == RunspaceState.Opened))) ((pipelineState == PipelineState.Stopped) && (this.RunspaceStateInfo.State == RunspaceState.Opened)))
&& (remoteCommand != null) && (cmdInstanceId != null) && (remoteCommand.CommandId == cmdInstanceId)) && (remoteCommand != null) && (cmdInstanceId != null) && (remoteCommand.CommandId == cmdInstanceId))
@ -1590,7 +1590,7 @@ namespace System.Management.Automation.Runspaces
get get
{ {
var context = GetExecutionContext; var context = GetExecutionContext;
return (context != null) ? context.Debugger : null; return context?.Debugger;
} }
} }

View File

@ -759,7 +759,7 @@ namespace Microsoft.PowerShell.Commands
{ {
int historySize = 0; int historySize = 0;
var executionContext = LocalPipeline.GetExecutionContextFromTLS(); var executionContext = LocalPipeline.GetExecutionContextFromTLS();
object obj = (executionContext != null) ? executionContext.GetVariableValue(SpecialVariables.HistorySizeVarPath) : null; object obj = executionContext?.GetVariableValue(SpecialVariables.HistorySizeVarPath);
if (obj != null) if (obj != null)
{ {
try try

View File

@ -312,7 +312,7 @@ namespace System.Management.Automation.Interpreter
_maxStackDepth, _maxStackDepth,
_maxContinuationDepth, _maxContinuationDepth,
_instructions.ToArray(), _instructions.ToArray(),
(_objects != null) ? _objects.ToArray() : null, _objects?.ToArray(),
BuildRuntimeLabels(), BuildRuntimeLabels(),
_debugCookies _debugCookies
); );

View File

@ -1531,7 +1531,7 @@ namespace System.Management.Automation.Interpreter
enterTryInstr.SetTryHandler( enterTryInstr.SetTryHandler(
new TryCatchFinallyHandler(tryStart, tryEnd, gotoEnd.TargetIndex, new TryCatchFinallyHandler(tryStart, tryEnd, gotoEnd.TargetIndex,
startOfFinally.TargetIndex, _instructions.Count, startOfFinally.TargetIndex, _instructions.Count,
exHandlers != null ? exHandlers.ToArray() : null)); exHandlers?.ToArray()));
PopLabelBlock(LabelScopeKind.Finally); PopLabelBlock(LabelScopeKind.Finally);
} }
else else

View File

@ -378,8 +378,8 @@ namespace System.Management.Automation
lval = PSObject.Base(lval); lval = PSObject.Base(lval);
rval = PSObject.Base(rval); rval = PSObject.Base(rval);
Type lvalType = lval != null ? lval.GetType() : null; Type lvalType = lval?.GetType();
Type rvalType = rval != null ? rval.GetType() : null; Type rvalType = rval?.GetType();
Type opType; Type opType;
if (lvalType == null || (lvalType.IsPrimitive)) if (lvalType == null || (lvalType.IsPrimitive))
{ {

View File

@ -596,7 +596,7 @@ namespace System.Management.Automation
/// Get the PSModuleInfo object for the module that defined this /// Get the PSModuleInfo object for the module that defined this
/// scriptblock. /// scriptblock.
/// </summary> /// </summary>
public PSModuleInfo Module { get => SessionStateInternal != null ? SessionStateInternal.Module : null; } public PSModuleInfo Module { get => SessionStateInternal?.Module; }
/// <summary> /// <summary>
/// Return the PSToken object for this function definition... /// Return the PSToken object for this function definition...
@ -709,7 +709,7 @@ namespace System.Management.Automation
} }
} }
return SessionStateInternal != null ? SessionStateInternal.PublicSessionState : null; return SessionStateInternal?.PublicSessionState;
} }
set set
@ -1138,7 +1138,7 @@ namespace System.Management.Automation
ExecutionContext executionContext = contextToRedirectTo.SessionState.Internal.ExecutionContext; ExecutionContext executionContext = contextToRedirectTo.SessionState.Internal.ExecutionContext;
CommandProcessorBase commandProcessor = executionContext.CurrentCommandProcessor; CommandProcessorBase commandProcessor = executionContext.CurrentCommandProcessor;
ICommandRuntime crt = commandProcessor == null ? null : commandProcessor.CommandRuntime; ICommandRuntime crt = commandProcessor?.CommandRuntime;
Begin(expectInput, crt); Begin(expectInput, crt);
} }

View File

@ -1166,7 +1166,7 @@ namespace System.Management.Automation.Language
expr = ((AttributedExpressionAst)expr).Child; 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) internal static PSMethodInvocationConstraints CombineTypeConstraintForMethodResolution(Type targetType, Type argType)
@ -6311,7 +6311,7 @@ namespace System.Management.Automation.Language
var targetTypeConstraint = GetTypeConstraintForMethodResolution(invokeMemberExpressionAst.Expression); var targetTypeConstraint = GetTypeConstraintForMethodResolution(invokeMemberExpressionAst.Expression);
return CombineTypeConstraintForMethodResolution( return CombineTypeConstraintForMethodResolution(
targetTypeConstraint, targetTypeConstraint,
arguments != null ? arguments.Select(Compiler.GetTypeConstraintForMethodResolution).ToArray() : null); arguments?.Select(Compiler.GetTypeConstraintForMethodResolution).ToArray());
} }
internal static PSMethodInvocationConstraints GetInvokeMemberConstraints(BaseCtorInvokeMemberExpressionAst invokeMemberExpressionAst) internal static PSMethodInvocationConstraints GetInvokeMemberConstraints(BaseCtorInvokeMemberExpressionAst invokeMemberExpressionAst)
@ -6330,7 +6330,7 @@ namespace System.Management.Automation.Language
return CombineTypeConstraintForMethodResolution( return CombineTypeConstraintForMethodResolution(
targetTypeConstraint, targetTypeConstraint,
arguments != null ? arguments.Select(Compiler.GetTypeConstraintForMethodResolution).ToArray() : null); arguments?.Select(Compiler.GetTypeConstraintForMethodResolution).ToArray());
} }
internal Expression InvokeMember( internal Expression InvokeMember(
@ -6343,7 +6343,7 @@ namespace System.Management.Automation.Language
bool nullConditional = false) bool nullConditional = false)
{ {
var callInfo = new CallInfo(args.Count()); 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 var binder = name.Equals("new", StringComparison.OrdinalIgnoreCase) && @static
? (CallSiteBinder)PSCreateInstanceBinder.Get(callInfo, constraints, publicTypeOnly: true) ? (CallSiteBinder)PSCreateInstanceBinder.Get(callInfo, constraints, publicTypeOnly: true)
: PSInvokeMemberBinder.Get(name, callInfo, @static, propertySet, constraints, classScope); : PSInvokeMemberBinder.Get(name, callInfo, @static, propertySet, constraints, classScope);

View File

@ -1666,7 +1666,7 @@ namespace System.Management.Automation.Language
statements.Add(predefinedStatementAst); statements.Add(predefinedStatementAst);
} }
IScriptExtent statementListExtent = paramBlockAst != null ? paramBlockAst.Extent : null; IScriptExtent statementListExtent = paramBlockAst?.Extent;
IScriptExtent scriptBlockExtent; IScriptExtent scriptBlockExtent;
while (true) while (true)
@ -1707,7 +1707,7 @@ namespace System.Management.Automation.Language
NamedBlockAst endBlock = null; NamedBlockAst endBlock = null;
IScriptExtent startExtent = lCurly != null IScriptExtent startExtent = lCurly != null
? lCurly.Extent ? lCurly.Extent
: (paramBlockAst != null) ? paramBlockAst.Extent : null; : paramBlockAst?.Extent;
IScriptExtent endExtent = null; IScriptExtent endExtent = null;
IScriptExtent extent = null; IScriptExtent extent = null;
IScriptExtent scriptBlockExtent = null; IScriptExtent scriptBlockExtent = null;
@ -2042,7 +2042,7 @@ namespace System.Management.Automation.Language
statement = BlockStatementRule(token); statement = BlockStatementRule(token);
break; break;
case TokenKind.Configuration: case TokenKind.Configuration:
statement = ConfigurationStatementRule(attributes != null ? attributes.OfType<AttributeAst>() : null, token); statement = ConfigurationStatementRule(attributes?.OfType<AttributeAst>(), token);
break; break;
case TokenKind.From: case TokenKind.From:
case TokenKind.Define: case TokenKind.Define:
@ -2848,7 +2848,7 @@ namespace System.Management.Automation.Language
} }
return new SwitchStatementAst(ExtentOf(labelToken ?? switchToken, rCurly), 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<AttributeAst> customAttributes, Token configurationToken) private StatementAst ConfigurationStatementRule(IEnumerable<AttributeAst> customAttributes, Token configurationToken)
@ -3439,7 +3439,7 @@ namespace System.Management.Automation.Language
} }
return new ForEachStatementAst(ExtentOf(startOfStatement, body), return new ForEachStatementAst(ExtentOf(startOfStatement, body),
labelToken != null ? labelToken.LabelText : null, labelToken?.LabelText,
flags, flags,
throttleLimit, variableAst, pipeline, body); throttleLimit, variableAst, pipeline, body);
} }
@ -3552,7 +3552,7 @@ namespace System.Management.Automation.Language
} }
return new ForStatementAst(ExtentOf(labelToken ?? forToken, body), 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) private StatementAst WhileStatementRule(LabelToken labelToken, Token whileToken)
@ -3634,7 +3634,7 @@ namespace System.Management.Automation.Language
} }
return new WhileStatementAst(ExtentOf(labelToken ?? whileToken, body), return new WhileStatementAst(ExtentOf(labelToken ?? whileToken, body),
labelToken != null ? labelToken.LabelText : null, condition, body); labelToken?.LabelText, condition, body);
} }
/// <summary> /// <summary>
@ -4129,7 +4129,7 @@ namespace System.Management.Automation.Language
} }
IScriptExtent extent = ExtentOf(startExtent, rParen); IScriptExtent extent = ExtentOf(startExtent, rParen);
string label = (labelToken != null) ? labelToken.LabelText : null; string label = labelToken?.LabelText;
if (whileOrUntilToken.Kind == TokenKind.Until) if (whileOrUntilToken.Kind == TokenKind.Until)
{ {
return new DoUntilStatementAst(extent, label, condition, body); return new DoUntilStatementAst(extent, label, condition, body);
@ -4283,7 +4283,7 @@ namespace System.Management.Automation.Language
? customAttributes[0].Extent ? customAttributes[0].Extent
: classToken.Extent; : classToken.Extent;
var extent = ExtentOf(startExtent, lastExtent); var extent = ExtentOf(startExtent, lastExtent);
var classDefn = new TypeDefinitionAst(extent, name.Value, customAttributes == null ? null : customAttributes.OfType<AttributeAst>(), members, TypeAttributes.Class, superClassesList); var classDefn = new TypeDefinitionAst(extent, name.Value, customAttributes?.OfType<AttributeAst>(), members, TypeAttributes.Class, superClassesList);
if (customAttributes != null && customAttributes.OfType<TypeConstraintAst>().Any()) if (customAttributes != null && customAttributes.OfType<TypeConstraintAst>().Any())
{ {
if (nestedAsts == null) if (nestedAsts == null)
@ -4744,7 +4744,7 @@ namespace System.Management.Automation.Language
? customAttributes[0].Extent ? customAttributes[0].Extent
: enumToken.Extent; : enumToken.Extent;
var extent = ExtentOf(startExtent, rCurly); var extent = ExtentOf(startExtent, rCurly);
var enumDefn = new TypeDefinitionAst(extent, name.Value, customAttributes == null ? null : customAttributes.OfType<AttributeAst>(), members, TypeAttributes.Enum, underlyingTypeConstraint == null ? null : new[] { underlyingTypeConstraint }); var enumDefn = new TypeDefinitionAst(extent, name.Value, customAttributes?.OfType<AttributeAst>(), members, TypeAttributes.Enum, underlyingTypeConstraint == null ? null : new[] { underlyingTypeConstraint });
if (customAttributes != null && customAttributes.OfType<TypeConstraintAst>().Any()) if (customAttributes != null && customAttributes.OfType<TypeConstraintAst>().Any())
{ {
// No need to report error since there is error reported in method StatementRule // No need to report error since there is error reported in method StatementRule
@ -5623,7 +5623,7 @@ namespace System.Management.Automation.Language
IScriptExtent endErrorStatement = null; IScriptExtent endErrorStatement = null;
SkipNewlines(); SkipNewlines();
var dataVariableNameAst = SimpleNameRule(); var dataVariableNameAst = SimpleNameRule();
string dataVariableName = (dataVariableNameAst != null) ? dataVariableNameAst.Value : null; string dataVariableName = dataVariableNameAst?.Value;
SkipNewlines(); SkipNewlines();
Token supportedCommandToken = PeekToken(); Token supportedCommandToken = PeekToken();
@ -6629,7 +6629,7 @@ namespace System.Management.Automation.Language
return new CommandAst(ExtentOf(firstToken, endExtent), elements, return new CommandAst(ExtentOf(firstToken, endExtent), elements,
dotSource || ampersand ? firstToken.Kind : TokenKind.Unknown, dotSource || ampersand ? firstToken.Kind : TokenKind.Unknown,
redirections != null ? redirections.Where(r => r != null) : null); redirections?.Where(r => r != null));
} }
#endregion Pipelines #endregion Pipelines

View File

@ -670,7 +670,7 @@ namespace System.Management.Automation.Language
} }
var str = expr as StringConstantExpressionAst; var str = expr as StringConstantExpressionAst;
return str != null ? str.Value : null; return str?.Value;
} }
public override AstVisitAction VisitBreakStatement(BreakStatementAst breakStatementAst) public override AstVisitAction VisitBreakStatement(BreakStatementAst breakStatementAst)

View File

@ -246,7 +246,7 @@ namespace System.Management.Automation.Language
try try
{ {
exception = null; 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, Type result = ResolveTypeNameWorker(typeName, currentScope, typeResolutionState.assemblies, t_searchedAssemblies, typeResolutionState,
/*onlySearchInGivenAssemblies*/ false, /* reportAmbiguousException */ true, out exception); /*onlySearchInGivenAssemblies*/ false, /* reportAmbiguousException */ true, out exception);
if (exception == null && result == null) if (exception == null && result == null)

View File

@ -2656,7 +2656,7 @@ namespace System.Management.Automation.Language
internal override object Accept(ICustomAstVisitor visitor) internal override object Accept(ICustomAstVisitor visitor)
{ {
var visitor2 = visitor as ICustomAstVisitor2; var visitor2 = visitor as ICustomAstVisitor2;
return visitor2 != null ? visitor2.VisitTypeDefinition(this) : null; return visitor2?.VisitTypeDefinition(this);
} }
internal override AstVisitAction InternalVisit(AstVisitor visitor) internal override AstVisitAction InternalVisit(AstVisitor visitor)
@ -2904,7 +2904,7 @@ namespace System.Management.Automation.Language
internal override object Accept(ICustomAstVisitor visitor) internal override object Accept(ICustomAstVisitor visitor)
{ {
var visitor2 = visitor as ICustomAstVisitor2; var visitor2 = visitor as ICustomAstVisitor2;
return visitor2 != null ? visitor2.VisitUsingStatement(this) : null; return visitor2?.VisitUsingStatement(this);
} }
internal override AstVisitAction InternalVisit(AstVisitor visitor) internal override AstVisitAction InternalVisit(AstVisitor visitor)
@ -3132,7 +3132,7 @@ namespace System.Management.Automation.Language
internal override object Accept(ICustomAstVisitor visitor) internal override object Accept(ICustomAstVisitor visitor)
{ {
var visitor2 = visitor as ICustomAstVisitor2; var visitor2 = visitor as ICustomAstVisitor2;
return visitor2 != null ? visitor2.VisitPropertyMember(this) : null; return visitor2?.VisitPropertyMember(this);
} }
internal override AstVisitAction InternalVisit(AstVisitor visitor) internal override AstVisitAction InternalVisit(AstVisitor visitor)
@ -3352,7 +3352,7 @@ namespace System.Management.Automation.Language
internal override object Accept(ICustomAstVisitor visitor) internal override object Accept(ICustomAstVisitor visitor)
{ {
var visitor2 = visitor as ICustomAstVisitor2; var visitor2 = visitor as ICustomAstVisitor2;
return visitor2 != null ? visitor2.VisitFunctionMember(this) : null; return visitor2?.VisitFunctionMember(this);
} }
internal override AstVisitAction InternalVisit(AstVisitor visitor) internal override AstVisitAction InternalVisit(AstVisitor visitor)
@ -3829,7 +3829,7 @@ namespace System.Management.Automation.Language
ReadOnlyCollection<ParameterAst> IParameterMetadataProvider.Parameters ReadOnlyCollection<ParameterAst> IParameterMetadataProvider.Parameters
{ {
get { return Parameters ?? (Body.ParamBlock != null ? Body.ParamBlock.Parameters : null); } get { return Parameters ?? (Body.ParamBlock?.Parameters); }
} }
PowerShell IParameterMetadataProvider.GetPowerShell(ExecutionContext context, Dictionary<string, object> variables, bool isTrustedInput, PowerShell IParameterMetadataProvider.GetPowerShell(ExecutionContext context, Dictionary<string, object> variables, bool isTrustedInput,
@ -5879,7 +5879,7 @@ namespace System.Management.Automation.Language
public string GetCommandName() public string GetCommandName()
{ {
var name = CommandElements[0] as StringConstantExpressionAst; var name = CommandElements[0] as StringConstantExpressionAst;
return name != null ? name.Value : null; return name?.Value;
} }
/// <summary> /// <summary>
@ -6422,7 +6422,7 @@ namespace System.Management.Automation.Language
{ {
LCurlyToken = this.LCurlyToken, LCurlyToken = this.LCurlyToken,
ConfigurationToken = this.ConfigurationToken, 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 @@ namespace System.Management.Automation.Language
internal override object Accept(ICustomAstVisitor visitor) internal override object Accept(ICustomAstVisitor visitor)
{ {
var visitor2 = visitor as ICustomAstVisitor2; var visitor2 = visitor as ICustomAstVisitor2;
return visitor2 != null ? visitor2.VisitConfigurationDefinition(this) : null; return visitor2?.VisitConfigurationDefinition(this);
} }
internal override AstVisitAction InternalVisit(AstVisitor visitor) internal override AstVisitAction InternalVisit(AstVisitor visitor)
@ -6521,7 +6521,7 @@ namespace System.Management.Automation.Language
cea.Add(new CommandParameterAst(PositionUtilities.EmptyExtent, "ResourceModuleTuplesToImport", new ConstantExpressionAst(PositionUtilities.EmptyExtent, resourceModulePairsToImport), PositionUtilities.EmptyExtent)); cea.Add(new CommandParameterAst(PositionUtilities.EmptyExtent, "ResourceModuleTuplesToImport", new ConstantExpressionAst(PositionUtilities.EmptyExtent, resourceModulePairsToImport), PositionUtilities.EmptyExtent));
var scriptBlockBody = new ScriptBlockAst(Body.Extent, var scriptBlockBody = new ScriptBlockAst(Body.Extent,
CustomAttributes == null ? null : CustomAttributes.Select(att => (AttributeAst)att.Copy()).ToList(), CustomAttributes?.Select(att => (AttributeAst)att.Copy()).ToList(),
null, null,
new StatementBlockAst(Body.Extent, resourceBody, null), new StatementBlockAst(Body.Extent, resourceBody, null),
false, false); false, false);
@ -6580,7 +6580,7 @@ namespace System.Management.Automation.Language
var statmentBlockAst = new StatementBlockAst(this.Extent, funcStatements, null); var statmentBlockAst = new StatementBlockAst(this.Extent, funcStatements, null);
var funcBody = new ScriptBlockAst(Body.Extent, 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); paramBlockAst, statmentBlockAst, false, true);
var funcBodyExp = new ScriptBlockExpressionAst(this.Extent, funcBody); var funcBodyExp = new ScriptBlockExpressionAst(this.Extent, funcBody);
@ -6898,7 +6898,7 @@ namespace System.Management.Automation.Language
internal override object Accept(ICustomAstVisitor visitor) internal override object Accept(ICustomAstVisitor visitor)
{ {
var visitor2 = visitor as ICustomAstVisitor2; var visitor2 = visitor as ICustomAstVisitor2;
return visitor2 != null ? visitor2.VisitDynamicKeywordStatement(this) : null; return visitor2?.VisitDynamicKeywordStatement(this);
} }
internal override AstVisitAction InternalVisit(AstVisitor visitor) internal override AstVisitAction InternalVisit(AstVisitor visitor)
@ -8103,7 +8103,7 @@ namespace System.Management.Automation.Language
internal override object Accept(ICustomAstVisitor visitor) internal override object Accept(ICustomAstVisitor visitor)
{ {
var visitor2 = visitor as ICustomAstVisitor2; var visitor2 = visitor as ICustomAstVisitor2;
return visitor2 != null ? visitor2.VisitBaseCtorInvokeMemberExpression(this) : null; return visitor2?.VisitBaseCtorInvokeMemberExpression(this);
} }
} }

View File

@ -645,7 +645,7 @@ namespace System.Management.Automation.Runspaces.Internal
// If RemoteSessionStateEventArgs are provided then use them to set the // If RemoteSessionStateEventArgs are provided then use them to set the
// session close reason when setting finished state. // session close reason when setting finished state.
RemoteSessionStateEventArgs sessionEventArgs = args as RemoteSessionStateEventArgs; 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 finishedState = (shell.InvocationStateInfo.State == PSInvocationState.Disconnected) ?
PSInvocationState.Failed : PSInvocationState.Stopped; PSInvocationState.Failed : PSInvocationState.Stopped;

View File

@ -1412,7 +1412,7 @@ namespace System.Management.Automation.Internal
// disconnect may be called on a pipeline that is already disconnected. // disconnect may be called on a pipeline that is already disconnected.
PSInvocationStateInfo stateInfo = PSInvocationStateInfo stateInfo =
new PSInvocationStateInfo(PSInvocationState.Disconnected, new PSInvocationStateInfo(PSInvocationState.Disconnected,
(rsStateInfo != null) ? rsStateInfo.Reason : null); rsStateInfo?.Reason);
Dbg.Assert(InvocationStateInfoReceived != null, Dbg.Assert(InvocationStateInfoReceived != null,
"ClientRemotePowerShell should subscribe to all data structure handler events"); "ClientRemotePowerShell should subscribe to all data structure handler events");

View File

@ -1939,7 +1939,7 @@ namespace System.Management.Automation
if (re.ErrorRecord.CategoryInfo.Reason == nameof(IncompleteParseException)) if (re.ErrorRecord.CategoryInfo.Reason == nameof(IncompleteParseException))
{ {
throw new IncompleteParseException( throw new IncompleteParseException(
(re.ErrorRecord.Exception != null) ? re.ErrorRecord.Exception.Message : null, re.ErrorRecord.Exception?.Message,
re.ErrorRecord.FullyQualifiedErrorId); re.ErrorRecord.FullyQualifiedErrorId);
} }
@ -2660,7 +2660,7 @@ namespace System.Management.Automation
// Attempt to process debugger stop event on original thread if it // Attempt to process debugger stop event on original thread if it
// is available (i.e., if it is blocked by EndInvoke). // is available (i.e., if it is blocked by EndInvoke).
PowerShell powershell = _runspace.RunspacePool.RemoteRunspacePoolInternal.GetCurrentRunningPowerShell(); PowerShell powershell = _runspace.RunspacePool.RemoteRunspacePoolInternal.GetCurrentRunningPowerShell();
AsyncResult invokeAsyncResult = (powershell != null) ? powershell.EndInvokeAsyncResult : null; AsyncResult invokeAsyncResult = powershell?.EndInvokeAsyncResult;
bool invokedOnBlockedThread = false; bool invokedOnBlockedThread = false;
if ((invokeAsyncResult != null) && (!invokeAsyncResult.IsCompleted)) if ((invokeAsyncResult != null) && (!invokeAsyncResult.IsCompleted))

View File

@ -589,8 +589,8 @@ else
restartServiceTarget, restartServiceTarget,
restartServiceAction, restartServiceAction,
restartWSManRequiredForUI, restartWSManRequiredForUI,
runAsCredential != null ? runAsCredential.UserName : null, runAsCredential?.UserName,
runAsCredential != null ? runAsCredential.Password : null, runAsCredential?.Password,
AccessMode, AccessMode,
isSddlSpecified, isSddlSpecified,
_configTableSDDL, _configTableSDDL,

View File

@ -2395,7 +2395,7 @@ namespace System.Management.Automation.Remoting
if (Convert.ToBoolean(_configHash[ConfigFileConstants.MountUserDrive], CultureInfo.InvariantCulture)) if (Convert.ToBoolean(_configHash[ConfigFileConstants.MountUserDrive], CultureInfo.InvariantCulture))
{ {
iss.UserDriveEnabled = true; 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. // Set user drive max drive if provided.
if (_configHash.ContainsKey(ConfigFileConstants.UserDriveMaxSize)) if (_configHash.ContainsKey(ConfigFileConstants.UserDriveMaxSize))

View File

@ -334,7 +334,7 @@ namespace System.Management.Automation.Remoting
// PSEdit support. Existence of RemoteSessionOpenFileEvent event indicates host supports PSEdit // PSEdit support. Existence of RemoteSessionOpenFileEvent event indicates host supports PSEdit
_hostSupportsPSEdit = false; _hostSupportsPSEdit = false;
PSEventManager localEventManager = (Runspace != null) ? Runspace.Events : null; PSEventManager localEventManager = Runspace?.Events;
_hostSupportsPSEdit = (localEventManager != null) ? localEventManager.GetEventSubscribers(HostUtilities.RemoteSessionOpenFileEvent).GetEnumerator().MoveNext() : false; _hostSupportsPSEdit = (localEventManager != null) ? localEventManager.GetEventSubscribers(HostUtilities.RemoteSessionOpenFileEvent).GetEnumerator().MoveNext() : false;
if (_hostSupportsPSEdit) if (_hostSupportsPSEdit)
{ {

View File

@ -1202,7 +1202,7 @@ namespace System.Management.Automation.Language
{ {
PSInvokeDynamicMemberBinder result; PSInvokeDynamicMemberBinder result;
var classScope = classScopeAst != null ? classScopeAst.Type : null; var classScope = classScopeAst?.Type;
lock (s_binderCache) lock (s_binderCache)
{ {
var key = Tuple.Create(callInfo, constraints, propertySetter, @static, classScope); var key = Tuple.Create(callInfo, constraints, propertySetter, @static, classScope);
@ -1296,7 +1296,7 @@ namespace System.Management.Automation.Language
PSGetDynamicMemberBinder binder; PSGetDynamicMemberBinder binder;
lock (s_binderCache) lock (s_binderCache)
{ {
var type = classScope != null ? classScope.Type : null; var type = classScope?.Type;
var tuple = Tuple.Create(type, @static); var tuple = Tuple.Create(type, @static);
if (!s_binderCache.TryGetValue(tuple, out binder)) if (!s_binderCache.TryGetValue(tuple, out binder))
{ {
@ -1406,7 +1406,7 @@ namespace System.Management.Automation.Language
PSSetDynamicMemberBinder binder; PSSetDynamicMemberBinder binder;
lock (s_binderCache) lock (s_binderCache)
{ {
var type = classScope != null ? classScope.Type : null; var type = classScope?.Type;
var tuple = Tuple.Create(type, @static); var tuple = Tuple.Create(type, @static);
if (!s_binderCache.TryGetValue(tuple, out binder)) if (!s_binderCache.TryGetValue(tuple, out binder))
{ {
@ -5071,7 +5071,7 @@ namespace System.Management.Automation.Language
public static PSGetMemberBinder Get(string memberName, TypeDefinitionAst classScope, bool @static) 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) public static PSGetMemberBinder Get(string memberName, Type classScope, bool @static)
@ -5629,7 +5629,7 @@ namespace System.Management.Automation.Language
PSMemberInfo memberInfo = null; PSMemberInfo memberInfo = null;
ConsolidatedString typenames = null; ConsolidatedString typenames = null;
var context = LocalPipeline.GetExecutionContextFromTLS(); var context = LocalPipeline.GetExecutionContextFromTLS();
var typeTable = context != null ? context.TypeTable : null; var typeTable = context?.TypeTable;
if (hasTypeTableMember) if (hasTypeTableMember)
{ {
@ -5842,7 +5842,7 @@ namespace System.Management.Automation.Language
} }
} }
var adapterSet = PSObject.GetMappedAdapter(obj, context != null ? context.TypeTable : null); var adapterSet = PSObject.GetMappedAdapter(obj, context?.TypeTable);
if (memberInfo == null) if (memberInfo == null)
{ {
memberInfo = adapterSet.OriginalAdapter.BaseGetMember<PSMemberInfo>(obj, member); memberInfo = adapterSet.OriginalAdapter.BaseGetMember<PSMemberInfo>(obj, member);
@ -5881,7 +5881,7 @@ namespace System.Management.Automation.Language
internal static TypeTable GetTypeTableFromTLS() internal static TypeTable GetTypeTableFromTLS()
{ {
var executionContext = LocalPipeline.GetExecutionContextFromTLS(); var executionContext = LocalPipeline.GetExecutionContextFromTLS();
return executionContext != null ? executionContext.TypeTable : null; return executionContext?.TypeTable;
} }
internal static bool TryGetInstanceMember(object value, string memberName, out PSMemberInfo memberInfo) internal static bool TryGetInstanceMember(object value, string memberName, out PSMemberInfo memberInfo)
@ -5964,7 +5964,7 @@ namespace System.Management.Automation.Language
public static PSSetMemberBinder Get(string memberName, TypeDefinitionAst classScopeAst, bool @static) 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); return Get(memberName, classScope, @static);
} }
@ -6446,7 +6446,7 @@ namespace System.Management.Automation.Language
} }
} }
var adapterSet = PSObject.GetMappedAdapter(obj, context != null ? context.TypeTable : null); var adapterSet = PSObject.GetMappedAdapter(obj, context?.TypeTable);
if (memberInfo == null) if (memberInfo == null)
{ {
memberInfo = adapterSet.OriginalAdapter.BaseGetMember<PSMemberInfo>(obj, member); memberInfo = adapterSet.OriginalAdapter.BaseGetMember<PSMemberInfo>(obj, member);
@ -7401,7 +7401,7 @@ namespace System.Management.Automation.Language
internal static object InvokeAdaptedMember(object obj, string methodName, object[] args) internal static object InvokeAdaptedMember(object obj, string methodName, object[] args)
{ {
var context = LocalPipeline.GetExecutionContextFromTLS(); 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<PSMemberInfo>(obj, methodName) as PSMethodInfo; var methodInfo = adapterSet.OriginalAdapter.BaseGetMember<PSMemberInfo>(obj, methodName) as PSMethodInfo;
if (methodInfo == null && adapterSet.DotNetAdapter != null) if (methodInfo == null && adapterSet.DotNetAdapter != null)
{ {
@ -7446,7 +7446,7 @@ namespace System.Management.Automation.Language
internal static object InvokeAdaptedSetMember(object obj, string methodName, object[] args, object valueToSet) internal static object InvokeAdaptedSetMember(object obj, string methodName, object[] args, object valueToSet)
{ {
var context = LocalPipeline.GetExecutionContextFromTLS(); 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<PSParameterizedProperty>(obj, methodName); var methodInfo = adapterSet.OriginalAdapter.BaseGetMember<PSParameterizedProperty>(obj, methodName);
if (methodInfo == null && adapterSet.DotNetAdapter != null) if (methodInfo == null && adapterSet.DotNetAdapter != null)
{ {

View File

@ -284,7 +284,7 @@ namespace System.Management.Automation.Internal
{ {
var validateAttributes = type.GetProperty(propertyName).GetCustomAttributes<ValidateArgumentsAttribute>(); var validateAttributes = type.GetProperty(propertyName).GetCustomAttributes<ValidateArgumentsAttribute>();
var executionContext = LocalPipeline.GetExecutionContextFromTLS(); var executionContext = LocalPipeline.GetExecutionContextFromTLS();
var engineIntrinsics = executionContext == null ? null : executionContext.EngineIntrinsics; var engineIntrinsics = executionContext?.EngineIntrinsics;
foreach (var validateAttribute in validateAttributes) foreach (var validateAttribute in validateAttributes)
{ {
validateAttribute.InternalValidate(value, engineIntrinsics); validateAttribute.InternalValidate(value, engineIntrinsics);

View File

@ -449,7 +449,7 @@ namespace System.Management.Automation
for (int i = 0; i < pipeElements.Length; i++) for (int i = 0; i < pipeElements.Length; i++)
{ {
commandRedirection = commandRedirections != null ? commandRedirections[i] : null; commandRedirection = commandRedirections?[i];
commandProcessor = AddCommand(pipelineProcessor, pipeElements[i], pipeElementAsts[i], commandProcessor = AddCommand(pipelineProcessor, pipeElements[i], pipeElementAsts[i],
commandRedirection, context); commandRedirection, context);
} }

View File

@ -4652,7 +4652,7 @@ namespace System.Management.Automation
activityId = int.Parse(deserializer.ReadDecodedElementString(SerializationStrings.ProgressRecordActivityId), CultureInfo.InvariantCulture); activityId = int.Parse(deserializer.ReadDecodedElementString(SerializationStrings.ProgressRecordActivityId), CultureInfo.InvariantCulture);
object tmp = deserializer.ReadOneObject(); object tmp = deserializer.ReadOneObject();
currentOperation = (tmp == null) ? null : tmp.ToString(); currentOperation = tmp?.ToString();
parentActivityId = int.Parse(deserializer.ReadDecodedElementString(SerializationStrings.ProgressRecordParentActivityId), CultureInfo.InvariantCulture); parentActivityId = int.Parse(deserializer.ReadDecodedElementString(SerializationStrings.ProgressRecordParentActivityId), CultureInfo.InvariantCulture);
percentComplete = int.Parse(deserializer.ReadDecodedElementString(SerializationStrings.ProgressRecordPercentComplete), CultureInfo.InvariantCulture); percentComplete = int.Parse(deserializer.ReadDecodedElementString(SerializationStrings.ProgressRecordPercentComplete), CultureInfo.InvariantCulture);

View File

@ -348,7 +348,7 @@ namespace Microsoft.PowerShell.Commands
foreach (UpdatableHelpUri contentUri in newHelpInfo.HelpContentUriCollection) 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, string updateHelpShouldProcessAction = string.Format(CultureInfo.InvariantCulture,
HelpDisplayStrings.UpdateHelpShouldProcessActionMessage, HelpDisplayStrings.UpdateHelpShouldProcessActionMessage,
module.ModuleName, module.ModuleName,

View File

@ -285,9 +285,7 @@ namespace System.Management.Automation
{ {
get get
{ {
return (_providerInvocationException == null) return _providerInvocationException?.ProviderInfo;
? null
: _providerInvocationException.ProviderInfo;
} }
} }
@ -296,7 +294,7 @@ namespace System.Management.Automation
#region Internal #region Internal
private static Exception GetInnerException(Exception e) private static Exception GetInnerException(Exception e)
{ {
return (e == null) ? null : e.InnerException; return e?.InnerException;
} }
#endregion Internal #endregion Internal
} }