Targets .NET Standard 2.0
Prints a System.Type
object as a valid C# literal, e.g. prints typeof(A<X>.B<Y>.C)
as a "A<X>.B<Y>.C"
It happens that the code for this is the complex pile of details especially if we talk about nested generics.
So I wanted to automate it and get and the robust implementation. A similar code is used Today by three of my projects: DryIoc, FastExpressionCompiler, ImTools.
The library contains a single extension method:
public static class TypePrinter
{
public static string ToCSharpCode(this Type type,
bool stripNamespace = false,
Func<Type, string, string> printType = null,
bool printGenericTypeArgs = false)
{
//:-)
}
}
The options include:
stripNamespace
self explanatory.printType
function may configure the final result given the input type and the output string.printGenericTypeArgs
if set to true will output open-generic type asBlah<T>
instead ofBlah<>
. The default value is false because of my own use-case of the type inside thetypeof()
wheretypeof(Blah<>)
is the valid code and thetypeof(Blah<T>)
is not.
Happy coding!