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
# IDE0031: UseNullPropagation
dotnet_diagnostic.IDE0031.severity = silent
dotnet_diagnostic.IDE0031.severity = warning
# IDE0032: UseAutoProperty
dotnet_diagnostic.IDE0032.severity = silent

View File

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

View File

@ -201,7 +201,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim
exception: exception,
errorId: errorId,
errorCategory: errorCategory,
targetObject: jobContext != null ? jobContext.TargetObject : null);
targetObject: jobContext?.TargetObject);
if (jobContext != null)
{
@ -242,7 +242,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim
if (cimException.ErrorData != null)
{
_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");
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))

View File

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

View File

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

View File

@ -774,7 +774,7 @@ namespace System.Management.Automation
return new PSControlGroupBy
{
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
{
return _convertTypes == null
? null
: _convertTypes.LastOrDefault();
return _convertTypes?.LastOrDefault();
}
}

View File

@ -4223,7 +4223,7 @@ namespace System.Management.Automation
if (error != null)
{
Type specifiedType = (argumentToBind.ArgumentValue == null) ? null : argumentToBind.ArgumentValue.GetType();
Type specifiedType = argumentToBind.ArgumentValue?.GetType();
ParameterBindingException bindingException =
new ParameterBindingException(
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.
var debugger = (powershell.Runspace != null) ? powershell.Runspace.Debugger : null;
var debugger = powershell.Runspace?.Debugger;
if ((debugger != null) && debugger.InBreakpoint)
{
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.
var debugger = (powershell.Runspace != null) ? powershell.Runspace.Debugger : null;
var debugger = powershell.Runspace?.Debugger;
if ((debugger != null) && debugger.InBreakpoint)
{
return CompleteInputInDebugger(ast, tokens, cursorPosition, options, debugger);

View File

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

View File

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

View File

@ -2457,7 +2457,7 @@ namespace System.Management.Automation
/// </param>
/// </summary>
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));

View File

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

View File

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

View File

@ -36,7 +36,7 @@ namespace System.Management.Automation
{
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 =

View File

@ -489,7 +489,7 @@ namespace System.Management.Automation
}
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)

View File

@ -1447,7 +1447,7 @@ namespace System.Management.Automation
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 @@ namespace System.Management.Automation
internal FunctionContext LastFunctionContext()
{
var last = Last();
return last != null ? last.FunctionContext : null;
return last?.FunctionContext;
}
internal bool Any()
@ -3677,7 +3677,7 @@ namespace System.Management.Automation
}
// Clean up nested debugger.
NestedRunspaceDebugger nestedDebugger = (runspaceInfo != null) ? runspaceInfo.NestedDebugger : null;
NestedRunspaceDebugger nestedDebugger = runspaceInfo?.NestedDebugger;
if (nestedDebugger != null)
{
nestedDebugger.DebuggerStop -= HandleMonitorRunningRSDebuggerStop;
@ -4447,7 +4447,7 @@ namespace System.Management.Automation
{
// Nested debugged runspace prompt should look like:
// [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 processPart = StringUtil.Format(processPartPattern,
@"""",

View File

@ -952,7 +952,7 @@ namespace System.Management.Automation.Runspaces
{
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 @@ namespace System.Management.Automation.Runspaces
get
{
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;
var executionContext = LocalPipeline.GetExecutionContextFromTLS();
object obj = (executionContext != null) ? executionContext.GetVariableValue(SpecialVariables.HistorySizeVarPath) : null;
object obj = executionContext?.GetVariableValue(SpecialVariables.HistorySizeVarPath);
if (obj != null)
{
try

View File

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

View File

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

View File

@ -378,8 +378,8 @@ namespace System.Management.Automation
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))
{

View File

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

View File

@ -1166,7 +1166,7 @@ namespace System.Management.Automation.Language
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)
@ -6311,7 +6311,7 @@ namespace System.Management.Automation.Language
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)
@ -6330,7 +6330,7 @@ namespace System.Management.Automation.Language
return CombineTypeConstraintForMethodResolution(
targetTypeConstraint,
arguments != null ? arguments.Select(Compiler.GetTypeConstraintForMethodResolution).ToArray() : null);
arguments?.Select(Compiler.GetTypeConstraintForMethodResolution).ToArray());
}
internal Expression InvokeMember(
@ -6343,7 +6343,7 @@ namespace System.Management.Automation.Language
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);

View File

@ -1666,7 +1666,7 @@ namespace System.Management.Automation.Language
statements.Add(predefinedStatementAst);
}
IScriptExtent statementListExtent = paramBlockAst != null ? paramBlockAst.Extent : null;
IScriptExtent statementListExtent = paramBlockAst?.Extent;
IScriptExtent scriptBlockExtent;
while (true)
@ -1707,7 +1707,7 @@ namespace System.Management.Automation.Language
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;
@ -2042,7 +2042,7 @@ namespace System.Management.Automation.Language
statement = BlockStatementRule(token);
break;
case TokenKind.Configuration:
statement = ConfigurationStatementRule(attributes != null ? attributes.OfType<AttributeAst>() : null, token);
statement = ConfigurationStatementRule(attributes?.OfType<AttributeAst>(), token);
break;
case TokenKind.From:
case TokenKind.Define:
@ -2848,7 +2848,7 @@ namespace System.Management.Automation.Language
}
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)
@ -3439,7 +3439,7 @@ namespace System.Management.Automation.Language
}
return new ForEachStatementAst(ExtentOf(startOfStatement, body),
labelToken != null ? labelToken.LabelText : null,
labelToken?.LabelText,
flags,
throttleLimit, variableAst, pipeline, body);
}
@ -3552,7 +3552,7 @@ namespace System.Management.Automation.Language
}
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)
@ -3634,7 +3634,7 @@ namespace System.Management.Automation.Language
}
return new WhileStatementAst(ExtentOf(labelToken ?? whileToken, body),
labelToken != null ? labelToken.LabelText : null, condition, body);
labelToken?.LabelText, condition, body);
}
/// <summary>
@ -4129,7 +4129,7 @@ namespace System.Management.Automation.Language
}
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);
@ -4283,7 +4283,7 @@ namespace System.Management.Automation.Language
? customAttributes[0].Extent
: classToken.Extent;
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 (nestedAsts == null)
@ -4744,7 +4744,7 @@ namespace System.Management.Automation.Language
? customAttributes[0].Extent
: enumToken.Extent;
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())
{
// 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;
SkipNewlines();
var dataVariableNameAst = SimpleNameRule();
string dataVariableName = (dataVariableNameAst != null) ? dataVariableNameAst.Value : null;
string dataVariableName = dataVariableNameAst?.Value;
SkipNewlines();
Token supportedCommandToken = PeekToken();
@ -6629,7 +6629,7 @@ namespace System.Management.Automation.Language
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

View File

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

View File

@ -246,7 +246,7 @@ namespace System.Management.Automation.Language
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)

View File

@ -2656,7 +2656,7 @@ namespace System.Management.Automation.Language
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 @@ namespace System.Management.Automation.Language
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 @@ namespace System.Management.Automation.Language
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 @@ namespace System.Management.Automation.Language
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 @@ namespace System.Management.Automation.Language
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,
@ -5879,7 +5879,7 @@ namespace System.Management.Automation.Language
public string GetCommandName()
{
var name = CommandElements[0] as StringConstantExpressionAst;
return name != null ? name.Value : null;
return name?.Value;
}
/// <summary>
@ -6422,7 +6422,7 @@ namespace System.Management.Automation.Language
{
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 @@ namespace System.Management.Automation.Language
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 @@ namespace System.Management.Automation.Language
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 @@ namespace System.Management.Automation.Language
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 @@ namespace System.Management.Automation.Language
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)
@ -8103,7 +8103,7 @@ namespace System.Management.Automation.Language
internal override object Accept(ICustomAstVisitor visitor)
{
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
// 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;

View File

@ -1412,7 +1412,7 @@ namespace System.Management.Automation.Internal
// 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");

View File

@ -1939,7 +1939,7 @@ namespace System.Management.Automation
if (re.ErrorRecord.CategoryInfo.Reason == nameof(IncompleteParseException))
{
throw new IncompleteParseException(
(re.ErrorRecord.Exception != null) ? re.ErrorRecord.Exception.Message : null,
re.ErrorRecord.Exception?.Message,
re.ErrorRecord.FullyQualifiedErrorId);
}
@ -2660,7 +2660,7 @@ namespace System.Management.Automation
// 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))

View File

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

View File

@ -2395,7 +2395,7 @@ namespace System.Management.Automation.Remoting
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))

View File

@ -334,7 +334,7 @@ namespace System.Management.Automation.Remoting
// 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)
{

View File

@ -1202,7 +1202,7 @@ namespace System.Management.Automation.Language
{
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 @@ namespace System.Management.Automation.Language
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 @@ namespace System.Management.Automation.Language
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 @@ namespace System.Management.Automation.Language
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 @@ namespace System.Management.Automation.Language
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 @@ 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)
{
memberInfo = adapterSet.OriginalAdapter.BaseGetMember<PSMemberInfo>(obj, member);
@ -5881,7 +5881,7 @@ namespace System.Management.Automation.Language
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 @@ namespace System.Management.Automation.Language
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 @@ 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)
{
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)
{
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;
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)
{
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);
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 executionContext = LocalPipeline.GetExecutionContextFromTLS();
var engineIntrinsics = executionContext == null ? null : executionContext.EngineIntrinsics;
var engineIntrinsics = executionContext?.EngineIntrinsics;
foreach (var validateAttribute in validateAttributes)
{
validateAttribute.InternalValidate(value, engineIntrinsics);

View File

@ -449,7 +449,7 @@ namespace System.Management.Automation
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);
}

View File

@ -4652,7 +4652,7 @@ namespace System.Management.Automation
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);

View File

@ -348,7 +348,7 @@ namespace Microsoft.PowerShell.Commands
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,

View File

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