using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; public class MyAnalyzer : DiagnosticAnalyzer { public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeMethod, SyntaxKind.MethodDeclaration); } private static void AnalyzeMethod(SyntaxNodeAnalysisContext context) { var method = (MethodDeclarationSyntax)context.Node; var semanticModel = context.SemanticModel; // Get the control flow graph for the method var cfg = semanticModel.AnalyzeControlFlow(method.Body); // Check if any of the statements in the method are unreachable if (cfg.ExitPoints.Count > 0) { foreach (var exitPoint in cfg.ExitPoints) { foreach (var unreachable in exitPoint.Block.DescendantNodes().Where(x => !cfg.Analyze(x).Succeeded)) { context.ReportDiagnostic(Diagnostic.Create("UNREACHABLE", unreachable.GetLocation())); } } } } }
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; public class MyAnalyzer : DiagnosticAnalyzer { public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeMethod, SyntaxKind.MethodDeclaration); } private static void AnalyzeMethod(SyntaxNodeAnalysisContext context) { var method = (MethodDeclarationSyntax)context.Node; var semanticModel = context.SemanticModel; // Get the control flow graph for the method var cfg = semanticModel.AnalyzeControlFlow(method.Body); // Check each assignment statement for potential null reference exceptions foreach (var assignment in method.DescendantNodes().OfTypeIn this example, we first extract the method declaration from the syntax tree, and then use the SemanticModel to analyze its control flow. We then search for any assignment expressions within the method, and for each one, we check whether the left-hand side can potentially be null, and whether the right-hand side can potentially be null and is reachable. If both conditions are met, we create a diagnostic using the provided DiagnosticDescriptor. Package library: Microsoft.CodeAnalysis.CSharp.()) { // Check if the left-hand side of the assignment has a non-null type var lhs = semanticModel.GetTypeInfo(assignment.Left).Type; if (lhs == null || lhs.IsReferenceType) { // Check if the right-hand side of the assignment can be null var rhs = semanticModel.GetSymbolInfo(assignment.Right).Symbol; if (rhs != null && cfg.Analyze(assignment.Right).Succeeded && rhs.CanBeNull()) { context.ReportDiagnostic(Diagnostic.Create("NULL_ASSIGNMENT", assignment.GetLocation())); } } } } }