stakx / TypeNameFormatter

A small .NET library for formatting type names à la C#.
MIT License
33 stars 4 forks source link
csharp dotnet dotnet-standard formatter reflection types

TypeNameFormatter

TypeNameFormatter is a small .NET library for formatting type names à la C#.

NuGet badge AppVeyor AppVeyor tests Codecov

What is this good for?

Have you ever stumbled over the cryptic formatting of Type objects?

var someType = typeof(IEnumerable<int[]>);

Console.WriteLine(someType);
// => System.Collections.Generic.IEnumerable`1[System.Int32[]]

If you'd rather see something that looks more like a C# type name, then this library might be for you:

using TypeNameFormatter;

var someType = typeof(IEnumerable<int[]>);

Console.WriteLine(someType.GetFormattedName());
// => IEnumerable<int[]>

Formatting any Type involves more special cases than you might expect (such as generic types, nested types, multi-dimensional and jagged arrays, by-reference and pointer types). This library deals with all of those, so that you don't have to.

How do I use it?

By importing the TypeNameFormatter namespace, the following extension methods become available:

Both methods allow you to specify any combination of the following TypeNameFormatOptions flags:

But it doesn't format \<some type> correctly!

If you think you've found a bug, please raise an issue so it can be looked into. (Make sure to mention the type that doesn't get formatted as expected.)

Alternatives

Advanced usage

Configuration knobs for the source code distribution

The TypeNameFormatter.Sources NuGet package comes with a few MSBuild properties that you can set inside your project file (inside a <PropertyGroup>):

For example:

<Project …>
  …
  <PropertyGroup>
    <!-- Make TypeNameFormatter's types `public` instead of `internal`: -->
    <TypeNameFormatterInternal>False<TypeNameFormatterInternal>

    <!-- Make a linked file `TypeNameFormatter.cs` show up in Solution Explorer
         under a folder node named `Utilities`: -->
    <TypeNameFormatterProjectNodeName>Utilities\TypeNameFormatter.cs</TypeNameFormatterProjectNodeName>
  </PropertyGroup>
  …
</Project>