Skip to content

Instantly share code, notes, and snippets.

@jaredpar
Created November 23, 2020 05:23
Show Gist options
  • Select an option

  • Save jaredpar/54158bd254427cd89e27437db3833ba0 to your computer and use it in GitHub Desktop.

Select an option

Save jaredpar/54158bd254427cd89e27437db3833ba0 to your computer and use it in GitHub Desktop.
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System;
using System.Linq;
var code = @"
using System;
#nullable enable
class C<T>
{
void M(C<int> p1, C<string?> p2, C<object?>? p3, object? p4) { }
}";
var syntaxTree = CSharpSyntaxTree.ParseText(code);
var compilation = CSharpCompilation.Create(
"example.dll",
new[] { syntaxTree },
new[] { MetadataReference.CreateFromFile(@"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\mscorlib.dll") });
var semanticModel = compilation.GetSemanticModel(syntaxTree);
var format = SymbolDisplayFormat
.FullyQualifiedFormat
.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier);
foreach (var paramNode in syntaxTree.GetRoot().DescendantNodes().OfType<ParameterSyntax>())
{
if (semanticModel.GetSymbolInfo(paramNode.Type).Symbol is { } symbol)
{
Console.WriteLine(symbol.ToDisplayString(format));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment