Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A sample application to retrieve all diagnostics related to the nullability
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Threading;
using Microsoft.CodeAnalysis.Diagnostics;
namespace TestNonNullableReferences
{
class Program
{
static void Main(string[] args)
{
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
var assemblyWithAnalyzers = GetAssembliesWithAnalyzers();
var output = new List<string>();
output.Add("|Code|Title|");
output.Add("|---|----|");
foreach (var (id, title) in GetAllRules(assemblyWithAnalyzers))
{
if (title.Contains("null", StringComparison.InvariantCultureIgnoreCase))
{
output.Add($"|{id}|{title}|");
}
}
File.WriteAllLines(@"rules.md", output);
}
private static IEnumerable<Assembly> GetAssembliesWithAnalyzers()
{
yield return typeof(Microsoft.CodeAnalysis.CSharp.CSharpCompilation).Assembly;
}
private static IEnumerable<(string? id, string title)> GetAllRules(IEnumerable<Assembly> assembliesWithAnalyzers)
{
foreach (var assemblyWithAnalyzers in assembliesWithAnalyzers)
{
var types = assemblyWithAnalyzers.GetTypes();
var baseType = typeof(DiagnosticAnalyzer);
foreach (var type in types)
{
if (baseType.IsAssignableFrom(type))
{
var instance = Activator.CreateInstance(type) as DiagnosticAnalyzer;
foreach (var diagnostic in instance.SupportedDiagnostics)
{
var title = diagnostic.Title?.ToString();
if (title!=null && string.IsNullOrWhiteSpace(title) == false)
{
yield return (diagnostic.Id, title);
}
}
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment