public static bool IsException( ITypeSymbol typeSymbol, SemanticModel semanticModel) { if (typeSymbol == null) { throw new ArgumentNullException(nameof(typeSymbol)); } if (semanticModel == null) { throw new ArgumentNullException(nameof(semanticModel)); } if (typeSymbol.IsClass()) { INamedTypeSymbol exceptionSymbol = semanticModel.Compilation.GetTypeByMetadataName("System.Exception"); return(typeSymbol .BaseTypesAndSelf() .Any(f => f.Equals(exceptionSymbol))); } return(false); }
// TODO: cater for generics, including in/out - test what CA2016 does in .NET 6 // after upgrading to Microsoft.CodeAnalysis.CSharp.Workspaces 3.x or later, we can convert this method to this single expression // see https://github.com/dotnet/roslyn-analyzers/blob/8236e8bdf092bd9ae21cf42d12b8c480459b5e36/src/Utilities/Compiler/Extensions/ITypeSymbolExtensions.cs#L15-L21 // => fromSymbol != null && toSymbol != null && compilation.ClassifyCommonConversion(fromSymbol, toSymbol).IsImplicit; public static bool IsAssignableTo( this ITypeSymbol fromSymbol, ITypeSymbol toSymbol) => fromSymbol != null && toSymbol != null && fromSymbol.AllInterfaces.Concat(fromSymbol.BaseTypesAndSelf()).Any(candidate => candidate.Equals(toSymbol));