using System.Diagnostics.CodeAnalysis; using System.Linq; static void Main(string[] args) { var bag = new DiagnosticBag(); bag.ReportDiagnostic(Diagnostic.Create( new DiagnosticDescriptor("MyDiagnostic", "MyDiagnostic", "MyDiagnostic", "MyDiagnostic", DiagnosticSeverity.Error, true), Location.None)); var diagnostics = bag.AsEnumerable().ToList(); foreach (var diagnostic in diagnostics) { Console.WriteLine(diagnostic.Id); } }
using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; class MyAnalyzer { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class MyDiagnosticAnalyzer : DiagnosticAnalyzer { public override ImmutableArrayThis code demonstrates how the DiagnosticBag class can be used in the context of a custom diagnostic analyzer. It defines a simple diagnostic analyzer that reports an error diagnostic for every variable declaration statement in a C# code file. Then, it loads the analyzer assembly, creates an instance of the analyzer, and uses it to analyze a syntax tree containing a single variable declaration statement. Finally, it calls AsEnumerable to get all the diagnostics reported by the analyzer and enumerates over them using a foreach loop. In this case, it prints out the diagnostic message, which is "MyDiagnostic". It is difficult to determine the package library without further details on the code context. The DiagnosticBag is a part of the System.Diagnostics.CodeAnalysis namespace in C# and is included in the .NET Core runtime libraries.SupportedDiagnostics { get { return ImmutableArray.Create(MyDiagnosticDescriptor); } } private static readonly DiagnosticDescriptor MyDiagnosticDescriptor = new DiagnosticDescriptor( "MyDiagnostic", "MyDiagnostic", "MyDiagnostic", "MyDiagnostic", DiagnosticSeverity.Error, true); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.VariableDeclaration); } private void AnalyzeNode(SyntaxNodeAnalysisContext context) { context.ReportDiagnostic(Diagnostic.Create(MyDiagnosticDescriptor, context.Node.GetLocation())); } } } static void Main(string[] args) { var assembly = Assembly.LoadFrom(@"C:\MyAnalyzer.dll"); var analyzerType = assembly.GetTypes().FirstOrDefault(t => typeof(DiagnosticAnalyzer).IsAssignableFrom(t)); var analyzer = (DiagnosticAnalyzer)Activator.CreateInstance(analyzerType); var diagnostics = new DiagnosticBag(); var compilation = CSharpCompilation.Create("MyCompilation") .WithAnalyzers(ImmutableArray.Create(analyzer)) .WithErrorReportingDiagnostics(diagnostics); var syntaxTree = CSharpSyntaxTree.ParseText("var x = 42;"); var result = compilation.AddSyntaxTrees(syntaxTree).GetDiagnostics(); foreach (var diagnostic in diagnostics.AsEnumerable()) { Console.WriteLine(diagnostic.GetMessage()); } }