From 2636dadf00b2f86130baec6474fe764eb06552ac Mon Sep 17 00:00:00 2001 From: xtqqczze Date: Fri, 12 Jun 2020 07:13:17 +0100 Subject: [PATCH 1/4] RCS1080: Use 'Count/Length' property instead of 'Any' method --- .../engine/AutomationEngine.cs | 2 +- .../engine/CommandCompletion/CompletionAnalysis.cs | 6 +++--- .../CommandCompletion/CompletionCompleters.cs | 6 +++--- .../engine/CoreAdapter.cs | 4 ++-- .../engine/GetCommandCommand.cs | 2 +- .../engine/LanguagePrimitives.cs | 4 ++-- .../engine/Modules/RemoteDiscoveryHelper.cs | 4 ++-- .../engine/SessionStateScope.cs | 2 +- .../engine/debugger/debugger.cs | 12 ++++++------ .../engine/parser/Compiler.cs | 2 +- .../engine/parser/PSType.cs | 8 ++++---- .../engine/parser/Parser.cs | 10 +++++----- .../engine/parser/SemanticChecks.cs | 2 +- .../engine/parser/TypeInferenceVisitor.cs | 2 +- .../engine/parser/VariableAnalysis.cs | 4 ++-- .../engine/parser/ast.cs | 12 ++++++------ .../engine/runtime/Binding/Binders.cs | 14 +++++++------- .../engine/runtime/CompiledScriptBlock.cs | 6 +++--- 18 files changed, 51 insertions(+), 51 deletions(-) diff --git a/src/System.Management.Automation/engine/AutomationEngine.cs b/src/System.Management.Automation/engine/AutomationEngine.cs index 1254e4027e1..38d985c7634 100644 --- a/src/System.Management.Automation/engine/AutomationEngine.cs +++ b/src/System.Management.Automation/engine/AutomationEngine.cs @@ -96,7 +96,7 @@ internal ScriptBlock ParseScriptBlock(string script, string fileName, bool addTo EngineParser.SetPreviousFirstLastToken(Context); } - if (errors.Any()) + if (errors.Length > 0) { if (errors[0].IncompleteInput) { diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs index 1a5f0989b8f..8ca65f501d5 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs @@ -1954,7 +1954,7 @@ private List GetResultForIdentifier(CompletionContext completi // If the last token was just a '.', we tried to complete members. That may // have failed because it wasn't really an attempt to complete a member, in // which case we should try to complete as an argument. - if (result.Any()) + if (result.Count > 0) { if (!isWildcard && memberOperator != TokenKind.Unknown) { @@ -1969,7 +1969,7 @@ private List GetResultForIdentifier(CompletionContext completi if (lastAst.Parent is HashtableAst) { result = CompletionCompleters.CompleteHashtableKey(completionContext, (HashtableAst)lastAst.Parent); - if (result != null && result.Any()) + if (result != null && result.Count > 0) { return result; } @@ -1992,7 +1992,7 @@ private List GetResultForIdentifier(CompletionContext completi else if (tokenAtCursorText.IndexOfAny(Utils.Separators.Directory) == 0) { var command = lastAst.Parent as CommandBaseAst; - if (command != null && command.Redirections.Any()) + if (command != null && command.Redirections.Count > 0) { var fileRedirection = command.Redirections[0] as FileRedirectionAst; if (fileRedirection != null && diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index e00302a1eb4..99ace506cbe 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -1603,7 +1603,7 @@ private static void CompletePositionalArgument( if (parameterSetData.ParameterSetFlag == defaultParameterSetFlag) { ProcessParameter(commandName, commandAst, context, result, param, boundArguments); - isProcessedAsPositional = result.Any(); + isProcessedAsPositional = result.Count > 0; break; } else @@ -2458,7 +2458,7 @@ private static bool InvokeScriptArgumentCompleter( { } - if (customResults == null || !customResults.Any()) + if (customResults == null || customResults.Count == 0) { return false; } @@ -5409,7 +5409,7 @@ private static bool IsMemberHidden(object member) var memberInfo = member as MemberInfo; if (memberInfo != null) - return memberInfo.GetCustomAttributes(typeof(HiddenAttribute), false).Any(); + return memberInfo.GetCustomAttributes(typeof(HiddenAttribute), false).Length > 0; var propertyMemberAst = member as PropertyMemberAst; if (propertyMemberAst != null) diff --git a/src/System.Management.Automation/engine/CoreAdapter.cs b/src/System.Management.Automation/engine/CoreAdapter.cs index 2fd5e1868c5..b6752387d58 100644 --- a/src/System.Management.Automation/engine/CoreAdapter.cs +++ b/src/System.Management.Automation/engine/CoreAdapter.cs @@ -2143,7 +2143,7 @@ internal MethodInformation(MethodBase method, int parametersToIgnore) // This inconsistent behavior affects OneCore powershell because we are using the extension method here when compiling // against CoreCLR. So we need to add a null check until this is fixed in CLR. var paramArrayAttrs = lastParameter.GetCustomAttributes(typeof(ParamArrayAttribute), false); - if (paramArrayAttrs != null && paramArrayAttrs.Any()) + if (paramArrayAttrs != null && paramArrayAttrs.Length > 0) { this.hasVarArgs = true; this.parameters[parametersLength - 1].isParamArray = true; @@ -4473,7 +4473,7 @@ internal static string GetMethodInfoOverloadDefinition(string memberName, Method // This inconsistent behavior affects OneCore powershell because we are using the extension method here when compiling // against CoreCLR. So we need to add a null check until this is fixed in CLR. var paramArrayAttrs = parameter.GetCustomAttributes(typeof(ParamArrayAttribute), false); - if (paramArrayAttrs != null && paramArrayAttrs.Any()) + if (paramArrayAttrs != null && paramArrayAttrs.Length > 0) builder.Append("Params "); } diff --git a/src/System.Management.Automation/engine/GetCommandCommand.cs b/src/System.Management.Automation/engine/GetCommandCommand.cs index eef50f29a24..8b2f6d21667 100644 --- a/src/System.Management.Automation/engine/GetCommandCommand.cs +++ b/src/System.Management.Automation/engine/GetCommandCommand.cs @@ -716,7 +716,7 @@ private bool IsNounVerbMatch(CommandInfo command) } else { - if (_modulePatterns.Count > 0 || _moduleSpecifications.Any()) + if (_modulePatterns.Count > 0 || _moduleSpecifications.Length > 0) { // Its not a match if we are filtering on a PSSnapin/Module name but the cmdlet doesn't have one. break; diff --git a/src/System.Management.Automation/engine/LanguagePrimitives.cs b/src/System.Management.Automation/engine/LanguagePrimitives.cs index d1ebac8c2ce..63ea00970c8 100644 --- a/src/System.Management.Automation/engine/LanguagePrimitives.cs +++ b/src/System.Management.Automation/engine/LanguagePrimitives.cs @@ -1973,7 +1973,7 @@ private static EnumHashEntry GetEnumHashEntry(Type enumType) // See if the [Flag] attribute is set on this type... // MemberInfo.GetCustomAttributes returns IEnumerable in CoreCLR. - bool hasFlagsAttribute = enumType.GetCustomAttributes(typeof(FlagsAttribute), false).Any(); + bool hasFlagsAttribute = enumType.GetCustomAttributes(typeof(FlagsAttribute), false).Length > 0; returnValue = new EnumHashEntry(Enum.GetNames(enumType), values, allValues, hasNegativeValue, hasFlagsAttribute); s_enumTable.Add(enumType, returnValue); @@ -5522,7 +5522,7 @@ private static bool TypeConverterPossiblyExists(Type type) // GetCustomAttributes returns IEnumerable in CoreCLR var typeConverters = type.GetCustomAttributes(typeof(TypeConverterAttribute), false); - if (typeConverters.Any()) + if (typeConverters.Length > 0) { return true; } diff --git a/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs b/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs index 4a1c50186eb..015b2bb72d2 100644 --- a/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs +++ b/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs @@ -82,7 +82,7 @@ internal static PSModuleInfo RehydratePSModuleInfo(PSObject deserializedModuleIn moduleInfo.DeclaredVariableExports = RehydrateHashtableKeys(deserializedModuleInfo, "ExportedVariables"); var compatiblePSEditions = DeserializingTypeConverter.GetPropertyValue(deserializedModuleInfo, "CompatiblePSEditions", rehydrationFlags); - if (compatiblePSEditions != null && compatiblePSEditions.Any()) + if (compatiblePSEditions != null && compatiblePSEditions.Length > 0) { foreach (var edition in compatiblePSEditions) { @@ -92,7 +92,7 @@ internal static PSModuleInfo RehydratePSModuleInfo(PSObject deserializedModuleIn // PowerShellGet related properties var tags = DeserializingTypeConverter.GetPropertyValue(deserializedModuleInfo, "Tags", rehydrationFlags); - if (tags != null && tags.Any()) + if (tags != null && tags.Length > 0) { foreach (var tag in tags) { diff --git a/src/System.Management.Automation/engine/SessionStateScope.cs b/src/System.Management.Automation/engine/SessionStateScope.cs index 434d1e0d929..ecae52770bb 100644 --- a/src/System.Management.Automation/engine/SessionStateScope.cs +++ b/src/System.Management.Automation/engine/SessionStateScope.cs @@ -440,7 +440,7 @@ internal PSVariable SetVariable(string name, object value, bool asValue, bool fo } if (variable is LocalVariable - && (variableToSet.Attributes.Any() || variableToSet.Options != variable.Options)) + && (variableToSet.Attributes.Count > 0 || variableToSet.Options != variable.Options)) { SessionStateUnauthorizedAccessException e = new SessionStateUnauthorizedAccessException( diff --git a/src/System.Management.Automation/engine/debugger/debugger.cs b/src/System.Management.Automation/engine/debugger/debugger.cs index 6355b0d83e5..b8683ad5e2c 100644 --- a/src/System.Management.Automation/engine/debugger/debugger.cs +++ b/src/System.Management.Automation/engine/debugger/debugger.cs @@ -1402,10 +1402,10 @@ internal bool CheckCommand(InvocationInfo invocationInfo) _commandBreakpoints.Values.Where(bp => bp.Enabled && bp.Trigger(invocationInfo)).ToList(); bool checkLineBp = true; - if (breakpoints.Any()) + if (breakpoints.Count > 0) { breakpoints = TriggerBreakpoints(breakpoints); - if (breakpoints.Any()) + if (breakpoints.Count > 0) { var breakInvocationInfo = functionContext != null @@ -1422,7 +1422,7 @@ internal bool CheckCommand(InvocationInfo invocationInfo) internal void CheckVariableRead(string variableName) { var breakpointsToTrigger = GetVariableBreakpointsToTrigger(variableName, read: true); - if (breakpointsToTrigger != null && breakpointsToTrigger.Any()) + if (breakpointsToTrigger != null && breakpointsToTrigger.Count > 0) { TriggerVariableBreakpoints(breakpointsToTrigger); } @@ -1431,7 +1431,7 @@ internal void CheckVariableRead(string variableName) internal void CheckVariableWrite(string variableName) { var breakpointsToTrigger = GetVariableBreakpointsToTrigger(variableName, read: false); - if (breakpointsToTrigger != null && breakpointsToTrigger.Any()) + if (breakpointsToTrigger != null && breakpointsToTrigger.Count > 0) { TriggerVariableBreakpoints(breakpointsToTrigger); } @@ -1580,7 +1580,7 @@ internal void OnSequencePointHit(FunctionContext functionContext) select breakpoint).ToList(); breakpoints = TriggerBreakpoints(breakpoints); - if (breakpoints.Any()) + if (breakpoints.Count > 0) { StopOnSequencePoint(functionContext, breakpoints); } @@ -2020,7 +2020,7 @@ private void UnbindBoundBreakpoints(List boundBreakpoints) private void SetPendingBreakpoints(FunctionContext functionContext) { - if (!_pendingBreakpoints.Any()) + if (_pendingBreakpoints.Count == 0) return; var newPendingBreakpoints = new Dictionary(); diff --git a/src/System.Management.Automation/engine/parser/Compiler.cs b/src/System.Management.Automation/engine/parser/Compiler.cs index d25aad0485d..e77097f2088 100644 --- a/src/System.Management.Automation/engine/parser/Compiler.cs +++ b/src/System.Management.Automation/engine/parser/Compiler.cs @@ -2591,7 +2591,7 @@ private void GenerateTypesAndUsings(ScriptBlockAst rootForDefiningTypesAndUsings // If Parent of rootForDefiningTypesAndUsings is not null, then we already defined all types, when Visit a parent ScriptBlock if (rootForDefiningTypesAndUsings.Parent == null) { - if (rootForDefiningTypesAndUsings.UsingStatements.Any()) + if (rootForDefiningTypesAndUsings.UsingStatements.Count > 0) { bool allUsingsAreNamespaces = rootForDefiningTypesAndUsings.UsingStatements.All(us => us.UsingStatementKind == UsingStatementKind.Namespace); GenerateLoadUsings(rootForDefiningTypesAndUsings.UsingStatements, allUsingsAreNamespaces, exprs); diff --git a/src/System.Management.Automation/engine/parser/PSType.cs b/src/System.Management.Automation/engine/parser/PSType.cs index 7ffaab3ff0a..0619f09a17b 100644 --- a/src/System.Management.Automation/engine/parser/PSType.cs +++ b/src/System.Management.Automation/engine/parser/PSType.cs @@ -110,7 +110,7 @@ private static CustomAttributeBuilder GetAttributeBuilder(Parser parser, Attribu // This inconsistent behavior affects OneCore powershell because we are using the extension method here when compiling // against CoreCLR. So we need to add a null check until this is fixed in CLR. var paramArrayAttrs = parameterInfo[argIndex].GetCustomAttributes(typeof(ParamArrayAttribute), true); - if (paramArrayAttrs != null && paramArrayAttrs.Any() && expandParamsOnBest) + if (paramArrayAttrs != null && paramArrayAttrs.Length > 0 && expandParamsOnBest) { var elementType = parameterInfo[argIndex].ParameterType.GetElementType(); var paramsArray = Array.CreateInstance(elementType, positionalArgCount - argIndex); @@ -323,7 +323,7 @@ private Type GetBaseTypes(Parser parser, TypeDefinitionAst typeDefinitionAst, ou // Default base class is System.Object and it has a default ctor. _baseClassHasDefaultCtor = true; - if (typeDefinitionAst.BaseTypes.Any()) + if (typeDefinitionAst.BaseTypes.Count > 0) { // base class var baseTypeAsts = typeDefinitionAst.BaseTypes; @@ -550,7 +550,7 @@ public void DefineMembers() if (needDefaultCtor) { - needDefaultCtor = !instanceCtors.Any(); + needDefaultCtor = instanceCtors.Count == 0; } //// Now we can decide to create explicit default ctors or report error. @@ -571,7 +571,7 @@ public void DefineMembers() } else { - if (!instanceCtors.Any()) + if (instanceCtors.Count == 0) { _parser.ReportError(_typeDefinitionAst.Extent, nameof(ParserStrings.BaseClassNoDefaultCtor), diff --git a/src/System.Management.Automation/engine/parser/Parser.cs b/src/System.Management.Automation/engine/parser/Parser.cs index cb0ace0029a..696a6802dd7 100644 --- a/src/System.Management.Automation/engine/parser/Parser.cs +++ b/src/System.Management.Automation/engine/parser/Parser.cs @@ -880,7 +880,7 @@ private ParamBlockAst ParamBlockRule() UngetToken(rParen); endExtent = Before(rParen); - ReportIncompleteInput(After(parameters != null && parameters.Any() ? parameters.Last().Extent : lparen.Extent), + ReportIncompleteInput(After(parameters != null && parameters.Count > 0 ? parameters.Last().Extent : lparen.Extent), nameof(ParserStrings.MissingEndParenthesisInFunctionParameterList), ParserStrings.MissingEndParenthesisInFunctionParameterList); } @@ -5369,7 +5369,7 @@ private List FunctionParameterDeclarationRule(out IScriptExtent en // ErrorRecovery: assume a body follows, so just keep parsing. UngetToken(rParen); - endErrorStatement = parameters.Any() ? parameters.Last().Extent : lParen.Extent; + endErrorStatement = parameters.Count > 0 ? parameters.Last().Extent : lParen.Extent; ReportIncompleteInput(After(endErrorStatement), nameof(ParserStrings.MissingEndParenthesisInFunctionParameterList), ParserStrings.MissingEndParenthesisInFunctionParameterList); @@ -7577,7 +7577,7 @@ private List ParseNestedExpressions(StringExpandableToken expanda List newNestedTokens = _savingTokens ? new List() : null; foreach (var token in expandableStringToken.NestedTokens) { - Diagnostics.Assert(!token.HasError || ErrorList.Any(), "No nested tokens should have unreported errors."); + Diagnostics.Assert(!token.HasError || ErrorList.Count > 0, "No nested tokens should have unreported errors."); ExpressionAst exprAst; var varToken = token as VariableToken; @@ -7807,7 +7807,7 @@ private List InvokeParamParenListRule(Token lParen, out IScriptEx UngetToken(rParen); if (!reportedError) { - ReportIncompleteInput(arguments.Any() ? After(arguments.Last()) : After(lParen), + ReportIncompleteInput(arguments.Count > 0 ? After(arguments.Last()) : After(lParen), nameof(ParserStrings.MissingEndParenthesisInMethodCall), ParserStrings.MissingEndParenthesisInMethodCall); } @@ -7893,7 +7893,7 @@ private void SaveError(IScriptExtent extent, string errorId, string errorMsg, bo { AssertErrorIdCorrespondsToMsgString(errorId, errorMsg); - if (args != null && args.Any()) + if (args != null && args.Length > 0) { errorMsg = string.Format(CultureInfo.CurrentCulture, errorMsg, args); } diff --git a/src/System.Management.Automation/engine/parser/SemanticChecks.cs b/src/System.Management.Automation/engine/parser/SemanticChecks.cs index b7d3bdb8bc8..f681a30d070 100644 --- a/src/System.Management.Automation/engine/parser/SemanticChecks.cs +++ b/src/System.Management.Automation/engine/parser/SemanticChecks.cs @@ -1811,7 +1811,7 @@ internal static void CheckDataStatementAstAtRuntime(DataStatementAst dataStateme var parser = new Parser(); var rlc = new RestrictedLanguageChecker(parser, allowedCommands, null, false); dataStatementAst.Body.InternalVisit(rlc); - if (parser.ErrorList.Any()) + if (parser.ErrorList.Count > 0) { throw new ParseException(parser.ErrorList.ToArray()); } diff --git a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs index f49c1fe5cd3..5cdfc103f57 100644 --- a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs +++ b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs @@ -1231,7 +1231,7 @@ bool IsInPropertyArgument(object o) } var memberNameAndTypes = GetMemberNameAndTypeFromProperties(prevType, IsInPropertyArgument); - if (!memberNameAndTypes.Any()) + if (memberNameAndTypes.Count == 0) { continue; } diff --git a/src/System.Management.Automation/engine/parser/VariableAnalysis.cs b/src/System.Management.Automation/engine/parser/VariableAnalysis.cs index 8b0ab3249df..1abe8bb6603 100644 --- a/src/System.Management.Automation/engine/parser/VariableAnalysis.cs +++ b/src/System.Management.Automation/engine/parser/VariableAnalysis.cs @@ -1416,7 +1416,7 @@ private void BreakOrContinue(ExpressionAst label, Func f if (label != null) { label.Accept(this); - if (_loopTargets.Any()) + if (_loopTargets.Count > 0) { var labelStrAst = label as StringConstantExpressionAst; if (labelStrAst != null) @@ -1600,7 +1600,7 @@ public object VisitPipeline(PipelineAst pipelineAst) // break or continue, so add the appropriate edges to our graph. These edges occur after visiting // the command elements because command arguments could create new blocks, and we won't have executed // the command yet. - if (invokesCommand && _loopTargets.Any()) + if (invokesCommand && _loopTargets.Count > 0) { foreach (var loopTarget in _loopTargets) { diff --git a/src/System.Management.Automation/engine/parser/ast.cs b/src/System.Management.Automation/engine/parser/ast.cs index 79d74b9edef..0aaa68bee94 100644 --- a/src/System.Management.Automation/engine/parser/ast.cs +++ b/src/System.Management.Automation/engine/parser/ast.cs @@ -1138,7 +1138,7 @@ public ScriptBlock GetScriptBlock() // It's ok to report an error from a different part of AST in this case. var root = GetRootScriptBlockAst(); root.PerformPostParseChecks(parser); - if (parser.ErrorList.Any()) + if (parser.ErrorList.Count > 0) { throw new ParseException(parser.ErrorList.ToArray()); } @@ -1573,7 +1573,7 @@ internal PipelineAst GetSimplePipeline(bool allowMultiplePipelines, out string e return null; } - if (EndBlock.Traps != null && EndBlock.Traps.Any()) + if (EndBlock.Traps != null && EndBlock.Traps.Count > 0) { errorId = "CantConvertScriptBlockWithTrap"; errorMsg = AutomationExceptions.CantConvertScriptBlockWithTrap; @@ -1781,7 +1781,7 @@ public NamedBlockAst(IScriptExtent extent, TokenKind blockName, StatementBlockAs SetParents(statements); var traps = statementBlock.Traps; - if (traps != null && traps.Any()) + if (traps != null && traps.Count > 0) { this.Traps = traps; for (int index = 0; index < traps.Count; index++) @@ -5609,7 +5609,7 @@ public override ExpressionAst GetPureExpression() } CommandExpressionAst expr = PipelineElements[0] as CommandExpressionAst; - if (expr != null && !expr.Redirections.Any()) + if (expr != null && expr.Redirections.Count == 0) { return expr.Expression; } @@ -8282,7 +8282,7 @@ internal bool HasDefaultCtor() if (function.IsConstructor) { // TODO: add check for default values, once default values for parameters supported - if (!function.Parameters.Any()) + if (function.Parameters.Count == 0) { return true; } @@ -9760,7 +9760,7 @@ public class ArrayLiteralAst : ExpressionAst, ISupportsAssignment public ArrayLiteralAst(IScriptExtent extent, IList elements) : base(extent) { - if (elements == null || !elements.Any()) + if (elements == null || elements.Count == 0) { throw PSTraceSource.NewArgumentException(nameof(elements)); } diff --git a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs index cc5dcad1805..a7ace47929d 100644 --- a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs +++ b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs @@ -1683,7 +1683,7 @@ public override DynamicMetaObject FallbackCreateInstance(DynamicMetaObject targe // This inconsistent behavior affects OneCore powershell because we are using the extension method here when compiling // against CoreCLR. So we need to add a null check until this is fixed in CLR. var paramArrayAttrs = parameterInfo[argIndex].GetCustomAttributes(typeof(ParamArrayAttribute), true); - if (paramArrayAttrs != null && paramArrayAttrs.Any() && expandParamsOnBest) + if (paramArrayAttrs != null && paramArrayAttrs.Length > 0 && expandParamsOnBest) { var elementType = parameterInfo[argIndex].ParameterType.GetElementType(); var paramsArray = new List(); @@ -1714,7 +1714,7 @@ public override DynamicMetaObject FallbackCreateInstance(DynamicMetaObject targe } Expression result = Expression.New(constructorInfo, ctorArgs); - if (CallInfo.ArgumentNames.Any()) + if (CallInfo.ArgumentNames.Count > 0) { var tmp = Expression.Parameter(result.Type); var blockExprs = new List(); @@ -2036,7 +2036,7 @@ internal static bool IsValueTypeMutable(Type type) } // If there are any fields, the type is mutable. - if (type.GetFields(BindingFlags.Public | BindingFlags.Instance).Any()) + if (type.GetFields(BindingFlags.Public | BindingFlags.Instance).Length > 0) { return true; } @@ -5102,7 +5102,7 @@ private static PSGetMemberBinder Get(string memberName, Type classScope, bool @s var binderList = s_binderCacheIgnoringCase.GetOrAdd(memberName, _ => new List()); lock (binderList) { - if (binderList.Any()) + if (binderList.Count > 0) { result._hasInstanceMember = binderList[0]._hasInstanceMember; result._hasTypeTableMember = binderList[0]._hasTypeTableMember; @@ -7084,7 +7084,7 @@ internal static Expression InvokeMethod(MethodBase mi, DynamicMetaObject target, // This inconsistent behavior affects OneCore powershell because we are using the extension method here when compiling // against CoreCLR. So we need to add a null check until this is fixed in CLR. var paramArrayAttrs = parameters[i].GetCustomAttributes(typeof(ParamArrayAttribute), false); - if (paramArrayAttrs != null && paramArrayAttrs.Any()) + if (paramArrayAttrs != null && paramArrayAttrs.Length > 0) { Diagnostics.Assert(i == parameters.Length - 1, "vararg parameter is not the last"); var paramElementType = parameterType.GetElementType(); @@ -7204,9 +7204,9 @@ internal static Expression InvokeMethod(MethodBase mi, DynamicMetaObject target, } } - if (temps.Any()) + if (temps.Count > 0) { - if (call.Type != typeof(void) && copyOutTemps.Any()) + if (call.Type != typeof(void) && copyOutTemps.Count > 0) { var retValue = Expression.Variable(call.Type); temps.Add(retValue); diff --git a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs index 76a8d8a1081..417fcd15b96 100644 --- a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs +++ b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs @@ -748,7 +748,7 @@ private PipelineAst GetSimplePipeline(Func errorHandler) var ast = AstInternal; var statements = ast.Body.EndBlock.Statements; - if (!statements.Any()) + if (statements.Count == 0) { return errorHandler(AutomationExceptions.CantConvertEmptyPipeline); } @@ -758,7 +758,7 @@ private PipelineAst GetSimplePipeline(Func errorHandler) return errorHandler(AutomationExceptions.CanOnlyConvertOnePipeline); } - if (ast.Body.EndBlock.Traps != null && ast.Body.EndBlock.Traps.Any()) + if (ast.Body.EndBlock.Traps != null && ast.Body.EndBlock.Traps.Count > 0) { return errorHandler(AutomationExceptions.CantConvertScriptBlockWithTrap); } @@ -904,7 +904,7 @@ public void CheckRestrictedLanguage( AstVisitAction.Continue); } - if (parser.ErrorList.Any()) + if (parser.ErrorList.Count > 0) { throw new ParseException(parser.ErrorList.ToArray()); } From e15ba48867e4315a91325a6a94e074988d8756ec Mon Sep 17 00:00:00 2001 From: xtqqczze Date: Fri, 12 Jun 2020 07:28:12 +0100 Subject: [PATCH 2/4] RCS1077: Optimize LINQ method call --- .../cimSupport/cmdletization/cim/clientSideQuery.cs | 2 +- src/System.Management.Automation/DscSupport/CimDSCParser.cs | 2 +- .../engine/CommandCompletion/CompletionCompleters.cs | 2 +- src/System.Management.Automation/engine/CommandDiscovery.cs | 2 +- .../engine/CompiledCommandParameter.cs | 2 +- .../engine/GetCommandCommand.cs | 4 ++-- .../engine/Modules/NewModuleManifestCommand.cs | 2 +- .../engine/SessionStateScope.cs | 2 +- .../engine/debugger/debugger.cs | 2 +- .../engine/interpreter/LightCompiler.cs | 2 +- src/System.Management.Automation/engine/lang/scriptblock.cs | 6 +++--- .../engine/parser/AstVisitor.cs | 2 +- src/System.Management.Automation/engine/parser/PSType.cs | 6 +++--- src/System.Management.Automation/engine/parser/Parser.cs | 2 +- .../engine/parser/VariableAnalysis.cs | 2 +- src/System.Management.Automation/engine/parser/ast.cs | 4 ++-- .../engine/remoting/commands/WaitJob.cs | 2 +- .../engine/runtime/CompiledScriptBlock.cs | 4 ++-- .../namespaces/FileSystemProvider.cs | 2 +- 19 files changed, 26 insertions(+), 26 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs index 6b454ad8b7e..001b311e82a 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs @@ -223,7 +223,7 @@ public override bool ShouldReportErrorOnNoMatches_IfMultipleFilters() case BehaviorOnNoMatch.Default: default: return this.PropertyValueFilters - .Where(f => !f.HadMatch).Any(f => f.BehaviorOnNoMatch == BehaviorOnNoMatch.ReportErrors); + .Any(f => !f.HadMatch && f.BehaviorOnNoMatch == BehaviorOnNoMatch.ReportErrors); } } diff --git a/src/System.Management.Automation/DscSupport/CimDSCParser.cs b/src/System.Management.Automation/DscSupport/CimDSCParser.cs index be547213afa..27b4e93bcc5 100644 --- a/src/System.Management.Automation/DscSupport/CimDSCParser.cs +++ b/src/System.Management.Automation/DscSupport/CimDSCParser.cs @@ -1153,7 +1153,7 @@ public static List GetFileDefiningClass(string className) { var file = pair.Key; var classList = pair.Value; - if (classList != null && classList.FirstOrDefault((CimClass c) => string.Equals(c.CimSystemProperties.ClassName, className, StringComparison.OrdinalIgnoreCase)) != null) + if (classList != null && classList.Find((CimClass c) => string.Equals(c.CimSystemProperties.ClassName, className, StringComparison.OrdinalIgnoreCase)) != null) { files.Add(file); } diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index 99ace506cbe..b6c7d88a111 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -120,7 +120,7 @@ private static List CompleteCommand(CompletionContext context, foreach (var defn in findFunctionsVisitor.FunctionDefinitions) { if (commandNamePattern.IsMatch(defn.Name) - && !commandResults.Where(cr => cr.CompletionText.Equals(defn.Name, StringComparison.OrdinalIgnoreCase)).Any()) + && !commandResults.Any(cr => cr.CompletionText.Equals(defn.Name, StringComparison.OrdinalIgnoreCase))) { // Results found in the current script are prepended to show up at the top of the list. commandResults.Insert(0, GetCommandNameCompletionResult(defn.Name, defn, addAmpersandIfNecessary, quote)); diff --git a/src/System.Management.Automation/engine/CommandDiscovery.cs b/src/System.Management.Automation/engine/CommandDiscovery.cs index 4737fe18d78..ef9cb56c636 100644 --- a/src/System.Management.Automation/engine/CommandDiscovery.cs +++ b/src/System.Management.Automation/engine/CommandDiscovery.cs @@ -375,7 +375,7 @@ private static void VerifyRequiredSnapins(IEnumerable req { IEnumerable loadedPSSnapIns = null; loadedPSSnapIns = context.InitialSessionState.GetPSSnapIn(requiresPSSnapIn.Name); - if (loadedPSSnapIns == null || loadedPSSnapIns.Count() == 0) + if (loadedPSSnapIns == null || !loadedPSSnapIns.Any()) { if (requiresMissingPSSnapIns == null) { diff --git a/src/System.Management.Automation/engine/CompiledCommandParameter.cs b/src/System.Management.Automation/engine/CompiledCommandParameter.cs index a9e85f43280..ba4fa1fbb21 100644 --- a/src/System.Management.Automation/engine/CompiledCommandParameter.cs +++ b/src/System.Management.Automation/engine/CompiledCommandParameter.cs @@ -649,7 +649,7 @@ internal ParameterCollectionTypeInformation(Type type) // to an ICollection is via reflected calls to Add(T), // but the advantage over plain IList is that we can typecast the elements. Type interfaceICollection = - interfaces.FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(ICollection<>)); + Array.Find(interfaces, i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(ICollection<>)); if (interfaceICollection != null) { // We only deal with the first type for which ICollection is implemented diff --git a/src/System.Management.Automation/engine/GetCommandCommand.cs b/src/System.Management.Automation/engine/GetCommandCommand.cs index 8b2f6d21667..95b9889ea78 100644 --- a/src/System.Management.Automation/engine/GetCommandCommand.cs +++ b/src/System.Management.Automation/engine/GetCommandCommand.cs @@ -1601,7 +1601,7 @@ private static PSObject[] GetParameterInfo(ReadOnlyCollection validValues = new List(); - var validateSetAttribute = parameter.Attributes.Where(x => (x is ValidateSetAttribute)).Cast().LastOrDefault(); + var validateSetAttribute = parameter.Attributes.OfType().LastOrDefault(); if (validateSetAttribute != null) { hasParameterSet = true; @@ -1631,7 +1631,7 @@ private static PSObject GetParameterType(Type parameterType) returnParameterType.Properties.Add(new PSNoteProperty("EnumValues", enumValues)); bool hasFlagAttribute = (isArray) ? - ((parameterType.GetCustomAttributes(typeof(FlagsAttribute), true)).Count() > 0) : false; + ((parameterType.GetCustomAttributes(typeof(FlagsAttribute), true)).Length > 0) : false; returnParameterType.Properties.Add(new PSNoteProperty("HasFlagAttribute", hasFlagAttribute)); // Recurse into array elements. diff --git a/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs b/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs index 8b2e996bd84..8ee68283ec6 100644 --- a/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs +++ b/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs @@ -965,7 +965,7 @@ protected override void EndProcessing() ValidateUriParameterValue(new Uri(_helpInfoUri), "HelpInfoUri"); } - if (CompatiblePSEditions != null && (CompatiblePSEditions.Distinct(StringComparer.OrdinalIgnoreCase).Count() != CompatiblePSEditions.Count())) + if (CompatiblePSEditions != null && (CompatiblePSEditions.Distinct(StringComparer.OrdinalIgnoreCase).Count() != CompatiblePSEditions.Length)) { string message = StringUtil.Format(Modules.DuplicateEntriesInCompatiblePSEditions, string.Join(",", CompatiblePSEditions)); var ioe = new InvalidOperationException(message); diff --git a/src/System.Management.Automation/engine/SessionStateScope.cs b/src/System.Management.Automation/engine/SessionStateScope.cs index ecae52770bb..54b7a40e1f2 100644 --- a/src/System.Management.Automation/engine/SessionStateScope.cs +++ b/src/System.Management.Automation/engine/SessionStateScope.cs @@ -1952,7 +1952,7 @@ private void RemoveAliasFromCache(string alias, string value) } else { - string itemToRemove = list.FirstOrDefault(item => item.Equals(alias, StringComparison.OrdinalIgnoreCase)); + string itemToRemove = list.Find(item => item.Equals(alias, StringComparison.OrdinalIgnoreCase)); if (itemToRemove != null) { list.Remove(itemToRemove); diff --git a/src/System.Management.Automation/engine/debugger/debugger.cs b/src/System.Management.Automation/engine/debugger/debugger.cs index b8683ad5e2c..41d82bffb64 100644 --- a/src/System.Management.Automation/engine/debugger/debugger.cs +++ b/src/System.Management.Automation/engine/debugger/debugger.cs @@ -5615,7 +5615,7 @@ public Dictionary GetFrameVariables() break; } - if (scope.DottedScopes != null && scope.DottedScopes.Where(s => s == FunctionContext._localsTuple).Any()) + if (scope.DottedScopes != null && scope.DottedScopes.Any(s => s == FunctionContext._localsTuple)) { var dottedScopes = scope.DottedScopes.ToArray(); diff --git a/src/System.Management.Automation/engine/interpreter/LightCompiler.cs b/src/System.Management.Automation/engine/interpreter/LightCompiler.cs index b05b317dfb5..e5d399bf480 100644 --- a/src/System.Management.Automation/engine/interpreter/LightCompiler.cs +++ b/src/System.Management.Automation/engine/interpreter/LightCompiler.cs @@ -167,7 +167,7 @@ internal TryCatchFinallyHandler(int tryStart, int tryEnd, int gotoEndLabelIndex, internal int GotoHandler(InterpretedFrame frame, object exception, out ExceptionHandler handler) { Debug.Assert(_handlers != null, "we should have at least one handler if the method gets called"); - handler = _handlers.FirstOrDefault(t => t.Matches(exception.GetType())); + handler = Array.Find(_handlers, t => t.Matches(exception.GetType())); if (handler == null) { return 0; } return frame.Goto(handler.LabelIndex, exception, gotoExceptionHandler: true); diff --git a/src/System.Management.Automation/engine/lang/scriptblock.cs b/src/System.Management.Automation/engine/lang/scriptblock.cs index cdce996a3c9..5930273ee60 100644 --- a/src/System.Management.Automation/engine/lang/scriptblock.cs +++ b/src/System.Management.Automation/engine/lang/scriptblock.cs @@ -463,7 +463,7 @@ public Collection InvokeWithContext( if (variablesToDefine != null) { // Extract the special variables "this", "input" and "_" - PSVariable located = variablesToDefine.FirstOrDefault( + PSVariable located = variablesToDefine.Find( v => string.Equals(v.Name, "this", StringComparison.OrdinalIgnoreCase)); if (located != null) { @@ -471,7 +471,7 @@ public Collection InvokeWithContext( variablesToDefine.Remove(located); } - located = variablesToDefine.FirstOrDefault( + located = variablesToDefine.Find( v => string.Equals(v.Name, "_", StringComparison.Ordinal)); if (located != null) { @@ -479,7 +479,7 @@ public Collection InvokeWithContext( variablesToDefine.Remove(located); } - located = variablesToDefine.FirstOrDefault( + located = variablesToDefine.Find( v => string.Equals(v.Name, "input", StringComparison.OrdinalIgnoreCase)); if (located != null) { diff --git a/src/System.Management.Automation/engine/parser/AstVisitor.cs b/src/System.Management.Automation/engine/parser/AstVisitor.cs index 4d24dcf55a3..03ce04ea4ad 100644 --- a/src/System.Management.Automation/engine/parser/AstVisitor.cs +++ b/src/System.Management.Automation/engine/parser/AstVisitor.cs @@ -374,7 +374,7 @@ internal static bool Contains(Ast ast, Func predicate, bool searchNes var searcher = new AstSearcher(predicate, stopOnFirst: true, searchNestedScriptBlocks: searchNestedScriptBlocks); ast.InternalVisit(searcher); - return searcher.Results.FirstOrDefault() != null; + return searcher.Results.Any(); } internal static bool IsUsingDollarInput(Ast ast) diff --git a/src/System.Management.Automation/engine/parser/PSType.cs b/src/System.Management.Automation/engine/parser/PSType.cs index 0619f09a17b..8a18f880bab 100644 --- a/src/System.Management.Automation/engine/parser/PSType.cs +++ b/src/System.Management.Automation/engine/parser/PSType.cs @@ -838,7 +838,7 @@ private void DefineMethod(FunctionMemberAst functionMemberAst) var parameters = functionMemberAst.Parameters; if (parameters.Count > 0) { - IScriptExtent errorExtent = Parser.ExtentOf(parameters.First(), parameters.Last()); + IScriptExtent errorExtent = Parser.ExtentOf(parameters[0], parameters.Last()); _parser.ReportError(errorExtent, nameof(ParserStrings.StaticConstructorCantHaveParameters), ParserStrings.StaticConstructorCantHaveParameters); @@ -888,7 +888,7 @@ private void DefineMethod(FunctionMemberAst functionMemberAst) } var ilGenerator = method.GetILGenerator(); - DefineMethodBody(functionMemberAst, ilGenerator, GetMetaDataName(method.Name, parameterTypes.Count()), functionMemberAst.IsStatic, parameterTypes, returnType, + DefineMethodBody(functionMemberAst, ilGenerator, GetMetaDataName(method.Name, parameterTypes.Length), functionMemberAst.IsStatic, parameterTypes, returnType, (i, n) => method.DefineParameter(i, ParameterAttributes.None, n)); } @@ -917,7 +917,7 @@ private void DefineConstructor(IParameterMetadataProvider ipmp, ReadOnlyCollecti ilGenerator.Emit(OpCodes.Stfld, _sessionStateField); } - DefineMethodBody(ipmp, ilGenerator, GetMetaDataName(ctor.Name, parameterTypes.Count()), isStatic, parameterTypes, typeof(void), + DefineMethodBody(ipmp, ilGenerator, GetMetaDataName(ctor.Name, parameterTypes.Length), isStatic, parameterTypes, typeof(void), (i, n) => ctor.DefineParameter(i, ParameterAttributes.None, n)); } diff --git a/src/System.Management.Automation/engine/parser/Parser.cs b/src/System.Management.Automation/engine/parser/Parser.cs index 696a6802dd7..d65835424a6 100644 --- a/src/System.Management.Automation/engine/parser/Parser.cs +++ b/src/System.Management.Automation/engine/parser/Parser.cs @@ -6277,7 +6277,7 @@ private ExpressionAst GetCommandArgument(CommandArgumentContext context, Token t nameof(ParserStrings.MissingExpression), ParserStrings.MissingExpression, ","); - return new ErrorExpressionAst(ExtentOf(commandArgs.First(), commaToken), commandArgs); + return new ErrorExpressionAst(ExtentOf(commandArgs[0], commaToken), commandArgs); case TokenKind.SplattedVariable: case TokenKind.Variable: diff --git a/src/System.Management.Automation/engine/parser/VariableAnalysis.cs b/src/System.Management.Automation/engine/parser/VariableAnalysis.cs index 1abe8bb6603..052a4d5aa7f 100644 --- a/src/System.Management.Automation/engine/parser/VariableAnalysis.cs +++ b/src/System.Management.Automation/engine/parser/VariableAnalysis.cs @@ -103,7 +103,7 @@ internal static Dictionary Visit(IParameterMeta visitor.VisitParameters(ast.Parameters); } - localsAllocated = visitor._variables.Where(details => details.Value.LocalTupleIndex != VariableAnalysis.Unanalyzed).Count(); + localsAllocated = visitor._variables.Count(details => details.Value.LocalTupleIndex != VariableAnalysis.Unanalyzed); return visitor._variables; } diff --git a/src/System.Management.Automation/engine/parser/ast.cs b/src/System.Management.Automation/engine/parser/ast.cs index 0aaa68bee94..7baec6102c3 100644 --- a/src/System.Management.Automation/engine/parser/ast.cs +++ b/src/System.Management.Automation/engine/parser/ast.cs @@ -223,7 +223,7 @@ internal static T[] CopyElements(ReadOnlyCollection elements) where T : As if (elements == null || elements.Count == 0) { return null; } var result = new T[elements.Count]; - for (int i = 0; i < result.Count(); i++) + for (int i = 0; i < result.Length; i++) { result[i] = (T)elements[i].Copy(); } @@ -6852,7 +6852,7 @@ public class DynamicKeywordStatementAst : StatementAst public DynamicKeywordStatementAst(IScriptExtent extent, IEnumerable commandElements) : base(extent) { - if (commandElements == null || commandElements.Count() <= 0) + if (commandElements == null || !commandElements.Any()) { throw PSTraceSource.NewArgumentException(nameof(commandElements)); } diff --git a/src/System.Management.Automation/engine/remoting/commands/WaitJob.cs b/src/System.Management.Automation/engine/remoting/commands/WaitJob.cs index dd04519eb19..f023ca168a7 100644 --- a/src/System.Management.Automation/engine/remoting/commands/WaitJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/WaitJob.cs @@ -247,7 +247,7 @@ private Job GetOneBlockedJob() { lock (_jobTrackingLock) { - return _jobsToWaitFor.FirstOrDefault(j => j.JobStateInfo.State == JobState.Blocked); + return _jobsToWaitFor.Find(j => j.JobStateInfo.State == JobState.Blocked); } } diff --git a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs index 417fcd15b96..819588225ba 100644 --- a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs +++ b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs @@ -428,7 +428,7 @@ internal CmdletBindingAttribute CmdletBindingAttribute } return _usesCmdletBinding - ? (CmdletBindingAttribute)_attributes.FirstOrDefault(attr => attr is CmdletBindingAttribute) + ? (CmdletBindingAttribute)Array.Find(_attributes, attr => attr is CmdletBindingAttribute) : null; } } @@ -442,7 +442,7 @@ internal ObsoleteAttribute ObsoleteAttribute InitializeMetadata(); } - return (ObsoleteAttribute)_attributes.FirstOrDefault(attr => attr is ObsoleteAttribute); + return (ObsoleteAttribute)Array.Find(_attributes, attr => attr is ObsoleteAttribute); } } diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 1ad37502614..ffe36a786ac 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -167,7 +167,7 @@ private static string GetCorrectCasedPath(string path) var entries = Directory.GetFileSystemEntries(exactPath, item); if (entries.Length > 0) { - exactPath = entries.First(); + exactPath = entries[0]; } else { From 585affef319eb04f3427295244d7d9c7a7c30e9e Mon Sep 17 00:00:00 2001 From: xtqqczze Date: Fri, 12 Jun 2020 12:31:31 +0100 Subject: [PATCH 3/4] RCS1235: Optimize method call --- .../CmdletOperation.cs | 4 ++-- .../Utils.cs | 2 +- .../HelpWindow/HelpParagraphBuilder.cs | 10 +++++----- .../ShowCommand/ViewModel/CommandViewModel.cs | 2 +- .../GetCounterCommand.cs | 2 +- .../management/ClearRecycleBinCommand.cs | 2 +- .../commands/management/Computer.cs | 2 +- .../commands/management/ContentCommandBase.cs | 4 ++-- .../management/GetComputerInfoCommand.cs | 4 ++-- .../commands/utility/Get-PSBreakpoint.cs | 4 ++-- .../commands/utility/GetUnique.cs | 2 +- .../commands/utility/Measure-Object.cs | 2 +- .../commands/utility/New-Object.cs | 2 +- .../commands/utility/WebCmdlet/JsonObject.cs | 2 +- .../host/msh/ConsoleHostUserInterfacePrompt.cs | 4 ++-- .../host/msh/Serialization.cs | 2 +- .../DscSupport/CimDSCParser.cs | 16 ++++++++-------- .../common/DisplayDatabase/typeDataQuery.cs | 2 +- .../FormatAndOutput/common/FormatGroupManager.cs | 2 +- .../common/FormattingObjectsDeserializer.cs | 2 +- .../CommandCompletion/CommandCompletion.cs | 6 +++--- .../CommandCompletion/CompletionAnalysis.cs | 2 +- .../engine/EnumExpressionEvaluator.cs | 2 +- .../engine/GetCommandCommand.cs | 4 ++-- .../engine/LanguagePrimitives.cs | 2 +- .../engine/SessionStateContainer.cs | 2 +- .../engine/SessionStateDriveAPIs.cs | 4 ++-- .../engine/SessionStateLocationAPIs.cs | 4 ++-- .../engine/TypeTable.cs | 10 +++++----- .../engine/debugger/debugger.cs | 4 ++-- .../engine/hostifaces/LocalPipeline.cs | 2 +- .../engine/hostifaces/MshHostUserInterface.cs | 6 +++--- .../engine/interpreter/Utilities.cs | 2 +- .../engine/parser/Parser.cs | 2 +- .../engine/parser/TypeInferenceVisitor.cs | 2 +- .../engine/parser/tokenizer.cs | 2 +- .../commands/EnterPSHostProcessCommand.cs | 2 +- .../engine/remoting/commands/ReceivePSSession.cs | 2 +- .../remoting/common/RemoteSessionHyperVSocket.cs | 6 +++--- .../engine/serialization.cs | 4 ++-- .../help/CommandHelpProvider.cs | 6 +++--- .../help/DscResourceHelpProvider.cs | 4 ++-- .../help/MamlNode.cs | 4 ++-- .../help/PSClassHelpProvider.cs | 4 ++-- .../help/ProviderHelpProvider.cs | 4 ++-- .../help/UpdatableHelpInfo.cs | 8 ++++---- .../namespaces/FileSystemProvider.cs | 12 ++++++------ .../namespaces/LocationGlobber.cs | 8 ++++---- .../namespaces/NavigationProviderBase.cs | 4 ++-- .../namespaces/RegistryProvider.cs | 12 ++++++------ .../singleshell/config/MshSnapinInfo.cs | 2 +- 51 files changed, 105 insertions(+), 105 deletions(-) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs index 648f6cfb327..f92dd6e8feb 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs @@ -234,8 +234,8 @@ public override void WriteObject(object sendToPipeline, XOperationContextBase co CimSetCimInstanceContext setContext = context as CimSetCimInstanceContext; if (setContext != null) { - if ((string.Compare(setContext.ParameterSetName, CimBaseCommand.QueryComputerSet, StringComparison.OrdinalIgnoreCase) == 0) || - (string.Compare(setContext.ParameterSetName, CimBaseCommand.QuerySessionSet, StringComparison.OrdinalIgnoreCase) == 0)) + if ((string.Equals(setContext.ParameterSetName, CimBaseCommand.QueryComputerSet, StringComparison.OrdinalIgnoreCase)) || + (string.Equals(setContext.ParameterSetName, CimBaseCommand.QuerySessionSet, StringComparison.OrdinalIgnoreCase))) { this.setCimInstance.SetCimInstance(sendToPipeline as CimInstance, setContext, this); return; diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs index e1104e4514b..96a56b8d0c9 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs @@ -452,7 +452,7 @@ public static string[] ValidateArgumentIsValidName(string parameterName, string[ foreach (string propertyName in value) { // * is wild char supported in select properties - if ((propertyName != null) && (string.Compare(propertyName.Trim(), "*", StringComparison.OrdinalIgnoreCase) == 0)) + if ((propertyName != null) && (string.Equals(propertyName.Trim(), "*", StringComparison.OrdinalIgnoreCase))) { continue; } diff --git a/src/Microsoft.Management.UI.Internal/HelpWindow/HelpParagraphBuilder.cs b/src/Microsoft.Management.UI.Internal/HelpWindow/HelpParagraphBuilder.cs index 8667afa3a62..1d4bcacd893 100644 --- a/src/Microsoft.Management.UI.Internal/HelpWindow/HelpParagraphBuilder.cs +++ b/src/Microsoft.Management.UI.Internal/HelpWindow/HelpParagraphBuilder.cs @@ -82,11 +82,11 @@ internal void AddTextToParagraphBuilder() HelpCategory category = HelpCategory.Default; - if (string.Compare(strCategory, "DscResource", StringComparison.OrdinalIgnoreCase) == 0) + if (string.Equals(strCategory, "DscResource", StringComparison.OrdinalIgnoreCase)) { category = HelpCategory.DscResource; } - else if (string.Compare(strCategory, "Class", StringComparison.OrdinalIgnoreCase) == 0) + else if (string.Equals(strCategory, "Class", StringComparison.OrdinalIgnoreCase)) { category = HelpCategory.Class; } @@ -594,7 +594,7 @@ private void AddMembers(bool setting, string sectionTitle) string type = GetPropertyString(member, "type"); string propertyType = null; - if (string.Compare("field", type, StringComparison.OrdinalIgnoreCase) == 0) + if (string.Equals("field", type, StringComparison.OrdinalIgnoreCase)) { PSObject fieldData = HelpParagraphBuilder.GetPropertyObject(member, "fieldData") as PSObject; @@ -610,7 +610,7 @@ private void AddMembers(bool setting, string sectionTitle) memberText = string.Format(CultureInfo.CurrentCulture, " [{0}] {1}\r\n", propertyType, name); } } - else if (string.Compare("method", type, StringComparison.OrdinalIgnoreCase) == 0) + else if (string.Equals("method", type, StringComparison.OrdinalIgnoreCase)) { FormatMethodData(member, name, out memberText, out description); } @@ -702,7 +702,7 @@ private static void FormatMethodData(PSObject member, string name, out string me parameterText.Append(paramString); } - if (string.Compare(parameterText[parameterText.Length - 1].ToString(), ",", StringComparison.OrdinalIgnoreCase) == 0) + if (string.Equals(parameterText[parameterText.Length - 1].ToString(), ",", StringComparison.OrdinalIgnoreCase)) { parameterText = parameterText.Remove(parameterText.Length - 1, 1); } diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandViewModel.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandViewModel.cs index a098185095c..e5eb1be800d 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandViewModel.cs @@ -612,7 +612,7 @@ private int Compare(ParameterSetViewModel source, ParameterSetViewModel target) } } - return string.Compare(source.Name, target.Name, StringComparison.Ordinal); + return string.CompareOrdinal(source.Name, target.Name); } /// diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs index 5ab73cf1ec6..459d553e27a 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs @@ -276,7 +276,7 @@ protected override void ProcessRecord() break; default: - Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Invalid parameter set name: {0}", ParameterSetName)); + Debug.Fail(string.Format(CultureInfo.InvariantCulture, "Invalid parameter set name: {0}", ParameterSetName)); break; } } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearRecycleBinCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearRecycleBinCommand.cs index f42e4dae173..3925c222eef 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearRecycleBinCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearRecycleBinCommand.cs @@ -113,7 +113,7 @@ private bool ValidDrivePath(string drivePath) { foreach (DriveInfo drive in _availableDrives) { - if (string.Compare(drive.Name, drivePath, StringComparison.OrdinalIgnoreCase) == 0) + if (string.Equals(drive.Name, drivePath, StringComparison.OrdinalIgnoreCase)) { actualDrive = drive; break; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs index dc545e76daa..5d2513a47ae 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs @@ -552,7 +552,7 @@ private List TestRestartStageUsingWsman(IEnumerable computerName string newLastBootUpTime = os.CimInstanceProperties["LastBootUpTime"].Value.ToString(); string oldLastBootUpTime = _computerInfos[computer].LastBootUpTime; - if (string.Compare(newLastBootUpTime, oldLastBootUpTime, StringComparison.OrdinalIgnoreCase) != 0) + if (!string.Equals(newLastBootUpTime, oldLastBootUpTime, StringComparison.OrdinalIgnoreCase)) { _computerInfos[computer].RebootComplete = true; nextTestList.Add(computer); diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs index 2271388c096..8de0f59fa16 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs @@ -151,10 +151,10 @@ internal void WriteContentObject(object content, long readCount, PathInfo pathIn if (_currentContentItem != null && ((_currentContentItem.PathInfo == pathInfo) || ( - string.Compare( + string.Equals( pathInfo.Path, _currentContentItem.PathInfo.Path, - StringComparison.OrdinalIgnoreCase) == 0) + StringComparison.OrdinalIgnoreCase)) ) ) { diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs index 14f8a207ae5..d73d191585e 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs @@ -1042,9 +1042,9 @@ private static List CollectPropertyNames(string[] requestedProperties) // find a matching property name via case-insensitive string comparison Predicate pred = (s) => { - return string.Compare(s, + return string.Equals(s, name, - StringComparison.OrdinalIgnoreCase) == 0; + StringComparison.OrdinalIgnoreCase); }; var propertyName = availableProperties.Find(pred); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSBreakpoint.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSBreakpoint.cs index ba57278f6c8..b836fafc9f9 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSBreakpoint.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSBreakpoint.cs @@ -259,11 +259,11 @@ protected override void ProcessRecord() return false; } - return string.Compare( + return string.Equals( SessionState.Path.GetUnresolvedProviderPathFromPSPath(breakpoint.Script), SessionState.Path.GetUnresolvedProviderPathFromPSPath(script), StringComparison.OrdinalIgnoreCase - ) == 0; + ); }); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUnique.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUnique.cs index 9dc133caced..ea33f7c28d7 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUnique.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUnique.cs @@ -77,7 +77,7 @@ protected override void ProcessRecord() _lastObjectAsString = _lastObject.ToString(); } - if (0 == string.Compare( + if (string.Equals( inputString, _lastObjectAsString, StringComparison.CurrentCulture)) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs index 2ef311e38f3..67a9e43c3b9 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs @@ -453,7 +453,7 @@ private bool IsMeasuringGeneric { get { - return string.Compare(ParameterSetName, GenericParameterSet, StringComparison.Ordinal) == 0; + return string.Equals(ParameterSetName, GenericParameterSet, StringComparison.Ordinal); } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs index c19c85d0a86..39fd390b1ce 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs @@ -133,7 +133,7 @@ protected override void BeginProcessing() Type type = null; PSArgumentException mshArgE = null; - if (string.Compare(ParameterSetName, netSetName, StringComparison.Ordinal) == 0) + if (string.Equals(ParameterSetName, netSetName, StringComparison.Ordinal)) { object _newObject = null; try diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs index def03fc9c45..2b15f150984 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs @@ -231,7 +231,7 @@ private static PSObject PopulateFromJDictionary(JObject entries, DuplicateMember // Case sensitive duplicates should normally not occur since JsonConvert.DeserializeObject // does not throw when encountering duplicates and just uses the last entry. if (memberHashTracker.TryGetValue(entry.Key, out var maybePropertyName) - && string.Compare(entry.Key, maybePropertyName, StringComparison.Ordinal) == 0) + && string.Equals(entry.Key, maybePropertyName, StringComparison.Ordinal)) { var errorMsg = string.Format(CultureInfo.CurrentCulture, WebCmdletStrings.DuplicateKeysInJsonString, entry.Key); error = new ErrorRecord( diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs index 9449669ab65..0afe5f987d8 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs @@ -516,13 +516,13 @@ private string PromptCommandMode(string input, FieldDescription desc, out bool i if (command.Length == 2) { - if (0 == string.Compare(command, "\"\"", StringComparison.OrdinalIgnoreCase)) + if (string.Equals(command, "\"\"", StringComparison.OrdinalIgnoreCase)) { return string.Empty; } } - if (0 == string.Compare(command, "$null", StringComparison.OrdinalIgnoreCase)) + if (string.Equals(command, "$null", StringComparison.OrdinalIgnoreCase)) { return null; } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs index 696e47313d5..696b95ca049 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs @@ -162,7 +162,7 @@ class WrappedDeserializer : Serialization textReader = input; _firstLine = textReader.ReadLine(); - if (string.Compare(_firstLine, Serialization.XmlCliTag, StringComparison.OrdinalIgnoreCase) == 0) + if (string.Equals(_firstLine, Serialization.XmlCliTag, StringComparison.OrdinalIgnoreCase)) { // format should be XML diff --git a/src/System.Management.Automation/DscSupport/CimDSCParser.cs b/src/System.Management.Automation/DscSupport/CimDSCParser.cs index 27b4e93bcc5..978f6ff4372 100644 --- a/src/System.Management.Automation/DscSupport/CimDSCParser.cs +++ b/src/System.Management.Automation/DscSupport/CimDSCParser.cs @@ -931,7 +931,7 @@ private static CimClass MyClassCallback(string serverName, string namespaceName, foreach (KeyValuePair cimClass in ClassCache) { string cachedClassName = cimClass.Key.Split(Utils.Separators.Backslash)[IndexClassName]; - if (string.Compare(cachedClassName, className, StringComparison.OrdinalIgnoreCase) == 0) + if (string.Equals(cachedClassName, className, StringComparison.OrdinalIgnoreCase)) { return cimClass.Value.CimClassInstance; } @@ -1107,9 +1107,9 @@ private static List> FindResourceInCach let cachedClassName = splittedName[IndexClassName] let cachedModuleName = splittedName[IndexModuleName] let cachedResourceName = splittedName[IndexFriendlyName] - where ((string.Compare(cachedResourceName, resourceName, StringComparison.OrdinalIgnoreCase) == 0) - || (string.Compare(cachedClassName, className, StringComparison.OrdinalIgnoreCase) == 0 - && string.Compare(cachedModuleName, moduleName, StringComparison.OrdinalIgnoreCase) == 0)) + where ((string.Equals(cachedResourceName, resourceName, StringComparison.OrdinalIgnoreCase)) + || (string.Equals(cachedClassName, className, StringComparison.OrdinalIgnoreCase) + && string.Equals(cachedModuleName, moduleName, StringComparison.OrdinalIgnoreCase))) select cacheEntry).ToList(); } @@ -1553,11 +1553,11 @@ private static DynamicKeyword CreateKeywordFromCimClass(string moduleName, Versi private static void UpdateKnownRestriction(DynamicKeyword keyword) { if ( - string.Compare(keyword.ResourceName, "MSFT_DSCMetaConfigurationV2", - StringComparison.OrdinalIgnoreCase) == 0 + string.Equals(keyword.ResourceName, "MSFT_DSCMetaConfigurationV2", + StringComparison.OrdinalIgnoreCase) || - string.Compare(keyword.ResourceName, "MSFT_DSCMetaConfiguration", - StringComparison.OrdinalIgnoreCase) == 0) + string.Equals(keyword.ResourceName, "MSFT_DSCMetaConfiguration", + StringComparison.OrdinalIgnoreCase)) { if (keyword.Properties["RefreshFrequencyMins"] != null) { diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs index 9e063988b08..ec0c40736fb 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs @@ -662,7 +662,7 @@ private static ControlBody ResolveControlReferenceInList(ControlReference contro { if (x.controlBody.GetType() != controlReference.controlType) continue; - if (string.Compare(controlReference.name, x.name, StringComparison.OrdinalIgnoreCase) == 0) + if (string.Equals(controlReference.name, x.name, StringComparison.OrdinalIgnoreCase)) return x.controlBody; } diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatGroupManager.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatGroupManager.cs index 92eb3708d16..c3d733a7f2d 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatGroupManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatGroupManager.cs @@ -97,7 +97,7 @@ private static bool IsEqual(object first, object second) string firstString = PSObject.AsPSObject(first).ToString(); string secondString = PSObject.AsPSObject(second).ToString(); - return string.Compare(firstString, secondString, StringComparison.CurrentCultureIgnoreCase) == 0; + return string.Equals(firstString, secondString, StringComparison.CurrentCultureIgnoreCase); } /// diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs b/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs index 3e8c320390b..21630c1a9c1 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs @@ -154,7 +154,7 @@ private void ProcessUnknownInvalidClassId(string classId, object obj, string err #region Helper Methods private static bool IsClass(string x, string y) { - return string.Compare(x, y, StringComparison.OrdinalIgnoreCase) == 0; + return string.Equals(x, y, StringComparison.OrdinalIgnoreCase); } #if _UNUSED diff --git a/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs b/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs index 7af3fb62fb4..e00e0d737fc 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs @@ -854,10 +854,10 @@ private static void PrependSnapInNameForSameCmdletNames(CommandAndName[] cmdlets CommandAndName nextCommandAndName = cmdlets[lookAhead]; - if (string.Compare( + if (string.Equals( commandAndName.CommandName.ShortName, nextCommandAndName.CommandName.ShortName, - StringComparison.OrdinalIgnoreCase) == 0) + StringComparison.OrdinalIgnoreCase)) { AddCommandResult(commandAndName, true, completingAtStartOfLine, quote, results); previousMatched = true; @@ -998,7 +998,7 @@ private static IEnumerable CombineMatchSets(List GetResultForIdentifierInConfiguration( IEnumerable keywords = configureAst.DefinedKeywords.Where( k => // Node is special case, legal in both Resource and Meta configuration - string.Compare(k.Keyword, @"Node", StringComparison.OrdinalIgnoreCase) == 0 || + string.Equals(k.Keyword, @"Node", StringComparison.OrdinalIgnoreCase) || ( // Check compatibility between Resource and Configuration Type k.IsCompatibleWithConfigurationType(configureAst.ConfigurationType) && diff --git a/src/System.Management.Automation/engine/EnumExpressionEvaluator.cs b/src/System.Management.Automation/engine/EnumExpressionEvaluator.cs index 092500c0af7..88aa49e98d2 100644 --- a/src/System.Management.Automation/engine/EnumExpressionEvaluator.cs +++ b/src/System.Management.Automation/engine/EnumExpressionEvaluator.cs @@ -131,7 +131,7 @@ internal Token(TokenKind kind) Text = "NOT"; break; default: - Debug.Assert(false, "Invalid token kind passed in."); + Debug.Fail("Invalid token kind passed in."); break; } } diff --git a/src/System.Management.Automation/engine/GetCommandCommand.cs b/src/System.Management.Automation/engine/GetCommandCommand.cs index 95b9889ea78..afc2b12393b 100644 --- a/src/System.Management.Automation/engine/GetCommandCommand.cs +++ b/src/System.Management.Automation/engine/GetCommandCommand.cs @@ -1491,10 +1491,10 @@ private bool IsCommandInResult(CommandInfo command) foreach (CommandInfo commandInfo in _accumulatedResults) { if ((command.CommandType == commandInfo.CommandType && - (string.Compare(command.Name, commandInfo.Name, StringComparison.OrdinalIgnoreCase) == 0 || + (string.Equals(command.Name, commandInfo.Name, StringComparison.OrdinalIgnoreCase) || // If the command has been imported with a prefix, then just checking the names for duplication will not be enough. // Hence, an additional check is done with the prefix information - string.Compare(ModuleCmdletBase.RemovePrefixFromCommandName(commandInfo.Name, commandInfo.Prefix), command.Name, StringComparison.OrdinalIgnoreCase) == 0) + string.Equals(ModuleCmdletBase.RemovePrefixFromCommandName(commandInfo.Name, commandInfo.Prefix), command.Name, StringComparison.OrdinalIgnoreCase)) ) && commandInfo.Module != null && commandHasModule && ( // We do reference equal comparison if both command are imported. If either one is not imported, we compare the module path (commandInfo.IsImported && command.IsImported && commandInfo.Module.Equals(command.Module)) || diff --git a/src/System.Management.Automation/engine/LanguagePrimitives.cs b/src/System.Management.Automation/engine/LanguagePrimitives.cs index 63ea00970c8..4a2b1608e60 100644 --- a/src/System.Management.Automation/engine/LanguagePrimitives.cs +++ b/src/System.Management.Automation/engine/LanguagePrimitives.cs @@ -2212,7 +2212,7 @@ protected static object BaseConvertFrom(object sourceValue, Type destinationType } else { - if (string.Compare(sourceValueEntry, name, ignoreCaseOpt) != 0) + if (!string.Equals(sourceValueEntry, name, ignoreCaseOpt)) continue; } diff --git a/src/System.Management.Automation/engine/SessionStateContainer.cs b/src/System.Management.Automation/engine/SessionStateContainer.cs index 4016bffbaa5..e3ce1679b49 100644 --- a/src/System.Management.Automation/engine/SessionStateContainer.cs +++ b/src/System.Management.Automation/engine/SessionStateContainer.cs @@ -3520,7 +3520,7 @@ internal void NewItem( out targetProvider, out targetProviderInstance); - if (string.Compare(targetProvider.Name, "filesystem", StringComparison.OrdinalIgnoreCase) != 0) + if (!string.Equals(targetProvider.Name, "filesystem", StringComparison.OrdinalIgnoreCase)) { throw PSTraceSource.NewNotSupportedException(SessionStateStrings.MustBeFileSystemPath); } diff --git a/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs b/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs index 7c2eeb447c8..23e9fdc0475 100644 --- a/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs @@ -170,7 +170,7 @@ internal void NewDrive(PSDriveInfo drive, string scopeID, CmdletProviderContext return; } - if (string.Compare(result.Name, drive.Name, StringComparison.OrdinalIgnoreCase) == 0) + if (string.Equals(result.Name, drive.Name, StringComparison.OrdinalIgnoreCase)) { // Set the drive in the current scope. @@ -1294,7 +1294,7 @@ private bool CanRemoveDrive(PSDriveInfo drive, CmdletProviderContext context) // Make sure the provider didn't try to pull a fast one on us // and substitute a different drive. - if (string.Compare(result.Name, drive.Name, StringComparison.OrdinalIgnoreCase) == 0) + if (string.Equals(result.Name, drive.Name, StringComparison.OrdinalIgnoreCase)) { driveRemovable = true; } diff --git a/src/System.Management.Automation/engine/SessionStateLocationAPIs.cs b/src/System.Management.Automation/engine/SessionStateLocationAPIs.cs index ca048aa0931..4cd4718aca5 100644 --- a/src/System.Management.Automation/engine/SessionStateLocationAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateLocationAPIs.cs @@ -733,7 +733,7 @@ CmdletProviderContext normalizePathContext providerSpecificPath, currentWorkingPath); - if (string.Compare(providerSpecificPath, currentWorkingPath, StringComparison.OrdinalIgnoreCase) == 0) + if (string.Equals(providerSpecificPath, currentWorkingPath, StringComparison.OrdinalIgnoreCase)) { // The path is the current working directory so // return true @@ -765,7 +765,7 @@ CmdletProviderContext normalizePathContext lockedDirectory, providerSpecificPath); - if (string.Compare(lockedDirectory, providerSpecificPath, StringComparison.OrdinalIgnoreCase) == 0) + if (string.Equals(lockedDirectory, providerSpecificPath, StringComparison.OrdinalIgnoreCase)) { // The path is a parent of the current working // directory diff --git a/src/System.Management.Automation/engine/TypeTable.cs b/src/System.Management.Automation/engine/TypeTable.cs index 2b0c0eb2ed0..c5b889b2586 100644 --- a/src/System.Management.Automation/engine/TypeTable.cs +++ b/src/System.Management.Automation/engine/TypeTable.cs @@ -2328,7 +2328,7 @@ public TypeData Copy() newTypeData.StringSerializationSource = this.StringSerializationSource; break; default: - Dbg.Assert(false, "Standard members should at most contain six kinds of elements"); + Dbg.Fail("Standard members should at most contain six kinds of elements"); break; } } @@ -2948,7 +2948,7 @@ private static bool GetCheckNote(ConcurrentBag errors, string typeName, for (int i = 0; i < members.Count; i++) { PSMemberInfo member = members[i]; - if (string.Compare(member.Name, noteName, StringComparison.OrdinalIgnoreCase) == 0) + if (string.Equals(member.Name, noteName, StringComparison.OrdinalIgnoreCase)) { noteAsMemberInfo = member; } @@ -2978,7 +2978,7 @@ private static bool GetCheckNote(ConcurrentBag errors, string typeName, } else { - note.noteValue = string.Compare(sourceValueAsString, "false", StringComparison.OrdinalIgnoreCase) != 0; + note.noteValue = !string.Equals(sourceValueAsString, "false", StringComparison.OrdinalIgnoreCase); } return true; @@ -3003,7 +3003,7 @@ private static bool EnsureNotPresent(ConcurrentBag errors, string typeNa for (int i = 0; i < members.Count; i++) { PSMemberInfo member = members[i]; - if (string.Compare(member.Name, memberName, StringComparison.OrdinalIgnoreCase) == 0) + if (string.Equals(member.Name, memberName, StringComparison.OrdinalIgnoreCase)) { AddError(errors, typeName, TypesXmlStrings.MemberShouldNotBePresent, member.Name); return false; @@ -3019,7 +3019,7 @@ private static bool GetCheckMemberType(ConcurrentBag errors, string type for (int i = 0; i < members.Count; i++) { PSMemberInfo m = members[i]; - if (string.Compare(m.Name, noteName, StringComparison.OrdinalIgnoreCase) == 0) + if (string.Equals(m.Name, noteName, StringComparison.OrdinalIgnoreCase)) { member = m; } diff --git a/src/System.Management.Automation/engine/debugger/debugger.cs b/src/System.Management.Automation/engine/debugger/debugger.cs index 41d82bffb64..d19815ac303 100644 --- a/src/System.Management.Automation/engine/debugger/debugger.cs +++ b/src/System.Management.Automation/engine/debugger/debugger.cs @@ -1949,7 +1949,7 @@ private void ResumeExecution(DebuggerResumeAction action) throw new TerminateException(); default: - Debug.Assert(false, "Received an unknown action: " + action); + Debug.Fail("Received an unknown action: " + action); break; } } @@ -3628,7 +3628,7 @@ internal override void StartMonitoringRunspace(PSMonitorRunspaceInfo runspaceInf if ((runspaceInfo.Runspace.Debugger != null) && runspaceInfo.Runspace.Debugger.Equals(this)) { - Debug.Assert(false, "Nested debugger cannot be the root debugger."); + Debug.Fail("Nested debugger cannot be the root debugger."); return; } diff --git a/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs b/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs index 379deff42e7..84c0c6c6ee9 100644 --- a/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs +++ b/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs @@ -249,7 +249,7 @@ protected override void StartPipelineExecution() } default: - Debug.Assert(false); + Debug.Fail(""); break; } } diff --git a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs index 2efd4d3c154..7650bf68540 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs @@ -1288,7 +1288,7 @@ internal static void BuildHotkeysAndPlainLabels(Collection ch #endregion SplitLabel // ? is not localizable - if (string.Compare(hotkeysAndPlainLabels[0, i], "?", StringComparison.Ordinal) == 0) + if (string.Equals(hotkeysAndPlainLabels[0, i], "?", StringComparison.Ordinal)) { Exception e = PSTraceSource.NewArgumentException( string.Format(Globalization.CultureInfo.InvariantCulture, "choices[{0}].Label", i), @@ -1320,7 +1320,7 @@ internal static int DetermineChoicePicked(string response, Collection 0) { - if (string.Compare(response, hotkeysAndPlainLabels[0, i], StringComparison.CurrentCultureIgnoreCase) == 0) + if (string.Equals(response, hotkeysAndPlainLabels[0, i], StringComparison.CurrentCultureIgnoreCase)) { result = i; break; diff --git a/src/System.Management.Automation/engine/interpreter/Utilities.cs b/src/System.Management.Automation/engine/interpreter/Utilities.cs index 2ff8dbf9790..810dea30d1a 100644 --- a/src/System.Management.Automation/engine/interpreter/Utilities.cs +++ b/src/System.Management.Automation/engine/interpreter/Utilities.cs @@ -905,7 +905,7 @@ internal static Exception Unreachable { get { - Debug.Assert(false, "Unreachable"); + Debug.Fail("Unreachable"); return new InvalidOperationException("Code supposed to be unreachable"); } } diff --git a/src/System.Management.Automation/engine/parser/Parser.cs b/src/System.Management.Automation/engine/parser/Parser.cs index d65835424a6..25622b80eda 100644 --- a/src/System.Management.Automation/engine/parser/Parser.cs +++ b/src/System.Management.Automation/engine/parser/Parser.cs @@ -3936,7 +3936,7 @@ instanceInvokeMemberExpressionAst.Arguments[0] is ScriptBlockExpressionAst && else if (keywordData.BodyMode == DynamicKeywordBodyMode.Hashtable) { // Resource property value could be set to nested DSC resources except Script resource - bool isScriptResource = string.Compare(functionName.Text, @"Script", StringComparison.OrdinalIgnoreCase) == 0; + bool isScriptResource = string.Equals(functionName.Text, @"Script", StringComparison.OrdinalIgnoreCase); try { if (isScriptResource) diff --git a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs index 5cdfc103f57..77efa843f28 100644 --- a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs +++ b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs @@ -1328,7 +1328,7 @@ bool IsInPropertyArgument(object o) switch (propertyNameOrPattern) { case string propertyName: - if (string.Compare(name, propertyName, StringComparison.OrdinalIgnoreCase) == 0) + if (string.Equals(name, propertyName, StringComparison.OrdinalIgnoreCase)) { return includeMatchedProperties; } diff --git a/src/System.Management.Automation/engine/parser/tokenizer.cs b/src/System.Management.Automation/engine/parser/tokenizer.cs index 6c956607e10..2b574071e1e 100644 --- a/src/System.Management.Automation/engine/parser/tokenizer.cs +++ b/src/System.Management.Automation/engine/parser/tokenizer.cs @@ -391,7 +391,7 @@ internal static bool IsCompatibleWithConfigurationType(this DynamicKeyword keywo internal static IEnumerable GetAllowedKeywords(this DynamicKeyword keyword, IEnumerable allowedKeywords) { string keywordName = keyword.Keyword; - if (string.Compare(keywordName, @"Node", StringComparison.OrdinalIgnoreCase) == 0) + if (string.Equals(keywordName, @"Node", StringComparison.OrdinalIgnoreCase)) { List excludeKeywords; if (s_excludeKeywords.TryGetValue(keywordName, out excludeKeywords)) diff --git a/src/System.Management.Automation/engine/remoting/commands/EnterPSHostProcessCommand.cs b/src/System.Management.Automation/engine/remoting/commands/EnterPSHostProcessCommand.cs index 3cf54997e5d..e99f77db796 100644 --- a/src/System.Management.Automation/engine/remoting/commands/EnterPSHostProcessCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/EnterPSHostProcessCommand.cs @@ -562,7 +562,7 @@ protected override void EndProcessing() break; default: - Debug.Assert(false, "Unknown parameter set."); + Debug.Fail("Unknown parameter set."); processAppDomainInfo = new ReadOnlyCollection(new Collection()); break; } diff --git a/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs b/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs index e36fb633783..500c5032a49 100644 --- a/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs +++ b/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs @@ -467,7 +467,7 @@ private void QueryForAndConnectCommands(string name, Guid instanceId) // Find specified session. bool haveMatch = false; if (!string.IsNullOrEmpty(name) && - string.Compare(name, ((RemoteRunspace)runspace).RunspacePool.RemoteRunspacePoolInternal.Name, StringComparison.OrdinalIgnoreCase) == 0) + string.Equals(name, ((RemoteRunspace)runspace).RunspacePool.RemoteRunspacePoolInternal.Name, StringComparison.OrdinalIgnoreCase)) { // Selected by friendly name. haveMatch = true; diff --git a/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs b/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs index 12bd7e1ad63..730a4aa9a2d 100644 --- a/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs +++ b/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs @@ -268,7 +268,7 @@ public RemoteSessionHyperVSocketServer(bool LoopbackMode) if (ex != null) { - Dbg.Assert(false, "Unexpected error in RemoteSessionHyperVSocketServer."); + Dbg.Fail("Unexpected error in RemoteSessionHyperVSocketServer."); // Unexpected error. string errorMessage = !string.IsNullOrEmpty(ex.Message) ? ex.Message : string.Empty; @@ -575,7 +575,7 @@ public bool Connect( // // Credential is invalid. // - if (string.Compare(responseString, "FAIL", StringComparison.Ordinal) == 0) + if (string.Equals(responseString, "FAIL", StringComparison.Ordinal)) { HyperVSocket.Send(response); @@ -586,7 +586,7 @@ public bool Connect( // // If PowerShell Direct in VM supports configuration, send configuration name. // - if (string.Compare(responseString, "CONF", StringComparison.Ordinal) == 0) + if (string.Equals(responseString, "CONF", StringComparison.Ordinal)) { if (emptyConfiguration) { diff --git a/src/System.Management.Automation/engine/serialization.cs b/src/System.Management.Automation/engine/serialization.cs index 31ec2e348d2..b70c7037c26 100644 --- a/src/System.Management.Automation/engine/serialization.cs +++ b/src/System.Management.Automation/engine/serialization.cs @@ -4019,7 +4019,7 @@ private object ReadDictionary(ContainerType ct) } string name = ReadNameAttribute(); - if (string.Compare(name, SerializationStrings.DictionaryKey, StringComparison.OrdinalIgnoreCase) != 0) + if (!string.Equals(name, SerializationStrings.DictionaryKey, StringComparison.OrdinalIgnoreCase)) { throw NewXmlException(Serialization.InvalidDictionaryKeyName, null); } @@ -4037,7 +4037,7 @@ private object ReadDictionary(ContainerType ct) } name = ReadNameAttribute(); - if (string.Compare(name, SerializationStrings.DictionaryValue, StringComparison.OrdinalIgnoreCase) != 0) + if (!string.Equals(name, SerializationStrings.DictionaryValue, StringComparison.OrdinalIgnoreCase)) { throw NewXmlException(Serialization.InvalidDictionaryValueName, null); } diff --git a/src/System.Management.Automation/help/CommandHelpProvider.cs b/src/System.Management.Automation/help/CommandHelpProvider.cs index aa3c1edb70e..8771c4eced7 100644 --- a/src/System.Management.Automation/help/CommandHelpProvider.cs +++ b/src/System.Management.Automation/help/CommandHelpProvider.cs @@ -696,7 +696,7 @@ private void LoadHelpFile(string helpFile, string helpFileIdentifier) for (int i = 0; i < doc.ChildNodes.Count; i++) { XmlNode node = doc.ChildNodes[i]; - if (node.NodeType == XmlNodeType.Element && string.Compare(node.LocalName, "helpItems", StringComparison.OrdinalIgnoreCase) == 0) + if (node.NodeType == XmlNodeType.Element && string.Equals(node.LocalName, "helpItems", StringComparison.OrdinalIgnoreCase)) { helpItemsNode = node; break; @@ -719,7 +719,7 @@ private void LoadHelpFile(string helpFile, string helpFileIdentifier) for (int i = 0; i < helpItemsNode.ChildNodes.Count; i++) { XmlNode node = helpItemsNode.ChildNodes[i]; - if (node.NodeType == XmlNodeType.Element && string.Compare(node.LocalName, "command", StringComparison.OrdinalIgnoreCase) == 0) + if (node.NodeType == XmlNodeType.Element && string.Equals(node.LocalName, "command", StringComparison.OrdinalIgnoreCase)) { MamlCommandHelpInfo helpInfo = null; @@ -735,7 +735,7 @@ private void LoadHelpFile(string helpFile, string helpFileIdentifier) } } - if (node.NodeType == XmlNodeType.Element && string.Compare(node.Name, "UserDefinedData", StringComparison.OrdinalIgnoreCase) == 0) + if (node.NodeType == XmlNodeType.Element && string.Equals(node.Name, "UserDefinedData", StringComparison.OrdinalIgnoreCase)) { UserDefinedHelpData userDefinedHelpData = UserDefinedHelpData.Load(node); diff --git a/src/System.Management.Automation/help/DscResourceHelpProvider.cs b/src/System.Management.Automation/help/DscResourceHelpProvider.cs index b0cdc239fb8..c29ed02b456 100644 --- a/src/System.Management.Automation/help/DscResourceHelpProvider.cs +++ b/src/System.Management.Automation/help/DscResourceHelpProvider.cs @@ -317,7 +317,7 @@ private void LoadHelpFile(string helpFile, string helpFileIdentifier) for (int i = 0; i < doc.ChildNodes.Count; i++) { XmlNode node = doc.ChildNodes[i]; - if (node.NodeType == XmlNodeType.Element && string.Compare(node.LocalName, "helpItems", StringComparison.OrdinalIgnoreCase) == 0) + if (node.NodeType == XmlNodeType.Element && string.Equals(node.LocalName, "helpItems", StringComparison.OrdinalIgnoreCase)) { helpItemsNode = node; break; @@ -343,7 +343,7 @@ private void LoadHelpFile(string helpFile, string helpFileIdentifier) string nodeLocalName = node.LocalName; - bool isDscResource = (string.Compare(nodeLocalName, "dscResource", StringComparison.OrdinalIgnoreCase) == 0); + bool isDscResource = (string.Equals(nodeLocalName, "dscResource", StringComparison.OrdinalIgnoreCase)); if (node.NodeType == XmlNodeType.Element && isDscResource) { diff --git a/src/System.Management.Automation/help/MamlNode.cs b/src/System.Management.Automation/help/MamlNode.cs index 712dc2325ea..51fda0bc244 100644 --- a/src/System.Management.Automation/help/MamlNode.cs +++ b/src/System.Management.Automation/help/MamlNode.cs @@ -214,9 +214,9 @@ private PSObject GetPSObject(XmlNode xmlNode) if (xmlNode.Attributes["type"] != null) { - if (string.Compare(xmlNode.Attributes["type"].Value, "field", StringComparison.OrdinalIgnoreCase) == 0) + if (string.Equals(xmlNode.Attributes["type"].Value, "field", StringComparison.OrdinalIgnoreCase)) mshObject.TypeNames.Add("MamlPSClassHelpInfo#field"); - else if (string.Compare(xmlNode.Attributes["type"].Value, "method", StringComparison.OrdinalIgnoreCase) == 0) + else if (string.Equals(xmlNode.Attributes["type"].Value, "method", StringComparison.OrdinalIgnoreCase)) mshObject.TypeNames.Add("MamlPSClassHelpInfo#method"); } diff --git a/src/System.Management.Automation/help/PSClassHelpProvider.cs b/src/System.Management.Automation/help/PSClassHelpProvider.cs index b6ec7a0db69..ee65529a026 100644 --- a/src/System.Management.Automation/help/PSClassHelpProvider.cs +++ b/src/System.Management.Automation/help/PSClassHelpProvider.cs @@ -322,7 +322,7 @@ private void LoadHelpFile(string helpFile, string helpFileIdentifier) for (int i = 0; i < doc.ChildNodes.Count; i++) { XmlNode node = doc.ChildNodes[i]; - if (node.NodeType == XmlNodeType.Element && string.Compare(node.LocalName, "helpItems", StringComparison.OrdinalIgnoreCase) == 0) + if (node.NodeType == XmlNodeType.Element && string.Equals(node.LocalName, "helpItems", StringComparison.OrdinalIgnoreCase)) { helpItemsNode = node; break; @@ -348,7 +348,7 @@ private void LoadHelpFile(string helpFile, string helpFileIdentifier) string nodeLocalName = node.LocalName; - bool isClass = (string.Compare(nodeLocalName, "class", StringComparison.OrdinalIgnoreCase) == 0); + bool isClass = (string.Equals(nodeLocalName, "class", StringComparison.OrdinalIgnoreCase)); if (node.NodeType == XmlNodeType.Element && isClass) { diff --git a/src/System.Management.Automation/help/ProviderHelpProvider.cs b/src/System.Management.Automation/help/ProviderHelpProvider.cs index a7d92f58f24..b28dcf86398 100644 --- a/src/System.Management.Automation/help/ProviderHelpProvider.cs +++ b/src/System.Management.Automation/help/ProviderHelpProvider.cs @@ -209,7 +209,7 @@ private void LoadHelpFile(ProviderInfo providerInfo) for (int i = 0; i < doc.ChildNodes.Count; i++) { XmlNode node = doc.ChildNodes[i]; - if (node.NodeType == XmlNodeType.Element && string.Compare(node.Name, "helpItems", StringComparison.OrdinalIgnoreCase) == 0) + if (node.NodeType == XmlNodeType.Element && string.Equals(node.Name, "helpItems", StringComparison.OrdinalIgnoreCase)) { helpItemsNode = node; break; @@ -227,7 +227,7 @@ private void LoadHelpFile(ProviderInfo providerInfo) for (int i = 0; i < helpItemsNode.ChildNodes.Count; i++) { XmlNode node = helpItemsNode.ChildNodes[i]; - if (node.NodeType == XmlNodeType.Element && string.Compare(node.Name, "providerHelp", StringComparison.OrdinalIgnoreCase) == 0) + if (node.NodeType == XmlNodeType.Element && string.Equals(node.Name, "providerHelp", StringComparison.OrdinalIgnoreCase)) { HelpInfo helpInfo = ProviderHelpInfo.Load(node); diff --git a/src/System.Management.Automation/help/UpdatableHelpInfo.cs b/src/System.Management.Automation/help/UpdatableHelpInfo.cs index 46026529df6..5af3fd57b6d 100644 --- a/src/System.Management.Automation/help/UpdatableHelpInfo.cs +++ b/src/System.Management.Automation/help/UpdatableHelpInfo.cs @@ -107,8 +107,8 @@ internal bool IsCultureSupported(CultureInfo culture) foreach (CultureSpecificUpdatableHelp updatableHelpItem in UpdatableHelpItems) { - if (string.Compare(updatableHelpItem.Culture.Name, culture.Name, - StringComparison.OrdinalIgnoreCase) == 0) + if (string.Equals(updatableHelpItem.Culture.Name, culture.Name, + StringComparison.OrdinalIgnoreCase)) { return true; } @@ -152,8 +152,8 @@ internal Version GetCultureVersion(CultureInfo culture) { foreach (CultureSpecificUpdatableHelp updatableHelpItem in UpdatableHelpItems) { - if (string.Compare(updatableHelpItem.Culture.Name, culture.Name, - StringComparison.OrdinalIgnoreCase) == 0) + if (string.Equals(updatableHelpItem.Culture.Name, culture.Name, + StringComparison.OrdinalIgnoreCase)) { return updatableHelpItem.Version; } diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index ffe36a786ac..9c454ce68f9 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -1417,10 +1417,10 @@ private FileSystemInfo GetFileSystemItem(string path, ref bool isContainer, bool // Since all root paths are hidden we need to show the directory // anyway bool isRootPath = - string.Compare( + string.Equals( Path.GetPathRoot(path), result.FullName, - StringComparison.OrdinalIgnoreCase) == 0; + StringComparison.OrdinalIgnoreCase); // if "Hidden" is specified in the attribute filter dynamic parameters // also return the object @@ -2140,7 +2140,7 @@ protected override void RenameItem( // Check to see if the target specified is just filename. We dont allow rename to move the file to a different directory. // If a path is specified for the newName then we flag that as an error. - if (string.Compare(Path.GetFileName(newName), newName, StringComparison.OrdinalIgnoreCase) != 0) + if (!string.Equals(Path.GetFileName(newName), newName, StringComparison.OrdinalIgnoreCase)) { throw PSTraceSource.NewArgumentException(nameof(newName), FileSystemProviderStrings.RenameError); } @@ -2858,10 +2858,10 @@ private bool CreateIntermediateDirectories(string path) string parentPath = GetParentPath(path, root); if (!string.IsNullOrEmpty(parentPath) && - string.Compare( + !string.Equals( parentPath, previousParent, - StringComparison.OrdinalIgnoreCase) != 0) + StringComparison.OrdinalIgnoreCase)) { if (!ItemExists(parentPath)) { @@ -6339,7 +6339,7 @@ public void SetProperty(string path, PSObject propertyToSet) if (member != null) { - if (string.Compare(property.Name, "attributes", StringComparison.OrdinalIgnoreCase) == 0) + if (string.Equals(property.Name, "attributes", StringComparison.OrdinalIgnoreCase)) { FileAttributes attributes; diff --git a/src/System.Management.Automation/namespaces/LocationGlobber.cs b/src/System.Management.Automation/namespaces/LocationGlobber.cs index ab43d492d8f..d5e60b652c9 100644 --- a/src/System.Management.Automation/namespaces/LocationGlobber.cs +++ b/src/System.Management.Automation/namespaces/LocationGlobber.cs @@ -1719,20 +1719,20 @@ internal bool IsShellVirtualDrive(string driveName, out SessionStateScope scope) bool result = false; - if (string.Compare( + if (string.Equals( driveName, StringLiterals.Global, - StringComparison.OrdinalIgnoreCase) == 0) + StringComparison.OrdinalIgnoreCase)) { // It's the global scope. s_tracer.WriteLine("match found: {0}", StringLiterals.Global); result = true; scope = _sessionState.Internal.GlobalScope; } - else if (string.Compare( + else if (string.Equals( driveName, StringLiterals.Local, - StringComparison.OrdinalIgnoreCase) == 0) + StringComparison.OrdinalIgnoreCase)) { // It's the local scope. s_tracer.WriteLine("match found: {0}", driveName); diff --git a/src/System.Management.Automation/namespaces/NavigationProviderBase.cs b/src/System.Management.Automation/namespaces/NavigationProviderBase.cs index 9bb1e3813b5..42dd3b32b36 100644 --- a/src/System.Management.Automation/namespaces/NavigationProviderBase.cs +++ b/src/System.Management.Automation/namespaces/NavigationProviderBase.cs @@ -432,10 +432,10 @@ protected virtual string GetParentPath(string path, string root) // Check to see if the path is equal to the root // of the virtual drive - if (string.Compare( + if (string.Equals( path, rootPath, - StringComparison.OrdinalIgnoreCase) == 0) + StringComparison.OrdinalIgnoreCase)) { parentPath = string.Empty; } diff --git a/src/System.Management.Automation/namespaces/RegistryProvider.cs b/src/System.Management.Automation/namespaces/RegistryProvider.cs index 5aa8fbc954d..ff8562bcdb9 100644 --- a/src/System.Management.Automation/namespaces/RegistryProvider.cs +++ b/src/System.Management.Automation/namespaces/RegistryProvider.cs @@ -1521,10 +1521,10 @@ private bool ErrorIfDestinationIsSourceOrChildOfSource( { // See if the paths are equal - if (string.Compare( + if (string.Equals( sourcePath, destinationPath, - StringComparison.OrdinalIgnoreCase) == 0) + StringComparison.OrdinalIgnoreCase)) { result = true; break; @@ -1539,10 +1539,10 @@ private bool ErrorIfDestinationIsSourceOrChildOfSource( break; } - if (string.Compare( + if (string.Equals( newDestinationPath, destinationPath, - StringComparison.OrdinalIgnoreCase) == 0) + StringComparison.OrdinalIgnoreCase)) { // We reached the root so the destination must not be a child // of the source @@ -3203,8 +3203,8 @@ private bool IsHiveContainer(string path) } if (string.IsNullOrEmpty(path) || - (string.Compare(path, "\\", StringComparison.OrdinalIgnoreCase) == 0) || - (string.Compare(path, "/", StringComparison.OrdinalIgnoreCase) == 0)) + (string.Equals(path, "\\", StringComparison.OrdinalIgnoreCase)) || + (string.Equals(path, "/", StringComparison.OrdinalIgnoreCase))) { result = true; } diff --git a/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs b/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs index 7c0bf58a5cf..33ef4a0cb9d 100644 --- a/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs +++ b/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs @@ -725,7 +725,7 @@ private static PSSnapInInfo ReadOne(RegistryKey mshSnapInRoot, string mshsnapinI string logPipelineExecutionDetailsStr = ReadStringValue(mshsnapinKey, RegistryStrings.MshSnapin_LogPipelineExecutionDetails, false); if (!string.IsNullOrEmpty(logPipelineExecutionDetailsStr)) { - if (string.Compare("1", logPipelineExecutionDetailsStr, StringComparison.OrdinalIgnoreCase) == 0) + if (string.Equals("1", logPipelineExecutionDetailsStr, StringComparison.OrdinalIgnoreCase)) logPipelineExecutionDetails = true; } From e24c43e728625ff67e3d607f81cb06db94b78bdb Mon Sep 17 00:00:00 2001 From: xtqqczze Date: Fri, 19 Jun 2020 19:01:19 +0100 Subject: [PATCH 4/4] fixup! RCS1235: Optimize method call --- .../CmdletOperation.cs | 4 ++-- src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs | 2 +- .../commands/management/ContentCommandBase.cs | 5 +---- src/System.Management.Automation/DscSupport/CimDSCParser.cs | 2 +- .../namespaces/RegistryProvider.cs | 4 ++-- 5 files changed, 7 insertions(+), 10 deletions(-) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs index f92dd6e8feb..bee7905cc52 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs @@ -234,8 +234,8 @@ public override void WriteObject(object sendToPipeline, XOperationContextBase co CimSetCimInstanceContext setContext = context as CimSetCimInstanceContext; if (setContext != null) { - if ((string.Equals(setContext.ParameterSetName, CimBaseCommand.QueryComputerSet, StringComparison.OrdinalIgnoreCase)) || - (string.Equals(setContext.ParameterSetName, CimBaseCommand.QuerySessionSet, StringComparison.OrdinalIgnoreCase))) + if (string.Equals(setContext.ParameterSetName, CimBaseCommand.QueryComputerSet, StringComparison.OrdinalIgnoreCase) || + string.Equals(setContext.ParameterSetName, CimBaseCommand.QuerySessionSet, StringComparison.OrdinalIgnoreCase)) { this.setCimInstance.SetCimInstance(sendToPipeline as CimInstance, setContext, this); return; diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs index 96a56b8d0c9..10fbc48a444 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs @@ -452,7 +452,7 @@ public static string[] ValidateArgumentIsValidName(string parameterName, string[ foreach (string propertyName in value) { // * is wild char supported in select properties - if ((propertyName != null) && (string.Equals(propertyName.Trim(), "*", StringComparison.OrdinalIgnoreCase))) + if ((propertyName != null) && string.Equals(propertyName.Trim(), "*", StringComparison.OrdinalIgnoreCase)) { continue; } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs index 8de0f59fa16..b595c0195f9 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs @@ -150,13 +150,10 @@ internal void WriteContentObject(object content, long readCount, PathInfo pathIn if (_currentContentItem != null && ((_currentContentItem.PathInfo == pathInfo) || - ( string.Equals( pathInfo.Path, _currentContentItem.PathInfo.Path, - StringComparison.OrdinalIgnoreCase)) - ) - ) + StringComparison.OrdinalIgnoreCase))) { result = _currentContentItem.AttachNotes(result); } diff --git a/src/System.Management.Automation/DscSupport/CimDSCParser.cs b/src/System.Management.Automation/DscSupport/CimDSCParser.cs index 978f6ff4372..58fc81715bb 100644 --- a/src/System.Management.Automation/DscSupport/CimDSCParser.cs +++ b/src/System.Management.Automation/DscSupport/CimDSCParser.cs @@ -1107,7 +1107,7 @@ private static List> FindResourceInCach let cachedClassName = splittedName[IndexClassName] let cachedModuleName = splittedName[IndexModuleName] let cachedResourceName = splittedName[IndexFriendlyName] - where ((string.Equals(cachedResourceName, resourceName, StringComparison.OrdinalIgnoreCase)) + where (string.Equals(cachedResourceName, resourceName, StringComparison.OrdinalIgnoreCase) || (string.Equals(cachedClassName, className, StringComparison.OrdinalIgnoreCase) && string.Equals(cachedModuleName, moduleName, StringComparison.OrdinalIgnoreCase))) select cacheEntry).ToList(); diff --git a/src/System.Management.Automation/namespaces/RegistryProvider.cs b/src/System.Management.Automation/namespaces/RegistryProvider.cs index ff8562bcdb9..ff0f5780771 100644 --- a/src/System.Management.Automation/namespaces/RegistryProvider.cs +++ b/src/System.Management.Automation/namespaces/RegistryProvider.cs @@ -3203,8 +3203,8 @@ private bool IsHiveContainer(string path) } if (string.IsNullOrEmpty(path) || - (string.Equals(path, "\\", StringComparison.OrdinalIgnoreCase)) || - (string.Equals(path, "/", StringComparison.OrdinalIgnoreCase))) + string.Equals(path, "\\", StringComparison.OrdinalIgnoreCase) || + string.Equals(path, "/", StringComparison.OrdinalIgnoreCase)) { result = true; }