diff --git a/src/Microsoft.CodeAnalysis.Analyzers/CSharp/MetaAnalyzers/CSharpDiagnosticAnalyzerAPIUsageAnalyzer.cs b/src/Microsoft.CodeAnalysis.Analyzers/CSharp/MetaAnalyzers/CSharpDiagnosticAnalyzerAPIUsageAnalyzer.cs index b91061f217..7161d6b841 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/CSharp/MetaAnalyzers/CSharpDiagnosticAnalyzerAPIUsageAnalyzer.cs +++ b/src/Microsoft.CodeAnalysis.Analyzers/CSharp/MetaAnalyzers/CSharpDiagnosticAnalyzerAPIUsageAnalyzer.cs @@ -11,20 +11,17 @@ public class CSharpDiagnosticAnalyzerApiUsageAnalyzer : DiagnosticAnalyzerApiUsa { protected override bool IsNamedTypeDeclarationBlock(SyntaxNode syntax) { - switch (syntax.Kind()) + return syntax.Kind() switch { - case SyntaxKind.ClassDeclaration: + SyntaxKind.ClassDeclaration + or SyntaxKind.StructDeclaration + or SyntaxKind.EnumDeclaration #if CODEANALYSIS_V3_OR_BETTER - case SyntaxKind.RecordDeclaration: + or SyntaxKind.RecordDeclaration: #endif - case SyntaxKind.StructDeclaration: - case SyntaxKind.EnumDeclaration: - case SyntaxKind.InterfaceDeclaration: - return true; - - default: - return false; - } + or SyntaxKind.InterfaceDeclaration => true, + _ => false, + }; } } } diff --git a/src/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/StartActionWithNoRegisteredActionsRuleTests.cs b/src/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/StartActionWithNoRegisteredActionsRuleTests.cs index bce1860a60..aa509b9dad 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/StartActionWithNoRegisteredActionsRuleTests.cs +++ b/src/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/StartActionWithNoRegisteredActionsRuleTests.cs @@ -710,21 +710,13 @@ private static DiagnosticResult GetBasicExpectedDiagnostic(int line, int column, private static string[] GetExpectedArguments(string parameterName, StartActionKind kind) { - string arg2; - switch (kind) + var arg2 = kind switch { - case StartActionKind.CompilationStartAction: - arg2 = "Initialize"; - break; - - case StartActionKind.CodeBlockStartAction: - case StartActionKind.OperationBlockStartAction: - arg2 = "Initialize, CompilationStartAction"; - break; - - default: - throw new ArgumentException("Unsupported action kind", nameof(kind)); - } + StartActionKind.CompilationStartAction => "Initialize", + StartActionKind.CodeBlockStartAction + or StartActionKind.OperationBlockStartAction => "Initialize, CompilationStartAction", + _ => throw new ArgumentException("Unsupported action kind", nameof(kind)), + }; return new[] { parameterName, arg2 }; } diff --git a/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/DoNotRaiseExceptionsInUnexpectedLocations.cs b/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/DoNotRaiseExceptionsInUnexpectedLocations.cs index 54cb807970..d0d093ffba 100644 --- a/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/DoNotRaiseExceptionsInUnexpectedLocations.cs +++ b/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/DoNotRaiseExceptionsInUnexpectedLocations.cs @@ -325,14 +325,13 @@ private static bool IsEqualityOperator(IMethodSymbol method, Compilation compila { if (!method.IsStatic || !method.IsPublic()) return false; - switch (method.Name) + + return method.Name switch { - case WellKnownMemberNames.EqualityOperatorName: - case WellKnownMemberNames.InequalityOperatorName: - return true; - default: - return false; - } + WellKnownMemberNames.EqualityOperatorName + or WellKnownMemberNames.InequalityOperatorName => true, + _ => false, + }; } private static bool IsImplicitCastOperator(IMethodSymbol method, Compilation compilation) diff --git a/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/ImplementIDisposableCorrectly.cs b/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/ImplementIDisposableCorrectly.cs index c6b9d5c101..c494952eb2 100644 --- a/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/ImplementIDisposableCorrectly.cs +++ b/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/ImplementIDisposableCorrectly.cs @@ -671,21 +671,14 @@ private bool ValidateOperations(ImmutableArray operations) private bool ValidateOperation(IOperation operation) { - switch (operation.Kind) - { - case OperationKind.Empty: - case OperationKind.Labeled: - return true; - case OperationKind.Block: - return ValidateOperations(((IBlockOperation)operation).Operations); - case OperationKind.ExpressionStatement: - return ValidateExpression((IExpressionStatementOperation)operation); - case OperationKind.Try: - return ValidateTryOperation((ITryOperation)operation); - default: - // Ignore operation roots with no IOperation API support (OperationKind.None) - return operation.IsOperationNoneRoot(); - } + return operation.Kind switch + { + OperationKind.Empty or OperationKind.Labeled => true, + OperationKind.Block => ValidateOperations(((IBlockOperation)operation).Operations), + OperationKind.ExpressionStatement => ValidateExpression((IExpressionStatementOperation)operation), + OperationKind.Try => ValidateTryOperation((ITryOperation)operation), + _ => operation.IsOperationNoneRoot(),// Ignore operation roots with no IOperation API support (OperationKind.None) + }; } private bool ValidateExpression(IExpressionStatementOperation expressionStatement) diff --git a/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/OperatorOverloadsHaveNamedAlternates.cs b/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/OperatorOverloadsHaveNamedAlternates.cs index e646f3b915..1c212619f4 100644 --- a/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/OperatorOverloadsHaveNamedAlternates.cs +++ b/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/OperatorOverloadsHaveNamedAlternates.cs @@ -176,14 +176,11 @@ private static Diagnostic CreateDiagnostic(DiagnosticDescriptor descriptor, Loca internal static bool IsPropertyExpected(string operatorName) { - switch (operatorName) + return operatorName switch { - case OpTrueText: - case OpFalseText: - return true; - default: - return false; - } + OpTrueText or OpFalseText => true, + _ => false, + }; } internal static ExpectedAlternateMethodGroup? GetExpectedAlternateMethodGroup(string operatorName, ITypeSymbol returnType, ITypeSymbol? parameterType) @@ -192,71 +189,47 @@ internal static bool IsPropertyExpected(string operatorName) // the most common case; create a static method with the already specified types static ExpectedAlternateMethodGroup createSingle(string methodName) => new(methodName); - switch (operatorName) + return operatorName switch { - case "op_Addition": - case "op_AdditonAssignment": - return createSingle("Add"); - case "op_BitwiseAnd": - case "op_BitwiseAndAssignment": - return createSingle("BitwiseAnd"); - case "op_BitwiseOr": - case "op_BitwiseOrAssignment": - return createSingle("BitwiseOr"); - case "op_Decrement": - return createSingle("Decrement"); - case "op_Division": - case "op_DivisionAssignment": - return createSingle("Divide"); - case "op_Equality": - case "op_Inequality": - return createSingle("Equals"); - case "op_ExclusiveOr": - case "op_ExclusiveOrAssignment": - return createSingle("Xor"); - case "op_GreaterThan": - case "op_GreaterThanOrEqual": - case "op_LessThan": - case "op_LessThanOrEqual": - return new ExpectedAlternateMethodGroup(alternateMethod1: "CompareTo", alternateMethod2: "Compare"); - case "op_Increment": - return createSingle("Increment"); - case "op_LeftShift": - case "op_LeftShiftAssignment": - return createSingle("LeftShift"); - case "op_LogicalAnd": - return createSingle("LogicalAnd"); - case "op_LogicalOr": - return createSingle("LogicalOr"); - case "op_LogicalNot": - return createSingle("LogicalNot"); - case "op_Modulus": - case "op_ModulusAssignment": - return new ExpectedAlternateMethodGroup(alternateMethod1: "Mod", alternateMethod2: "Remainder"); - case "op_MultiplicationAssignment": - case "op_Multiply": - return createSingle("Multiply"); - case "op_OnesComplement": - return createSingle("OnesComplement"); - case "op_RightShift": - case "op_RightShiftAssignment": - case "op_SignedRightShift": - case "op_UnsignedRightShift": - case "op_UnsignedRightShiftAssignment": - return createSingle("RightShift"); - case "op_Subtraction": - case "op_SubtractionAssignment": - return createSingle("Subtract"); - case "op_UnaryNegation": - return createSingle("Negate"); - case "op_UnaryPlus": - return createSingle("Plus"); - case "op_Implicit": - case "op_Explicit": - return new ExpectedAlternateMethodGroup(alternateMethod1: $"To{GetTypeName(returnType)}", alternateMethod2: parameterType != null ? $"From{GetTypeName(parameterType)}" : null); - default: - return null; - } + "op_Addition" + or "op_AdditonAssignment" => createSingle("Add"), + "op_BitwiseAnd" + or "op_BitwiseAndAssignment" => createSingle("BitwiseAnd"), + "op_BitwiseOr" + or "op_BitwiseOrAssignment" => createSingle("BitwiseOr"), + "op_Decrement" => createSingle("Decrement"), + "op_Division" + or "op_DivisionAssignment" => createSingle("Divide"), + "op_Equality" + or "op_Inequality" => createSingle("Equals"), + "op_ExclusiveOr" + or "op_ExclusiveOrAssignment" => createSingle("Xor"), + "op_GreaterThan" + or "op_GreaterThanOrEqual" or "op_LessThan" or "op_LessThanOrEqual" => new ExpectedAlternateMethodGroup(alternateMethod1: "CompareTo", alternateMethod2: "Compare"), + "op_Increment" => createSingle("Increment"), + "op_LeftShift" + or "op_LeftShiftAssignment" => createSingle("LeftShift"), + "op_LogicalAnd" => createSingle("LogicalAnd"), + "op_LogicalOr" => createSingle("LogicalOr"), + "op_LogicalNot" => createSingle("LogicalNot"), + "op_Modulus" + or "op_ModulusAssignment" => new ExpectedAlternateMethodGroup(alternateMethod1: "Mod", alternateMethod2: "Remainder"), + "op_MultiplicationAssignment" + or "op_Multiply" => createSingle("Multiply"), + "op_OnesComplement" => createSingle("OnesComplement"), + "op_RightShift" + or "op_RightShiftAssignment" + or "op_SignedRightShift" + or "op_UnsignedRightShift" + or "op_UnsignedRightShiftAssignment" => createSingle("RightShift"), + "op_Subtraction" + or "op_SubtractionAssignment" => createSingle("Subtract"), + "op_UnaryNegation" => createSingle("Negate"), + "op_UnaryPlus" => createSingle("Plus"), + "op_Implicit" + or "op_Explicit" => new ExpectedAlternateMethodGroup(alternateMethod1: $"To{GetTypeName(returnType)}", alternateMethod2: parameterType != null ? $"From{GetTypeName(parameterType)}" : null), + _ => null, + }; static string GetTypeName(ITypeSymbol typeSymbol) { diff --git a/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/Maintainability/CodeMetricsAnalyzer.cs b/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/Maintainability/CodeMetricsAnalyzer.cs index 6bae1da363..169b26bfad 100644 --- a/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/Maintainability/CodeMetricsAnalyzer.cs +++ b/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/Maintainability/CodeMetricsAnalyzer.cs @@ -251,45 +251,22 @@ void analyzeMetricsData(CodeAnalysisMetricData codeAnalysisMetricData) static bool isApplicableByDefault(string ruleId, SymbolKind symbolKind) { - switch (ruleId) + return ruleId switch { - case CA1501RuleId: - return symbolKind == SymbolKind.NamedType; - - case CA1502RuleId: - return symbolKind == SymbolKind.Method; - - case CA1505RuleId: - switch (symbolKind) - { - case SymbolKind.NamedType: - case SymbolKind.Method: - case SymbolKind.Field: - case SymbolKind.Property: - case SymbolKind.Event: - return true; - - default: - return false; - } - - case CA1506RuleId: - switch (symbolKind) - { - case SymbolKind.NamedType: - case SymbolKind.Method: - case SymbolKind.Field: - case SymbolKind.Property: - case SymbolKind.Event: - return true; - - default: - return false; - } - - default: - throw new NotImplementedException(); - } + CA1501RuleId => symbolKind == SymbolKind.NamedType, + CA1502RuleId => symbolKind == SymbolKind.Method, + CA1505RuleId => symbolKind switch + { + SymbolKind.NamedType or SymbolKind.Method or SymbolKind.Field or SymbolKind.Property or SymbolKind.Event => true, + _ => false, + }, + CA1506RuleId => symbolKind switch + { + SymbolKind.NamedType or SymbolKind.Method or SymbolKind.Field or SymbolKind.Property or SymbolKind.Event => true, + _ => false, + }, + _ => throw new NotImplementedException(), + }; } static uint? getDefaultThreshold(string ruleId, SymbolKind symbolKind) diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/DoNotLockOnObjectsWithWeakIdentity.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/DoNotLockOnObjectsWithWeakIdentity.cs index 1bae67fdb7..597363028f 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/DoNotLockOnObjectsWithWeakIdentity.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/DoNotLockOnObjectsWithWeakIdentity.cs @@ -123,26 +123,24 @@ private static bool TypeHasWeakIdentity(ITypeSymbol type, Compilation compilatio public static bool IsPrimitiveType(ITypeSymbol type) { - switch (type.SpecialType) + return type.SpecialType switch { - case SpecialType.System_Boolean: - case SpecialType.System_Byte: - case SpecialType.System_Char: - case SpecialType.System_Double: - case SpecialType.System_Int16: - case SpecialType.System_Int32: - case SpecialType.System_Int64: - case SpecialType.System_UInt16: - case SpecialType.System_UInt32: - case SpecialType.System_UInt64: - case SpecialType.System_IntPtr: - case SpecialType.System_UIntPtr: - case SpecialType.System_SByte: - case SpecialType.System_Single: - return true; - default: - return false; - } + SpecialType.System_Boolean + or SpecialType.System_Byte + or SpecialType.System_Char + or SpecialType.System_Double + or SpecialType.System_Int16 + or SpecialType.System_Int32 + or SpecialType.System_Int64 + or SpecialType.System_UInt16 + or SpecialType.System_UInt32 + or SpecialType.System_UInt64 + or SpecialType.System_IntPtr + or SpecialType.System_UIntPtr + or SpecialType.System_SByte + or SpecialType.System_Single => true, + _ => false, + }; } } } diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/DoNotUseEnumerableMethodsOnIndexableCollectionsInsteadUseTheCollectionDirectly.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/DoNotUseEnumerableMethodsOnIndexableCollectionsInsteadUseTheCollectionDirectly.cs index f5dfb310a6..e5d7ac421c 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/DoNotUseEnumerableMethodsOnIndexableCollectionsInsteadUseTheCollectionDirectly.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/DoNotUseEnumerableMethodsOnIndexableCollectionsInsteadUseTheCollectionDirectly.cs @@ -147,18 +147,12 @@ private static bool IsSingleParameterLinqMethod(IMethodSymbol methodSymbol, ITyp private static bool IsPossibleLinqInvocation(IInvocationOperation invocation, bool excludeOrDefaultMethods) { - switch (invocation.TargetMethod.Name) + return invocation.TargetMethod.Name switch { - case "Last": - case "First": - case "Count": - return true; - case "LastOrDefault": - case "FirstOrDefault": - return !excludeOrDefaultMethods; - default: - return false; - } + "Last" or "First" or "Count" => true, + "LastOrDefault" or "FirstOrDefault" => !excludeOrDefaultMethods, + _ => false, + }; } } } \ No newline at end of file diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/SerializationRulesDiagnosticAnalyzer.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/SerializationRulesDiagnosticAnalyzer.cs index ae140e88b6..a113a943d3 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/SerializationRulesDiagnosticAnalyzer.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/SerializationRulesDiagnosticAnalyzer.cs @@ -284,33 +284,17 @@ private bool IsSerializable(ITypeSymbol type) return true; } - switch (type.TypeKind) + return type.TypeKind switch { - case TypeKind.Array: - return IsSerializable(((IArrayTypeSymbol)type).ElementType); - - case TypeKind.Enum: - return IsSerializable(((INamedTypeSymbol)type).EnumUnderlyingType); - - case TypeKind.TypeParameter: - case TypeKind.Interface: - // The concrete type can't be determined statically, - // so we assume true to cut down on noise. - return true; - - case TypeKind.Class: - case TypeKind.Struct: - // Check SerializableAttribute or Serializable flag from metadata. - return ((INamedTypeSymbol)type).IsSerializable; - - case TypeKind.Delegate: - // delegates are always serializable, even if - // they aren't actually marked [Serializable] - return true; - - default: - return type.GetAttributes().Any(a => a.AttributeClass.Equals(_serializableAttributeTypeSymbol)); - } + TypeKind.Array => IsSerializable(((IArrayTypeSymbol)type).ElementType), + TypeKind.Enum => IsSerializable(((INamedTypeSymbol)type).EnumUnderlyingType), + TypeKind.TypeParameter or TypeKind.Interface => true,// The concrete type can't be determined statically, + // so we assume true to cut down on noise. + TypeKind.Class or TypeKind.Struct => ((INamedTypeSymbol)type).IsSerializable,// Check SerializableAttribute or Serializable flag from metadata. + TypeKind.Delegate => true,// delegates are always serializable, even if + // they aren't actually marked [Serializable] + _ => type.GetAttributes().Any(a => a.AttributeClass.Equals(_serializableAttributeTypeSymbol)), + }; } } } diff --git a/src/PublicApiAnalyzers/Core/Analyzers/DeclarePublicApiAnalyzer.Impl.cs b/src/PublicApiAnalyzers/Core/Analyzers/DeclarePublicApiAnalyzer.Impl.cs index 1d8a303bfd..ca6cb22eda 100644 --- a/src/PublicApiAnalyzers/Core/Analyzers/DeclarePublicApiAnalyzer.Impl.cs +++ b/src/PublicApiAnalyzers/Core/Analyzers/DeclarePublicApiAnalyzer.Impl.cs @@ -735,21 +735,16 @@ private bool IsPublicAPI(ISymbol symbol) private bool IsPublicApiCore(ISymbol symbol) { - switch (symbol.DeclaredAccessibility) - { - case Accessibility.Public: - return symbol.ContainingType == null || IsPublicApiCore(symbol.ContainingType); - case Accessibility.Protected: - case Accessibility.ProtectedOrInternal: - // Protected symbols must have parent types (that is, top-level protected - // symbols are not allowed. - return - symbol.ContainingType != null && - IsPublicApiCore(symbol.ContainingType) && - CanTypeBeExtendedPublicly(symbol.ContainingType); - default: - return false; - } + return symbol.DeclaredAccessibility switch + { + Accessibility.Public => symbol.ContainingType == null || IsPublicApiCore(symbol.ContainingType), + Accessibility.Protected + or Accessibility.ProtectedOrInternal => symbol.ContainingType != null + && IsPublicApiCore(symbol.ContainingType) + && CanTypeBeExtendedPublicly(symbol.ContainingType),// Protected symbols must have parent types (that is, top-level protected + // symbols are not allowed. + _ => false, + }; } private bool CanTypeBeExtendedPublicly(ITypeSymbol type) diff --git a/src/Roslyn.Diagnostics.Analyzers/CSharp/CSharpSpecializedEnumerableCreationAnalyzer.cs b/src/Roslyn.Diagnostics.Analyzers/CSharp/CSharpSpecializedEnumerableCreationAnalyzer.cs index 4f87563ed1..f59aa91345 100644 --- a/src/Roslyn.Diagnostics.Analyzers/CSharp/CSharpSpecializedEnumerableCreationAnalyzer.cs +++ b/src/Roslyn.Diagnostics.Analyzers/CSharp/CSharpSpecializedEnumerableCreationAnalyzer.cs @@ -64,16 +64,13 @@ public void AnalyzeNode(SyntaxNodeAnalysisContext context) private bool ShouldAnalyzeExpression(SyntaxNode expression, SemanticModel semanticModel, CancellationToken cancellationToken) { - switch (expression.Kind()) + return (expression.Kind()) switch { - case SyntaxKind.ArrayCreationExpression: - case SyntaxKind.ImplicitArrayCreationExpression: - return ShouldAnalyzeArrayCreationExpression(expression, semanticModel, cancellationToken); - case SyntaxKind.SimpleMemberAccessExpression: - return true; - default: - return false; - } + SyntaxKind.ArrayCreationExpression + or SyntaxKind.ImplicitArrayCreationExpression => ShouldAnalyzeArrayCreationExpression(expression, semanticModel, cancellationToken), + SyntaxKind.SimpleMemberAccessExpression => true, + _ => false, + }; } private static void AnalyzeArrayCreationExpression(ArrayCreationExpressionSyntax arrayCreationExpression, Action addDiagnostic) diff --git a/src/Utilities/Compiler/CodeMetrics/MetricsHelper.cs b/src/Utilities/Compiler/CodeMetrics/MetricsHelper.cs index f4987c79a8..2fc2ae3c01 100644 --- a/src/Utilities/Compiler/CodeMetrics/MetricsHelper.cs +++ b/src/Utilities/Compiler/CodeMetrics/MetricsHelper.cs @@ -321,34 +321,31 @@ private static void AddCoupledNamedTypesCore(ImmutableHashSet. static bool isIgnoreableType(INamedTypeSymbol namedType, WellKnownTypeProvider wellKnownTypeProvider) { - switch (namedType.SpecialType) + return namedType.SpecialType switch { - case SpecialType.System_Boolean: - case SpecialType.System_Byte: - case SpecialType.System_Char: - case SpecialType.System_Double: - case SpecialType.System_Int16: - case SpecialType.System_Int32: - case SpecialType.System_Int64: - case SpecialType.System_UInt16: - case SpecialType.System_UInt32: - case SpecialType.System_UInt64: - case SpecialType.System_IntPtr: - case SpecialType.System_UIntPtr: - case SpecialType.System_SByte: - case SpecialType.System_Single: - case SpecialType.System_String: - case SpecialType.System_Object: - case SpecialType.System_ValueType: - case SpecialType.System_Void: - return true; - - default: - return namedType.IsAnonymousType || - namedType.GetAttributes().Any(a => - a.AttributeClass.Equals(wellKnownTypeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeCompilerServicesCompilerGeneratedAttribute)) || - a.AttributeClass.Equals(wellKnownTypeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCodeDomCompilerGeneratedCodeAttribute))); - } + SpecialType.System_Boolean + or SpecialType.System_Byte + or SpecialType.System_Char + or SpecialType.System_Double + or SpecialType.System_Int16 + or SpecialType.System_Int32 + or SpecialType.System_Int64 + or SpecialType.System_UInt16 + or SpecialType.System_UInt32 + or SpecialType.System_UInt64 + or SpecialType.System_IntPtr + or SpecialType.System_UIntPtr + or SpecialType.System_SByte + or SpecialType.System_Single + or SpecialType.System_String + or SpecialType.System_Object + or SpecialType.System_ValueType + or SpecialType.System_Void => true, + _ => namedType.IsAnonymousType + || namedType.GetAttributes().Any(a => + a.AttributeClass.Equals(wellKnownTypeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeCompilerServicesCompilerGeneratedAttribute)) || + a.AttributeClass.Equals(wellKnownTypeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCodeDomCompilerGeneratedCodeAttribute))), + }; } } diff --git a/src/Utilities/Compiler/Extensions/IMethodSymbolExtensions.cs b/src/Utilities/Compiler/Extensions/IMethodSymbolExtensions.cs index 76f0c26ca2..abecc85421 100644 --- a/src/Utilities/Compiler/Extensions/IMethodSymbolExtensions.cs +++ b/src/Utilities/Compiler/Extensions/IMethodSymbolExtensions.cs @@ -563,29 +563,20 @@ public static bool IsTaskConfigureAwaitMethod(this IMethodSymbol method, [NotNul public static bool IsLambdaOrLocalFunctionOrDelegate(this IMethodSymbol method) { - switch (method.MethodKind) + return method.MethodKind switch { - case MethodKind.LambdaMethod: - case MethodKindEx.LocalFunction: - case MethodKind.DelegateInvoke: - return true; - - default: - return false; - } + MethodKind.LambdaMethod or MethodKindEx.LocalFunction or MethodKind.DelegateInvoke => true, + _ => false, + }; } public static bool IsLambdaOrLocalFunction(this IMethodSymbol method) { - switch (method.MethodKind) + return method.MethodKind switch { - case MethodKind.LambdaMethod: - case MethodKindEx.LocalFunction: - return true; - - default: - return false; - } + MethodKind.LambdaMethod or MethodKindEx.LocalFunction => true, + _ => false, + }; } public static int GetParameterIndex(this IMethodSymbol methodSymbol, IParameterSymbol parameterSymbol) diff --git a/src/Utilities/Compiler/Extensions/IOperationExtensions.cs b/src/Utilities/Compiler/Extensions/IOperationExtensions.cs index f835471a85..56765efd76 100644 --- a/src/Utilities/Compiler/Extensions/IOperationExtensions.cs +++ b/src/Utilities/Compiler/Extensions/IOperationExtensions.cs @@ -373,21 +373,18 @@ public static bool HasAnyOperationDescendant(this ImmutableArray ope /// public static bool IsComparisonOperator(this IBinaryOperation binaryOperation) { - switch (binaryOperation.OperatorKind) + return binaryOperation.OperatorKind switch { - case BinaryOperatorKind.Equals: - case BinaryOperatorKind.NotEquals: - case BinaryOperatorKind.ObjectValueEquals: - case BinaryOperatorKind.ObjectValueNotEquals: - case BinaryOperatorKind.LessThan: - case BinaryOperatorKind.LessThanOrEqual: - case BinaryOperatorKind.GreaterThan: - case BinaryOperatorKind.GreaterThanOrEqual: - return true; - - default: - return false; - } + BinaryOperatorKind.Equals + or BinaryOperatorKind.NotEquals + or BinaryOperatorKind.ObjectValueEquals + or BinaryOperatorKind.ObjectValueNotEquals + or BinaryOperatorKind.LessThan + or BinaryOperatorKind.LessThanOrEqual + or BinaryOperatorKind.GreaterThan + or BinaryOperatorKind.GreaterThanOrEqual => true, + _ => false, + }; } public static IOperation GetRoot(this IOperation operation) diff --git a/src/Utilities/Compiler/Extensions/ITypeSymbolExtensions.cs b/src/Utilities/Compiler/Extensions/ITypeSymbolExtensions.cs index 5ea79aaeb9..006f35f174 100644 --- a/src/Utilities/Compiler/Extensions/ITypeSymbolExtensions.cs +++ b/src/Utilities/Compiler/Extensions/ITypeSymbolExtensions.cs @@ -14,25 +14,23 @@ internal static class ITypeSymbolExtensions { public static bool IsPrimitiveType(this ITypeSymbol type) { - switch (type.SpecialType) + return type.SpecialType switch { - case SpecialType.System_Boolean: - case SpecialType.System_Byte: - case SpecialType.System_Char: - case SpecialType.System_Double: - case SpecialType.System_Int16: - case SpecialType.System_Int32: - case SpecialType.System_Int64: - case SpecialType.System_UInt16: - case SpecialType.System_UInt32: - case SpecialType.System_UInt64: - case SpecialType.System_SByte: - case SpecialType.System_Single: - case SpecialType.System_String: - return true; - default: - return false; - } + SpecialType.System_Boolean + or SpecialType.System_Byte + or SpecialType.System_Char + or SpecialType.System_Double + or SpecialType.System_Int16 + or SpecialType.System_Int32 + or SpecialType.System_Int64 + or SpecialType.System_UInt16 + or SpecialType.System_UInt32 + or SpecialType.System_UInt64 + or SpecialType.System_SByte + or SpecialType.System_Single + or SpecialType.System_String => true, + _ => false, + }; } public static bool Inherits([NotNullWhen(returnValue: true)] this ITypeSymbol? type, [NotNullWhen(returnValue: true)] ITypeSymbol? possibleBase) @@ -60,11 +58,11 @@ public static bool Inherits([NotNullWhen(returnValue: true)] this ITypeSymbol? t } } - public static IEnumerable GetBaseTypes(this ITypeSymbol type, Func? takeWilePredicate = null) + public static IEnumerable GetBaseTypes(this ITypeSymbol type, Func? takeWhilePredicate = null) { INamedTypeSymbol current = type.BaseType; while (current != null && - (takeWilePredicate == null || takeWilePredicate(current))) + (takeWhilePredicate == null || takeWhilePredicate(current))) { yield return current; current = current.BaseType; diff --git a/src/Utilities/Compiler/WellKnownTypeProvider.cs b/src/Utilities/Compiler/WellKnownTypeProvider.cs index 3b5826e519..6dc397d5d8 100644 --- a/src/Utilities/Compiler/WellKnownTypeProvider.cs +++ b/src/Utilities/Compiler/WellKnownTypeProvider.cs @@ -257,33 +257,22 @@ private static bool IsIdentifierPartCharacter(char ch) //// || IsCombiningChar(cat) //// || IsFormattingChar(cat); - switch (cat) + return cat switch { // Letter - case UnicodeCategory.UppercaseLetter: - case UnicodeCategory.LowercaseLetter: - case UnicodeCategory.TitlecaseLetter: - case UnicodeCategory.ModifierLetter: - case UnicodeCategory.OtherLetter: - case UnicodeCategory.LetterNumber: - - // DecimalDigit - case UnicodeCategory.DecimalDigitNumber: - - // ConnectingChar - case UnicodeCategory.ConnectorPunctuation: - - // CombiningChar - case UnicodeCategory.NonSpacingMark: - case UnicodeCategory.SpacingCombiningMark: - - // FormattingChar - case UnicodeCategory.Format: - return true; - - default: - return false; - } + UnicodeCategory.UppercaseLetter + or UnicodeCategory.LowercaseLetter + or UnicodeCategory.TitlecaseLetter + or UnicodeCategory.ModifierLetter + or UnicodeCategory.OtherLetter + or UnicodeCategory.LetterNumber + or UnicodeCategory.DecimalDigitNumber + or UnicodeCategory.ConnectorPunctuation + or UnicodeCategory.NonSpacingMark + or UnicodeCategory.SpacingCombiningMark + or UnicodeCategory.Format => true, + _ => false, + }; } private static bool IsSubsetOfCollection(ImmutableArray set1, ICollection set2) diff --git a/src/Utilities/Compiler/WordParser.cs b/src/Utilities/Compiler/WordParser.cs index d286940cf2..de90a4ddf7 100644 --- a/src/Utilities/Compiler/WordParser.cs +++ b/src/Utilities/Compiler/WordParser.cs @@ -650,40 +650,22 @@ private static bool IsDigit(char c) private static bool IsHexDigit(char c) { - switch (c) + return c switch { - case 'A': - case 'a': - case 'B': - case 'b': - case 'C': - case 'c': - case 'D': - case 'd': - case 'E': - case 'e': - case 'F': - case 'f': - return true; - } - - return IsDigit(c); + 'A' or 'a' or 'B' or 'b' or 'C' or 'c' or 'D' or 'd' or 'E' or 'e' or 'F' or 'f' => true, + _ => IsDigit(c), + }; } private static bool IsIntraWordPunctuation(char c) { // Don't be tempted to add En dash and Em dash to this // list, as these should be treated as word delimiters. - switch (c) + return c switch { - case '-': - case '\u00AD': // Soft hyphen - case '\'': - case '\u2019': // Right Single Quotation Mark - return true; - } - - return false; + '-' or '\u00AD' or '\'' or '\u2019' => true, + _ => false, + }; } } } diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/CopyAnalysis/CopyAbstractValueKind.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/CopyAnalysis/CopyAbstractValueKind.cs index ff585a7cc9..45a6f25330 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/CopyAnalysis/CopyAbstractValueKind.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/CopyAnalysis/CopyAbstractValueKind.cs @@ -37,15 +37,12 @@ internal static class CopyAbstractValueKindExtensions { public static bool IsKnown(this CopyAbstractValueKind kind) { - switch (kind) + return kind switch { - case CopyAbstractValueKind.KnownValueCopy: - case CopyAbstractValueKind.KnownReferenceCopy: - return true; - - default: - return false; - } + CopyAbstractValueKind.KnownValueCopy + or CopyAbstractValueKind.KnownReferenceCopy => true, + _ => false, + }; } public static CopyAbstractValueKind MergeIfBothKnown(this CopyAbstractValueKind kind, CopyAbstractValueKind kindToMerge) diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/PointsToAnalysis.PointsToDataFlowOperationVisitor.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/PointsToAnalysis.PointsToDataFlowOperationVisitor.cs index 882d852562..5d844aa093 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/PointsToAnalysis.PointsToDataFlowOperationVisitor.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/PointsToAnalysis.PointsToDataFlowOperationVisitor.cs @@ -380,15 +380,12 @@ private protected override PointsToAbstractValue GetAbstractValueForImplicitWrap #region Predicate analysis private static bool IsValidValueForPredicateAnalysis(NullAbstractValue value) { - switch (value) + return value switch { - case NullAbstractValue.Null: - case NullAbstractValue.NotNull: - return true; - - default: - return false; - } + NullAbstractValue.Null + or NullAbstractValue.NotNull => true, + _ => false, + }; } protected override PredicateValueKind SetValueForEqualsOrNotEqualsComparisonOperator( @@ -1016,15 +1013,12 @@ private NullAbstractValue GetNullStateBasedOnInstanceOrReferenceValue(IOperation } NullAbstractValue referenceOrInstanceValue = referenceOrInstance != null ? GetNullAbstractValue(referenceOrInstance) : NullAbstractValue.NotNull; - switch (referenceOrInstanceValue) + return referenceOrInstanceValue switch { - case NullAbstractValue.Invalid: - case NullAbstractValue.Null: - return referenceOrInstanceValue; - - default: - return defaultValue; - } + NullAbstractValue.Invalid + or NullAbstractValue.Null => referenceOrInstanceValue, + _ => defaultValue, + }; } private PointsToAbstractValue GetValueBasedOnInstanceOrReferenceValue(IOperation? referenceOrInstance, IOperation operation, PointsToAbstractValue defaultValue) diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AnalysisEntity.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AnalysisEntity.cs index d4067ee567..4916cdae4f 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AnalysisEntity.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AnalysisEntity.cs @@ -197,16 +197,13 @@ public bool HasUnknownInstanceLocation { get { - switch (InstanceLocation.Kind) + return InstanceLocation.Kind switch { - case PointsToAbstractValueKind.Unknown: - case PointsToAbstractValueKind.UnknownNull: - case PointsToAbstractValueKind.UnknownNotNull: - return true; - - default: - return false; - } + PointsToAbstractValueKind.Unknown + or PointsToAbstractValueKind.UnknownNull + or PointsToAbstractValueKind.UnknownNotNull => true, + _ => false, + }; } } diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/DataFlowOperationVisitor.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/DataFlowOperationVisitor.cs index a54f4e1f4e..d19d4deb3f 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/DataFlowOperationVisitor.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/DataFlowOperationVisitor.cs @@ -1647,7 +1647,7 @@ private void PerformPredicateAnalysisCore(IOperation operation, TAnalysisData ta PerformPredicateAnalysisCore(parenthesizedOperation.Operand, targetAnalysisData); return; - case IFlowCaptureReferenceOperation _: + case IFlowCaptureReferenceOperation: var result = AnalysisEntityFactory.TryCreate(operation, out AnalysisEntity? flowCaptureReferenceEntity); Debug.Assert(result); RoslynDebug.Assert(flowCaptureReferenceEntity != null); diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/MapAbstractDomain.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/MapAbstractDomain.cs index 2dc5e36027..3fae3504dc 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/MapAbstractDomain.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/MapAbstractDomain.cs @@ -55,7 +55,7 @@ private int Compare(DictionaryAnalysisData oldValue, DictionaryAna { var key = kvp.Key; var value = kvp.Value; - if (!newValue.TryGetValue(key, out TValue otherValue)) + if (!newValue.TryGetValue(key, out var otherValue)) { FireNonMonotonicAssertIfNeeded(assertMonotonicity); return 1; @@ -98,7 +98,7 @@ public override DictionaryAnalysisData Merge(DictionaryAnalysisDat var result = new DictionaryAnalysisData(value1); foreach (var entry in value2) { - if (result.TryGetValue(entry.Key, out TValue value)) + if (result.TryGetValue(entry.Key, out var value)) { value = ValueDomain.Merge(value, entry.Value); diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/PredicatedAnalysisData.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/PredicatedAnalysisData.cs index e5e677779f..d266d41ed0 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/PredicatedAnalysisData.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/PredicatedAnalysisData.cs @@ -414,7 +414,7 @@ protected static bool EqualsHelper(DictionaryAnalysisData? dict1, return false; } - return dict1.Keys.All(key => dict2.TryGetValue(key, out TValue value2) && + return dict1.Keys.All(key => dict2.TryGetValue(key, out var value2) && EqualityComparer.Default.Equals(dict1[key], value2)); } diff --git a/src/Utilities/FlowAnalysis/Options/DisposeAnalysisKind.cs b/src/Utilities/FlowAnalysis/Options/DisposeAnalysisKind.cs index 8106a3eb07..4434937a22 100644 --- a/src/Utilities/FlowAnalysis/Options/DisposeAnalysisKind.cs +++ b/src/Utilities/FlowAnalysis/Options/DisposeAnalysisKind.cs @@ -49,28 +49,22 @@ public static bool AreExceptionPathsAndMayBeNotDisposedViolationsEnabled(this Di public static bool AreExceptionPathsEnabled(this DisposeAnalysisKind disposeAnalysisKind) { - switch (disposeAnalysisKind) + return disposeAnalysisKind switch { - case DisposeAnalysisKind.NonExceptionPaths: - case DisposeAnalysisKind.NonExceptionPathsOnlyNotDisposed: - return false; - - default: - return true; - } + DisposeAnalysisKind.NonExceptionPaths + or DisposeAnalysisKind.NonExceptionPathsOnlyNotDisposed => false, + _ => true, + }; } public static bool AreMayBeNotDisposedViolationsEnabled(this DisposeAnalysisKind disposeAnalysisKind) { - switch (disposeAnalysisKind) + return disposeAnalysisKind switch { - case DisposeAnalysisKind.AllPathsOnlyNotDisposed: - case DisposeAnalysisKind.NonExceptionPathsOnlyNotDisposed: - return false; - - default: - return true; - } + DisposeAnalysisKind.AllPathsOnlyNotDisposed + or DisposeAnalysisKind.NonExceptionPathsOnlyNotDisposed => false, + _ => true, + }; } } }