Skip to content

Instantly share code, notes, and snippets.

@jmarolf
Last active June 5, 2017 17:19
Show Gist options
  • Save jmarolf/57352bac8d3f20cf47249e00fb48a8ea to your computer and use it in GitHub Desktop.
Save jmarolf/57352bac8d3f20cf47249e00fb48a8ea to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
namespace GetTypeName
{
class Program
{
static void Main(string[] args)
{
var str = GetFullName(typeof(List<int>));
Console.WriteLine(str);
}
private static string GetFullName(Type type)
{
var reference = MetadataReference.CreateFromFile(type.Assembly.Location);
var mscorlb = MetadataReference.CreateFromFile(typeof(Object).Assembly.Location);
var compilation = CSharpCompilation.Create("test", references: new[] { reference, mscorlb });
if (type.IsConstructedGenericType)
{
var def = type.GetGenericTypeDefinition();
var args = type.GetGenericArguments();
var namedType = compilation.GetTypeByMetadataName(def.FullName);
var typeArguments = args.Select(a
=> compilation.GetTypeByMetadataName(a.FullName)).ToArray();
var constructedNamedType = namedType.Construct(typeArguments);
return constructedNamedType.ToDisplayString();
}
else
{
var namedType = compilation.GetTypeByMetadataName(type.FullName);
return namedType.ToDisplayString();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment