Skip to content

Latest commit

 

History

History
35 lines (24 loc) · 1.54 KB

README.md

File metadata and controls

35 lines (24 loc) · 1.54 KB

CSharpTypePrinter

NuGet Badgefuget.org

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 as Blah<T> instead of Blah<>. The default value is false because of my own use-case of the type inside the typeof() where typeof(Blah<>) is the valid code and the typeof(Blah<T>) is not.

Happy coding!