I want to get a System.Type
given a string
that specifies a (primitive) type\'s C# friendly name, basically the way the C# compiler d
Here's my stab at it. I approached it using two similar libraries:
I think it's pretty clean and straightforward.
Here I'm using Mono's C# compiler-as-a-service, namely the Mono.CSharp.Evaluator class. (It's available as a Nuget package named, unsurprisingly, Mono.CSharp)
using Mono.CSharp;
public static Type GetFriendlyType(string typeName)
{
//this class could use a default ctor with default sensible settings...
var eval = new Mono.CSharp.Evaluator(new CompilerContext(
new CompilerSettings(),
new ConsoleReportPrinter()));
//MAGIC!
object type = eval.Evaluate(string.Format("typeof({0});", typeName));
return (Type)type;
}
Up next: The counterpart from "the friends in building 41" aka Roslyn...
Later:
Roslyn is almost as easy to install - once you figure out what's what. I ended up using Nuget package "Roslyn.Compilers.CSharp" (Or get it as a VS add-in). Just be warned that Roslyn requires a .NET 4.5 project.
The code is even cleaner:
using Roslyn.Scripting.CSharp;
public static Type GetFriendlyType(string typeName)
{
ScriptEngine engine = new ScriptEngine();
var type = engine.CreateSession()
.Execute(string.Format("typeof({0})", typeName));
return type;
}